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

Open
wants to merge 2 commits into
base: 3.1.0-eap
Choose a base branch
from

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
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.

2 participants