Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,26 @@ import kotlinx.coroutines.NonDisposableHandle
import kotlinx.coroutines.delay
import net.bladehunt.kotstom.SchedulerManager
import net.minestom.server.MinecraftServer
import net.minestom.server.timer.Schedulable
import net.minestom.server.timer.Scheduler
import net.minestom.server.timer.TaskSchedule
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, 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.
* A `CoroutineDispatcher` that runs coroutines when [scheduler] processes its next tick. Delays and
* timeouts are counted in whole ticks, rounding up, so they only advance while [scheduler] is being
* ticked. Coroutines on the scheduler of a removed entity or unregistered instance never resume.
* 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
abstract class SchedulerDispatcher : CoroutineDispatcher(), Delay {
abstract val scheduler: Scheduler

override fun dispatch(context: CoroutineContext, block: Runnable) {
SchedulerManager.execute(block)
scheduler.execute(block)
}

override fun scheduleResumeAfterDelay(
Expand All @@ -48,15 +50,48 @@ object MinestomDispatcher : CoroutineDispatcher(), Delay {
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()
val scheduled = scheduler.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()
}
}

// Equal dispatchers let withContext between them skip the extra tick
override fun equals(other: Any?): Boolean = other is SchedulerDispatcher && other.scheduler === scheduler

override fun hashCode(): Int = System.identityHashCode(scheduler)

override fun toString(): String = "SchedulerDispatcher[$scheduler]"

companion object {
/** 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
}
}

/**
* The [SchedulerDispatcher] for the server's `SchedulerManager`, running coroutines at the start of
* server ticks
*
* @author oglassdev
*/
object MinestomDispatcher : SchedulerDispatcher() {
override val scheduler: Scheduler
get() = SchedulerManager

override fun toString(): String = "MinestomDispatcher"
}

/** Returns a [SchedulerDispatcher] that runs coroutines and counts delays on this scheduler's ticks */
fun Scheduler.asCoroutineDispatcher(): SchedulerDispatcher = ScheduledDispatcher(this)

/** Returns a [SchedulerDispatcher] for this entity's or instance's own scheduler */
fun Schedulable.asCoroutineDispatcher(): SchedulerDispatcher = scheduler().asCoroutineDispatcher()

private class ScheduledDispatcher(override val scheduler: Scheduler) : SchedulerDispatcher()

internal class ReleasingTask(@Volatile var block: Runnable?) : Runnable {
override fun run() {
block?.run()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import net.bladehunt.kotstom.SchedulerManager
import net.bladehunt.kotstom.coroutines.MinestomDispatcher
import net.bladehunt.kotstom.coroutines.asCoroutineDispatcher
import net.bladehunt.kotstom.coroutines.delayTicks
import net.bladehunt.kotstom.extension.await
import net.minestom.server.timer.Scheduler
import net.minestom.server.timer.TaskSchedule

private fun tick() {
Expand Down Expand Up @@ -75,4 +77,16 @@ class MinestomDispatcherTest :
repeat(25) { tick() }
resumed shouldBe false
}

test("custom schedulers only advance when ticked") {
val scheduler = Scheduler.newScheduler()
val job = scope.launch(scheduler.asCoroutineDispatcher(), CoroutineStart.UNDISPATCHED) { delayTicks(2) }
repeat(5) { tick() }
job.isActive shouldBe true
repeat(2) { scheduler.processTick() }
job.isCompleted shouldBe true

scheduler.asCoroutineDispatcher() shouldBe scheduler.asCoroutineDispatcher()
SchedulerManager.asCoroutineDispatcher() shouldBe MinestomDispatcher
}
})
Loading