proposal-cancellation icon indicating copy to clipboard operation
proposal-cancellation copied to clipboard

Integration with explicit resource management?

Open dead-claudia opened this issue 1 year ago • 0 comments

Tying this with explicit resource management would be extremely valuable for plugging resource leaks, for cases where cancellation simply causes a promise to not settle.

Precedent goes two ways:

  1. Throwing a specific "cancelled" exception, indirectly triggering disposal callbacks/methods as the exception propagates: C#, most JDK languages
  2. Disposing directly as part of cancellation. Rust and C++ userland libraries take this approach, modeling cancellation as dropping the relevant token.

I'm imagining a variation of 2:

  • An internal async context variable exists to return the current cancel token. This can and should be exposed, both get and scoped update, in some way.
  • When using is evaluated, it implicitly subscribes to the current cancel token, if available. On block exit, that implicit subscription is terminated. Ideally, a single shared subscription should be used for all active using resources in a function, and it should just use a list.
    • Implementations can know this list's max size statically if no eval is present, as at most one slot can be alive per using. This can be leveraged by both transpilers and engines.
    • Function granularity is the most natural point of sharing for this. Anything more can't be statically analyzed and requires special runtime support, and anything less doesn't capture the optimization potential available.
  • The same cleanup steps would be performed both by block exit and cancellation. Only the first of the two would execute in this case.

dead-claudia avatar May 18 '24 20:05 dead-claudia