diff --git a/build.gradle.kts b/build.gradle.kts index e7276fa..6991d80 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -14,6 +14,7 @@ dependencies { testImplementation(libs.minestom) testImplementation(libs.adventure.minimessage) testImplementation(libs.bundles.test) + testImplementation(libs.kotlinx.coroutines) } java { withSourcesJar() } diff --git a/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt b/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt index ee3031c..05cae23 100644 --- a/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt +++ b/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt @@ -1,20 +1,31 @@ package net.bladehunt.kotstom.coroutines -import kotlin.coroutines.CoroutineContext -import kotlin.coroutines.resume -import kotlinx.coroutines.* +import kotlinx.coroutines.CancellableContinuation +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Delay +import kotlinx.coroutines.DisposableHandle +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.InternalCoroutinesApi +import kotlinx.coroutines.NonDisposableHandle +import kotlinx.coroutines.delay import net.bladehunt.kotstom.SchedulerManager -import net.bladehunt.kotstom.dsl.scheduleTask +import net.minestom.server.MinecraftServer import net.minestom.server.timer.TaskSchedule +import kotlin.coroutines.CoroutineContext /** - * A `CoroutineDispatcher` that uses Minestom's SchedulerManager to schedule tasks. Note: These are - * not properly 'asynchronous.' If you need async, use Dispatchers.default. + * A `CoroutineDispatcher` that runs coroutines at the start of Minestom ticks using the + * `SchedulerManager`. Delays and timeouts are counted in whole ticks, rounding up, so they only + * advance while the server is ticking. Delays longer than [MAX_DELAY_TICKS] never resume. Note: + * These are not properly 'asynchronous.' If you need async, use Dispatchers.Default. * * @author oglassdev */ -@OptIn(InternalCoroutinesApi::class) +@OptIn(InternalCoroutinesApi::class, ExperimentalCoroutinesApi::class) object MinestomDispatcher : CoroutineDispatcher(), Delay { + /** Minestom stores task deadlines as an `Int` tick, so longer delays are treated as infinite */ + const val MAX_DELAY_TICKS: Long = Int.MAX_VALUE / 2L + override fun dispatch(context: CoroutineContext, block: Runnable) { SchedulerManager.execute(block) } @@ -23,9 +34,38 @@ object MinestomDispatcher : CoroutineDispatcher(), Delay { timeMillis: Long, continuation: CancellableContinuation ) { - SchedulerManager.scheduleTask( - delay = TaskSchedule.millis(timeMillis), repeat = TaskSchedule.stop()) { - continuation.resume(Unit) - } + val handle = schedule(timeMillis) { with(continuation) { resumeUndispatched(Unit) } } + continuation.invokeOnCancellation { handle.dispose() } + } + + override fun invokeOnTimeout( + timeMillis: Long, + block: Runnable, + context: CoroutineContext + ): DisposableHandle = schedule(timeMillis, block) + + private fun schedule(timeMillis: Long, block: Runnable): DisposableHandle { + val ticks = timeMillis / MinecraftServer.TICK_MS + if (timeMillis % MinecraftServer.TICK_MS == 0L) 0 else 1 + if (ticks > MAX_DELAY_TICKS) return NonDisposableHandle + val task = ReleasingTask(block) + val scheduled = SchedulerManager.buildTask(task).delay(TaskSchedule.tick(ticks.coerceAtLeast(1).toInt())).schedule() + return DisposableHandle { + // Cancelled tasks stay queued until their tick, so release the block now + task.block = null + scheduled.cancel() + } } } + +internal class ReleasingTask(@Volatile var block: Runnable?) : Runnable { + override fun run() { + block?.run() + } +} + +/** + * Delays the coroutine for [ticks] server ticks + * + * @author oglassdev + */ +suspend fun delayTicks(ticks: Int) = delay(ticks.toLong() * MinecraftServer.TICK_MS) diff --git a/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt b/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt index 007d636..68584fe 100644 --- a/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt +++ b/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt @@ -1,7 +1,8 @@ package net.bladehunt.kotstom.extension +import kotlinx.coroutines.suspendCancellableCoroutine +import net.bladehunt.kotstom.coroutines.ReleasingTask import kotlin.coroutines.resume -import kotlin.coroutines.suspendCoroutine import net.minestom.server.timer.ExecutionType import net.minestom.server.timer.Schedulable import net.minestom.server.timer.Scheduler @@ -11,8 +12,13 @@ import net.minestom.server.timer.TaskSchedule suspend fun Scheduler.await( delay: TaskSchedule, executionType: ExecutionType = ExecutionType.TICK_START -) = suspendCoroutine { - this.buildTask { it.resume(Unit) }.delay(delay).executionType(executionType).schedule() +): Unit = suspendCancellableCoroutine { continuation -> + val resume = ReleasingTask { continuation.resume(Unit) } + val task = buildTask(resume).delay(delay).executionType(executionType).schedule() + continuation.invokeOnCancellation { + resume.block = null + task.cancel() + } } /** Suspends a coroutine until a delay is met */ diff --git a/src/test/kotlin/net/bladehunt/kotstom/test/MinestomDispatcherTest.kt b/src/test/kotlin/net/bladehunt/kotstom/test/MinestomDispatcherTest.kt new file mode 100644 index 0000000..106ca7d --- /dev/null +++ b/src/test/kotlin/net/bladehunt/kotstom/test/MinestomDispatcherTest.kt @@ -0,0 +1,78 @@ +package net.bladehunt.kotstom.test + +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import net.bladehunt.kotstom.SchedulerManager +import net.bladehunt.kotstom.coroutines.MinestomDispatcher +import net.bladehunt.kotstom.coroutines.delayTicks +import net.bladehunt.kotstom.extension.await +import net.minestom.server.timer.TaskSchedule + +private fun tick() { + SchedulerManager.processTick() + SchedulerManager.processTickEnd() +} + +private fun ticksUntilDone(job: Job, max: Int = 10): Int { + var ticks = 0 + while (!job.isCompleted && ticks < max) { + tick() + ticks++ + } + return ticks +} + +class MinestomDispatcherTest : + FunSpec({ + beforeSpec { SERVER } + + val scope = CoroutineScope(SupervisorJob()) + afterSpec { scope.cancel() } + + fun launch(block: suspend CoroutineScope.() -> Unit) = + scope.launch(MinestomDispatcher, CoroutineStart.UNDISPATCHED, block) + + test("delays round up to whole ticks") { + ticksUntilDone(launch { delay(1) }) shouldBe 1 + ticksUntilDone(launch { delay(50) }) shouldBe 1 + ticksUntilDone(launch { delay(51) }) shouldBe 2 + ticksUntilDone(launch { delayTicks(3) }) shouldBe 3 + } + + test("withTimeoutOrNull times out") { + var result: Any? = "pending" + val job = launch { result = withTimeoutOrNull(100) { awaitCancellation() } } + ticksUntilDone(job) shouldBe 3 + result shouldBe null + } + + test("huge delays never fire") { + val jobs = listOf(launch { delay(Long.MAX_VALUE - 1) }, launch { delayTicks(Int.MAX_VALUE) }) + repeat(5) { tick() } + jobs.forEach { it.isActive shouldBe true } + jobs.forEach { it.cancel() } + } + + test("cancelled delay and await complete without resuming") { + var resumed = false + val jobs = + listOf( + launch { delay(1_000).also { resumed = true } }, + launch { SchedulerManager.await(TaskSchedule.tick(20)).also { resumed = true } }, + ) + jobs.forEach { it.cancel() } + tick() + jobs.forEach { it.isCompleted shouldBe true } + repeat(25) { tick() } + resumed shouldBe false + } + })