Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KTOR-7845 Fix for threading issue in flushAndClose for reader job channels #4503

Merged
merged 2 commits into from
Nov 27, 2024

Conversation

bjhham
Copy link
Contributor

@bjhham bjhham commented Nov 25, 2024

Subsystem
Core, I/O

Motivation
KTOR-7845 File is not commited after closing writeChannel() of the file

Solution
The problem here is that flushAndClose() doesn't wait for the ReaderJob to finish so it has no effect on the final destination of the data. By adding a hook to wait for the job to complete, we can daisy chain these jobs with some trust that flushAndClose() will work properly from the perspective of the caller.

For reference, here is the writeChannel utility function:

@OptIn(DelicateCoroutinesApi::class)
public fun File.writeChannel(
    coroutineContext: CoroutineContext = Dispatchers.IO
): ByteWriteChannel = GlobalScope.reader(CoroutineName("file-writer") + coroutineContext, autoFlush = true) {
    @Suppress("BlockingMethodInNonBlockingContext")
    RandomAccessFile(this@writeChannel, "rw").use { file ->
        val copied = channel.copyTo(file.channel)
        file.setLength(copied) // truncate tail that could remain from the previously written data
    }
}.channel

@bjhham bjhham requested a review from e5l November 25, 2024 10:19
Copy link
Member

@e5l e5l left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please change the target branch to 3.1.0

@bjhham bjhham changed the base branch from main to 3.1.0-eap November 25, 2024 14:36
@bjhham bjhham force-pushed the bjhham/file-write-channel-fix branch from 906c159 to 18aeee9 Compare November 25, 2024 14:38
@bjhham bjhham requested a review from e5l November 25, 2024 16:20
* Use stdlib `use` extension-function
* Update type checks
@bjhham bjhham force-pushed the bjhham/file-write-channel-fix branch from 06be3d9 to 3e3d808 Compare November 27, 2024 16:16
@bjhham bjhham force-pushed the bjhham/file-write-channel-fix branch from 3e3d808 to b0fcd93 Compare November 27, 2024 16:21
@bjhham bjhham merged commit bc68267 into 3.1.0-eap Nov 27, 2024
13 of 14 checks passed
@bjhham bjhham deleted the bjhham/file-write-channel-fix branch November 27, 2024 18:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants