Skip to content

feat(coroutines): let async handlers and commands be cancelled with their owner - #26

Draft
oglassdev wants to merge 1 commit into
mainfrom
feat/scoped-async-handlers
Draft

oglassdev wants to merge 1 commit into
mainfrom
feat/scoped-async-handlers

Conversation

@oglassdev

Copy link
Copy Markdown
Owner

asyncHandler, executorAsync and defaultExecutorAsync launch with CoroutineScope(context).launch, which creates a fresh scope nothing holds on to. Their coroutines can't be cancelled. In the example's /suspending command, a player who quits mid-loop keeps getting messages sent for the remaining ~9 seconds, and a minigame that ends can't stop its handlers. Failures also skip Minestom's ExceptionManager.

This adds an overload of each that takes the scope that owns the work:

class Minigame : CoroutineScope by CoroutineScope(MinestomDispatcher) {
    fun setup() {
        node.builder<PlayerMoveEvent> { asyncHandler(this@Minigame) { ... } }
        kommand("leave") { buildSyntax { executorAsync(this@Minigame) { sender -> ... } } }
    }
    fun end() = cancel()   // stops every handler and command launched above
}

All async variants, new and existing, now catch failures and report them to ExceptionManager.handleException, the way Minestom's own listeners behave. Without that, one throwing handler would cancel a user's plain-Job scope and silently kill every other handler running in it.

Why not context parameters

A context(scope: CoroutineScope) overload with the same name was the first idea. Testing showed Kotlin silently picks it whenever any scope is available, including inside runBlocking { } or launch { }. That would quietly make existing handlers children of whatever coroutine registered them. An explicit parameter can't change existing call sites.

Open questions (why this is a draft)

  • Additive vs. required: this keeps the unscoped CoroutineContext overloads. Removing them (breaking) would force every async handler to have an owner.
  • Exception routing for the existing overloads: failures that used to go to the coroutine default handler now go to ExceptionManager. That's arguably a fix, but it's a behavior change.

Testing

  • New CoroutineEventsTest: a failing handler leaves its scope active, and cancelling the scope cancels running handlers. With exception routing turned off, the first test fails, so it does guard the fix.
  • compileKotlin, compileTestKotlin and :example:compileKotlin pass.

…ned scope

Add asyncHandler, executorAsync and defaultExecutorAsync overloads that
take a CoroutineScope, so cancelling that scope stops their coroutines.
All async variants now report failures to Minestom's ExceptionManager
instead of letting one failing handler cancel the scope it runs in.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant