package eu.friedcutlet.yokan.services import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.job import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext /** * `runBlocking` for call sites that must bridge into suspending code from a * synchronous context (extension bridge callbacks, startup checks). JVM and * native targets delegate to `kotlinx.coroutines.runBlocking`; the browser * cannot block its single thread, so the wasm actual throws * [UnsupportedOperationException] — callers already wrap these paths in * `runCatching` and degrade gracefully. A [kotlinx.coroutines.Job] in [context] * makes the blocked work its child, so cancelling that job cancels the work. */ expect fun runBlockingCompat( context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T, ): T /** * Dispatcher for work that blocks its thread (extension engines and their synchronous host * bridges): `Dispatchers.IO` where the platform has one, `Dispatchers.Default` in the browser. */ expect val blockingDispatcher: CoroutineDispatcher /** * [runCatching] for suspending work: failures become [Result.failure], but * [kotlinx.coroutines.CancellationException] is rethrown so cancellation still * propagates to the caller's scope. */ inline fun catchingNonCancellation(block: () -> T): Result = try { Result.success(block()) } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled } catch (failure: Throwable) { Result.failure(failure) } /** * Runs [action] as a child of this owner scope and joins it before returning, so the work never * outlives the owner: cancelling the caller or the owner cancels the work, and the caller resumes * only after the work's finalizers have finished. [admit] runs before dispatch and throws to * reject the call. A result produced after the call or the owner was cancelled is discarded, * because a delegate may swallow cancellation or return from a `NonCancellable` finalizer. */ internal suspend fun CoroutineScope.runJoined( context: CoroutineContext = EmptyCoroutineContext, admit: () -> Unit = {}, action: suspend (callJob: Job) -> T, ): T { // An expired caller must not dispatch even when the owner's dispatcher is immediate. currentCoroutineContext().ensureActive() admit() ensureActive() val work = async(context) { val callJob = currentCoroutineContext().job callJob.ensureActive() action(callJob).also { callJob.ensureActive() this@runJoined.ensureActive() } } return try { work.await() } finally { withContext(NonCancellable) { work.cancelAndJoin() } } }