From e637c4a68ad09ca60b2c0a7644fc3460ff0e0cac Mon Sep 17 00:00:00 2001 From: Rustam Date: Mon, 14 Aug 2023 10:31:08 +0200 Subject: [PATCH] KTOR-6147 Darwin: App hangs when streaming request without connection (#3720) (cherry picked from commit c75fce9bdd7ee01ba5eb46fce66c8022afb8dd50) --- .../io/ktor/client/engine/darwin/DarwinUtils.kt | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/DarwinUtils.kt b/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/DarwinUtils.kt index b3008d0203c..886ae93ddfc 100644 --- a/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/DarwinUtils.kt +++ b/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/DarwinUtils.kt @@ -9,13 +9,10 @@ import io.ktor.client.engine.* import io.ktor.http.content.* import io.ktor.util.* import io.ktor.utils.io.* -import io.ktor.utils.io.core.* import io.ktor.utils.io.errors.* import kotlinx.cinterop.* -import kotlinx.cinterop.ByteVar import kotlinx.coroutines.* import platform.Foundation.* -import platform.darwin.* import platform.posix.* @OptIn(DelicateCoroutinesApi::class, UnsafeNumber::class, InternalAPI::class) @@ -53,10 +50,19 @@ internal suspend fun OutgoingContent.toDataOrStream(): Any? { var offset = 0 val read = channel.readAvailable(buffer, 0, 4096) while (offset < read) { + while (!outputStream.hasSpaceAvailable) { + yield() + } @Suppress("UNCHECKED_CAST") val written = outputStream - .write(buffer.plus(offset) as CPointer, (read - offset).convert()).convert() + .write(buffer.plus(offset) as CPointer, (read - offset).convert()) + .convert() offset += written + if (written < 0) { + throw outputStream.streamError?.let { DarwinHttpRequestException(it) } + ?: inputStream.streamError?.let { DarwinHttpRequestException(it) } + ?: IOException("Failed to write to the network") + } } } }