From b181a4f78a67c57ac5c2ba679a39ea77276873d8 Mon Sep 17 00:00:00 2001 From: oglassdev <23040613+oglassdev@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:56:48 -0400 Subject: [PATCH 1/5] fix(coroutines): count MinestomDispatcher delays in ticks and stop depending on Delay defaults Implement every Delay member MinestomDispatcher relies on, so it no longer calls interface default bodies that only exist in some kotlinx.coroutines versions (withTimeout hung forever on 1.10.2). Delays and timeouts are scheduled in whole ticks, rounding up, resume without an extra tick hop, and release their continuation when cancelled. Scheduler.await is now cancellable, delayTicks is added, and tests run against the coroutines version the library compiles with. --- build.gradle.kts | 1 + .../kotstom/coroutines/MinestomDispatcher.kt | 61 +++++++++++++++---- .../kotstom/extension/SchedulerExt.kt | 7 ++- 3 files changed, 55 insertions(+), 14 deletions(-) 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..5f56730 100644 --- a/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt +++ b/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt @@ -1,19 +1,25 @@ 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.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. 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 { override fun dispatch(context: CoroutineContext, block: Runnable) { SchedulerManager.execute(block) @@ -23,9 +29,42 @@ object MinestomDispatcher : CoroutineDispatcher(), Delay { timeMillis: Long, continuation: CancellableContinuation ) { - SchedulerManager.scheduleTask( - delay = TaskSchedule.millis(timeMillis), repeat = TaskSchedule.stop()) { - continuation.resume(Unit) - } + val resume = ResumeTask(continuation) + val task = SchedulerManager.buildTask(resume).delay(ticksFor(timeMillis)).schedule() + continuation.invokeOnCancellation { + // Cancelled tasks stay queued until their tick, so release the continuation now + resume.continuation = null + task.cancel() + } + } + + override fun invokeOnTimeout( + timeMillis: Long, + block: Runnable, + context: CoroutineContext + ): DisposableHandle { + val task = SchedulerManager.buildTask(block).delay(ticksFor(timeMillis)).schedule() + return DisposableHandle { task.cancel() } + } + + @Deprecated("Not called by kotlinx.coroutines", level = DeprecationLevel.HIDDEN) + override suspend fun delay(time: Long) = kotlinx.coroutines.delay(time) + + private fun ticksFor(timeMillis: Long): TaskSchedule { + val ticks = timeMillis / MinecraftServer.TICK_MS + if (timeMillis % MinecraftServer.TICK_MS == 0L) 0 else 1 + return TaskSchedule.tick(ticks.coerceIn(1, Int.MAX_VALUE.toLong()).toInt()) + } + + private class ResumeTask(@Volatile var continuation: CancellableContinuation?) : Runnable { + override fun run() { + continuation?.run { resumeUndispatched(Unit) } + } } } + +/** + * 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..adc0688 100644 --- a/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt +++ b/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt @@ -1,7 +1,7 @@ package net.bladehunt.kotstom.extension +import kotlinx.coroutines.suspendCancellableCoroutine 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 +11,9 @@ 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 task = buildTask { continuation.resume(Unit) }.delay(delay).executionType(executionType).schedule() + continuation.invokeOnCancellation { task.cancel() } } /** Suspends a coroutine until a delay is met */ From 8f46c8abf9bde044a112fa285a02d696eeb1f2d2 Mon Sep 17 00:00:00 2001 From: oglassdev <23040613+oglassdev@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:12:08 -0400 Subject: [PATCH 2/5] refactor(coroutines): drop the delay override kept only for older coroutines KotStom targets the kotlinx.coroutines version it compiles against. --- .../net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt b/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt index 5f56730..2add3c0 100644 --- a/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt +++ b/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt @@ -47,9 +47,6 @@ object MinestomDispatcher : CoroutineDispatcher(), Delay { return DisposableHandle { task.cancel() } } - @Deprecated("Not called by kotlinx.coroutines", level = DeprecationLevel.HIDDEN) - override suspend fun delay(time: Long) = kotlinx.coroutines.delay(time) - private fun ticksFor(timeMillis: Long): TaskSchedule { val ticks = timeMillis / MinecraftServer.TICK_MS + if (timeMillis % MinecraftServer.TICK_MS == 0L) 0 else 1 return TaskSchedule.tick(ticks.coerceIn(1, Int.MAX_VALUE.toLong()).toInt()) From 183d6032554dd00733254c250676c0fc309d1a79 Mon Sep 17 00:00:00 2001 From: oglassdev <23040613+oglassdev@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:17:58 -0400 Subject: [PATCH 3/5] fix(coroutines): release cancelled delays, timeouts and awaits eagerly and treat overflowing delays as infinite --- .../kotstom/coroutines/MinestomDispatcher.kt | 42 ++++++++++--------- .../kotstom/extension/SchedulerExt.kt | 9 +++- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt b/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt index 2add3c0..05cae23 100644 --- a/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt +++ b/src/main/kotlin/net/bladehunt/kotstom/coroutines/MinestomDispatcher.kt @@ -6,6 +6,7 @@ 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.minestom.server.MinecraftServer @@ -14,13 +15,17 @@ import kotlin.coroutines.CoroutineContext /** * A `CoroutineDispatcher` that runs coroutines at the start of Minestom ticks using the - * `SchedulerManager`. Delays and timeouts are counted in whole ticks, rounding up. Note: These are - * not properly 'asynchronous.' If you need async, use Dispatchers.Default. + * `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, 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) } @@ -29,33 +34,32 @@ object MinestomDispatcher : CoroutineDispatcher(), Delay { timeMillis: Long, continuation: CancellableContinuation ) { - val resume = ResumeTask(continuation) - val task = SchedulerManager.buildTask(resume).delay(ticksFor(timeMillis)).schedule() - continuation.invokeOnCancellation { - // Cancelled tasks stay queued until their tick, so release the continuation now - resume.continuation = null - task.cancel() - } + val handle = schedule(timeMillis) { with(continuation) { resumeUndispatched(Unit) } } + continuation.invokeOnCancellation { handle.dispose() } } override fun invokeOnTimeout( timeMillis: Long, block: Runnable, context: CoroutineContext - ): DisposableHandle { - val task = SchedulerManager.buildTask(block).delay(ticksFor(timeMillis)).schedule() - return DisposableHandle { task.cancel() } - } + ): DisposableHandle = schedule(timeMillis, block) - private fun ticksFor(timeMillis: Long): TaskSchedule { + private fun schedule(timeMillis: Long, block: Runnable): DisposableHandle { val ticks = timeMillis / MinecraftServer.TICK_MS + if (timeMillis % MinecraftServer.TICK_MS == 0L) 0 else 1 - return TaskSchedule.tick(ticks.coerceIn(1, Int.MAX_VALUE.toLong()).toInt()) + 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() + } } +} - private class ResumeTask(@Volatile var continuation: CancellableContinuation?) : Runnable { - override fun run() { - continuation?.run { resumeUndispatched(Unit) } - } +internal class ReleasingTask(@Volatile var block: Runnable?) : Runnable { + override fun run() { + block?.run() } } diff --git a/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt b/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt index adc0688..68584fe 100644 --- a/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt +++ b/src/main/kotlin/net/bladehunt/kotstom/extension/SchedulerExt.kt @@ -1,6 +1,7 @@ package net.bladehunt.kotstom.extension import kotlinx.coroutines.suspendCancellableCoroutine +import net.bladehunt.kotstom.coroutines.ReleasingTask import kotlin.coroutines.resume import net.minestom.server.timer.ExecutionType import net.minestom.server.timer.Schedulable @@ -12,8 +13,12 @@ suspend fun Scheduler.await( delay: TaskSchedule, executionType: ExecutionType = ExecutionType.TICK_START ): Unit = suspendCancellableCoroutine { continuation -> - val task = buildTask { continuation.resume(Unit) }.delay(delay).executionType(executionType).schedule() - continuation.invokeOnCancellation { task.cancel() } + 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 */ From 4542516585b00313d11528163c372c0d40cfb8e4 Mon Sep 17 00:00:00 2001 From: oglassdev <23040613+oglassdev@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:25:41 -0400 Subject: [PATCH 4/5] test(coroutines): cover MinestomDispatcher tick rounding, timeouts, overflow and cancellation --- .../kotstom/test/MinestomDispatcherTest.kt | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/test/kotlin/net/bladehunt/kotstom/test/MinestomDispatcherTest.kt 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..e85308b --- /dev/null +++ b/src/test/kotlin/net/bladehunt/kotstom/test/MinestomDispatcherTest.kt @@ -0,0 +1,77 @@ +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() } + repeat(25) { tick() } + jobs.forEach { it.isCompleted shouldBe true } + resumed shouldBe false + } + }) From 9d82c1c495e40dd9ab8d6408f740ee5609462ab7 Mon Sep 17 00:00:00 2001 From: oglassdev <23040613+oglassdev@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:34:09 -0400 Subject: [PATCH 5/5] test(coroutines): assert cancellation completes after one tick --- .../net/bladehunt/kotstom/test/MinestomDispatcherTest.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/kotlin/net/bladehunt/kotstom/test/MinestomDispatcherTest.kt b/src/test/kotlin/net/bladehunt/kotstom/test/MinestomDispatcherTest.kt index e85308b..106ca7d 100644 --- a/src/test/kotlin/net/bladehunt/kotstom/test/MinestomDispatcherTest.kt +++ b/src/test/kotlin/net/bladehunt/kotstom/test/MinestomDispatcherTest.kt @@ -70,8 +70,9 @@ class MinestomDispatcherTest : launch { SchedulerManager.await(TaskSchedule.tick(20)).also { resumed = true } }, ) jobs.forEach { it.cancel() } - repeat(25) { tick() } + tick() jobs.forEach { it.isCompleted shouldBe true } + repeat(25) { tick() } resumed shouldBe false } })