Fix blocking calls in suspend contexts

This commit is contained in:
Him188 2021-01-26 13:38:23 +08:00
parent 63860f9ab7
commit 8ad0b91974
3 changed files with 19 additions and 12 deletions

View File

@ -195,7 +195,6 @@ public interface ExternalResource : Closeable {
): MessageReceipt<C> =
runBIO {
// toExternalResource throws IOException however we're in BIO context so not propagating IOException to sendAsImageTo
@Suppress("BlockingMethodInNonBlockingContext")
toExternalResource(formatName)
}.withUse { sendAsImageTo(contact) }
@ -239,7 +238,6 @@ public interface ExternalResource : Closeable {
@JvmOverloads
public suspend fun InputStream.uploadAsImage(contact: Contact, formatName: String? = null): Image =
// toExternalResource throws IOException however we're in BIO context so not propagating IOException to sendAsImageTo
@Suppress("BlockingMethodInNonBlockingContext")
runBIO { toExternalResource(formatName) }.withUse { uploadAsImage(contact) }
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2019-2020 Mamoe Technologies and contributors.
* Copyright 2019-2021 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
@ -14,8 +14,20 @@ package net.mamoe.mirai.utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.withContext
@Suppress("unused", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "DeprecatedCallableAddReplaceWith")
@Deprecated(
message = "Use runBIO which delegates to `runInterruptible`. " +
"Technically remove suspend call in `block` and remove CoroutineScope parameter usages.",
level = DeprecationLevel.WARNING
)
@kotlin.internal.LowPriorityInOverloadResolution
public suspend inline fun <R> runBIO(
noinline block: suspend CoroutineScope.() -> R
): R = withContext(Dispatchers.IO, block)
): R = withContext(Dispatchers.IO, block)
public suspend inline fun <R> runBIO(
noinline block: () -> R
): R = runInterruptible(context = Dispatchers.IO, block = block)

View File

@ -25,15 +25,12 @@ internal class ChunkedFlowSession<T>(
private var offset = 0L
@Suppress("BlockingMethodInNonBlockingContext")
internal suspend inline fun useAll(crossinline block: suspend (T) -> Unit) = withUse {
runBIO {
while (true) {
val size = input.read(buffer)
if (size == -1) return@runBIO
block(mapper(buffer, size, offset))
offset += size
}
while (true) {
val size = runBIO { input.read(buffer) }
if (size == -1) return
block(mapper(buffer, size, offset))
offset += size
}
}
}