@file:OptIn(ExperimentalCoroutinesApi::class, kotlinx.cinterop.BetaInteropApi::class) package eu.friedcutlet.yokan.services.extensions.js import kotlinx.cinterop.autoreleasepool import kotlinx.coroutines.CloseableCoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Runnable import platform.Foundation.NSCondition import platform.Foundation.NSThread import kotlin.coroutines.CoroutineContext // zipline builds QuickJS for Kotlin/Native without optimization, so one JS call costs ~22 KiB of // native stack here versus ~1 KiB on the JVM; 128 MiB buys ~5,900 levels (8 MiB would be ~370). // Stack pages are only committed as deep JS actually touches them. internal actual const val QuickJsMaxStackSizeBytes: Long = 128L * 1024L * 1024L // Kotlin/Native workers (newSingleThreadContext) run on default 512 KiB pthread stacks, far below the // QuickJS limit, so each engine gets an NSThread with an explicit stack size instead. internal actual fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher = NSThreadDispatcher(stackBytes) private class NSThreadDispatcher(stackBytes: Long) : CloseableCoroutineDispatcher() { private val condition = NSCondition() private val tasks = ArrayDeque() private var closed = false init { NSThread { runTasks() }.apply { name = "quickjs" stackSize = stackBytes.toULong() start() } } override fun dispatch(context: CoroutineContext, block: Runnable) { condition.lock() val accepted = !closed if (accepted) { tasks.addLast(block) condition.signal() } condition.unlock() // Like a shut-down JVM executor: late continuations (cancelled zipline jobs) finish elsewhere. if (!accepted) Dispatchers.Default.dispatch(context, block) } /** Lets the thread finish the queued tasks, then exit. */ override fun close() { condition.lock() closed = true condition.signal() condition.unlock() } private fun runTasks() { while (true) { condition.lock() while (tasks.isEmpty() && !closed) condition.wait() val task = tasks.removeFirstOrNull() condition.unlock() if (task == null) return // Host bridge calls create Objective-C objects; this thread has no run loop to drain them. autoreleasepool { task.run() } } } }