M4 executors: coroutine executor, tasks, timers, test dispatcher, AsyncApp
- executor: coroutines on MoonBit's async intrinsics (%async.suspend / run / capture_cancellation / raise_cancellation_signal), scheduled by a Dispatcher trait (the platform hook) instead of core/async's event loop; works on wasm, wasm-gc, js and native. - Task[T]: wait (re-raises task errors), cancel (unwinds at the next suspension point, running defers; waiters get TaskCancelled), ready, try_result, detach. Executor: spawn, timer, sleep, yield_now, now. - TestDispatcher: deterministic FIFO queue and virtual clock with GPUI's advance_clock semantics (run, then step to each due timer). - app: AsyncApp, App::spawn, Context::spawn (weak handle), foreground/background executors, run_until_parked / advance_clock; App::new() owns a TestDispatcher unless given a dispatcher. - Tests ported/adapted from the scheduler crate; app async tests; the counter example gains a ticker task. Docs: M4 status and deviations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
64bf747047
commit
eeab51348e
16 files changed
+1108
-13
No files matched your search
@@ -0,0 +1,157 @@
|
||||
// Coroutines on top of MoonBit's async intrinsics, scheduled by a
|
||||
// `Dispatcher` instead of `moonbitlang/core/async`'s event loop.
|
||||
//
|
||||
// Why not `moonbitlang/core/async`: it owns the event loop (`async fn main`,
|
||||
// `with_task_group`) and does not support the wasm-gc backend. GPUI's
|
||||
// executors are driven by the platform (the browser's event loop, a native run
|
||||
// loop, or a deterministic test scheduler), so we schedule coroutines
|
||||
// ourselves with the same intrinsics `moonbitlang/core/async` is built on.
|
||||
// They are experimental; see docs/PORTING.md.
|
||||
|
||||
///|
|
||||
async fn[T] async_suspend(cb : ((T) -> Unit) -> Unit) -> T noraise + nocancel = "%async.suspend"
|
||||
|
||||
///|
|
||||
fn run_async(f : async () -> Unit noraise + nocancel) = "%async.run"
|
||||
|
||||
///|
|
||||
async fn[X] raise_cancellation_signal() -> X noraise = "%async.raise_cancellation_signal"
|
||||
|
||||
///|
|
||||
async fn[X] capture_cancellation(
|
||||
f : async () -> X,
|
||||
handler~ : async () -> X nocancel,
|
||||
) -> X nocancel = "%async.capture_cancellation"
|
||||
|
||||
///|
|
||||
priv enum Wake {
|
||||
Continue
|
||||
Cancelled
|
||||
}
|
||||
|
||||
///|
|
||||
/// One running computation. While suspended, `continuation` resumes it.
|
||||
priv struct Coroutine {
|
||||
scheduler : Scheduler
|
||||
mut continuation : ((Wake) -> Unit)?
|
||||
mut cancelled : Bool
|
||||
mut scheduled : Bool
|
||||
mut finished : Bool
|
||||
/// Woken while running: the next `suspend` returns immediately.
|
||||
mut missed_wake : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
/// Runs coroutines one step at a time through a dispatcher.
|
||||
priv struct Scheduler {
|
||||
dispatcher : &Dispatcher
|
||||
}
|
||||
|
||||
///|
|
||||
/// The coroutine running right now, across all schedulers (there is one
|
||||
/// thread).
|
||||
let current : Ref[Coroutine?] = { val: None, }
|
||||
|
||||
///|
|
||||
/// Schedules `coroutine` to continue on the dispatcher, once.
|
||||
fn Coroutine::wake(self : Coroutine) -> Unit {
|
||||
if self.scheduled || self.finished {
|
||||
return
|
||||
}
|
||||
self.scheduled = true
|
||||
self.scheduler.dispatcher.dispatch(fn() { self.step() })
|
||||
}
|
||||
|
||||
///|
|
||||
fn Coroutine::step(self : Coroutine) -> Unit {
|
||||
self.scheduled = false
|
||||
guard self.continuation is Some(continuation) else {
|
||||
// Woken while running (it has not suspended yet).
|
||||
if !self.finished {
|
||||
self.missed_wake = true
|
||||
}
|
||||
return
|
||||
}
|
||||
self.continuation = None
|
||||
let previous = current.val
|
||||
current.val = Some(self)
|
||||
continuation(if self.cancelled { Cancelled } else { Continue })
|
||||
current.val = previous
|
||||
}
|
||||
|
||||
///|
|
||||
/// The coroutine running right now; fails loudly outside of a task.
|
||||
fn current_coroutine(operation : String) -> Coroutine {
|
||||
match current.val {
|
||||
Some(coroutine) => coroutine
|
||||
None => abort("\{operation} must be called from inside a task")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Suspends the current coroutine until it is woken. If the task is cancelled
|
||||
/// (before or while suspended), raises the cancellation signal, which unwinds
|
||||
/// the task and runs its `defer` blocks.
|
||||
async fn suspend(coroutine : Coroutine) -> Unit noraise {
|
||||
if coroutine.cancelled {
|
||||
raise_cancellation_signal()
|
||||
}
|
||||
if coroutine.missed_wake {
|
||||
coroutine.missed_wake = false
|
||||
return
|
||||
}
|
||||
let wake : Wake = async_suspend(fn(k) { coroutine.continuation = Some(k) })
|
||||
match wake {
|
||||
Continue => ()
|
||||
Cancelled => raise_cancellation_signal()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Starts `body` as a new coroutine on the next dispatcher turn.
|
||||
fn Scheduler::spawn(
|
||||
self : Scheduler,
|
||||
body : async () -> Unit,
|
||||
on_cancelled : () -> Unit,
|
||||
on_error : (Error) -> Unit,
|
||||
on_finished : () -> Unit,
|
||||
) -> Coroutine {
|
||||
let coroutine : Coroutine = {
|
||||
scheduler: self,
|
||||
continuation: None,
|
||||
cancelled: false,
|
||||
scheduled: false,
|
||||
finished: false,
|
||||
missed_wake: false,
|
||||
}
|
||||
coroutine.continuation = Some(fn(wake) {
|
||||
match wake {
|
||||
Cancelled => {
|
||||
// Cancelled before it ever ran: the body never starts.
|
||||
coroutine.finished = true
|
||||
on_cancelled()
|
||||
on_finished()
|
||||
}
|
||||
Continue =>
|
||||
run_async(() => {
|
||||
capture_cancellation(body, handler=() => on_cancelled()) catch {
|
||||
error => on_error(error)
|
||||
}
|
||||
coroutine.finished = true
|
||||
on_finished()
|
||||
})
|
||||
}
|
||||
})
|
||||
coroutine.wake()
|
||||
coroutine
|
||||
}
|
||||
|
||||
///|
|
||||
fn Coroutine::cancel(self : Coroutine) -> Unit {
|
||||
if self.finished || self.cancelled {
|
||||
return
|
||||
}
|
||||
self.cancelled = true
|
||||
// Resume it so that it observes the cancellation (and runs its `defer`s).
|
||||
self.wake()
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// The platform hook that runs executor work (GPUI: `PlatformDispatcher`,
|
||||
// reduced to a single thread: GPUI's background threads are not available
|
||||
// on the web and MoonBit has no threads; background tasks share the main
|
||||
// thread, as in GPUI's single-threaded web backend).
|
||||
|
||||
///|
|
||||
/// Runs callbacks on the (only) thread, soon or after a delay.
|
||||
pub(open) trait Dispatcher {
|
||||
/// Run `runnable` soon, after the current callback returns.
|
||||
fn dispatch(Self, runnable : () -> Unit) -> Unit
|
||||
/// Run `runnable` after `delay_ms` milliseconds.
|
||||
fn dispatch_after(Self, delay_ms : Int32, runnable : () -> Unit) -> Unit
|
||||
/// Milliseconds since an arbitrary, fixed origin.
|
||||
fn now(Self) -> Int64
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct PendingTimer {
|
||||
deadline : Int64
|
||||
runnable : () -> Unit
|
||||
}
|
||||
|
||||
///|
|
||||
/// A deterministic dispatcher with a virtual clock, for tests (GPUI:
|
||||
/// `TestScheduler`/`TestDispatcher`). Nothing runs until the test drives it
|
||||
/// with `tick`, `run_until_parked` or `advance_clock`.
|
||||
pub struct TestDispatcher {
|
||||
priv queue : @deque.Deque[() -> Unit]
|
||||
priv timers : Array[PendingTimer]
|
||||
priv mut now_ms : Int64
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn TestDispatcher::new() -> TestDispatcher {
|
||||
{ queue: @deque.Deque([]), timers: [], now_ms: 0, }
|
||||
}
|
||||
|
||||
///|
|
||||
pub impl Dispatcher for TestDispatcher with fn dispatch(self, runnable) {
|
||||
self.queue.push_back(runnable)
|
||||
}
|
||||
|
||||
///|
|
||||
pub impl Dispatcher for TestDispatcher with fn dispatch_after(
|
||||
self,
|
||||
delay_ms,
|
||||
runnable,
|
||||
) {
|
||||
guard delay_ms >= 0 else {
|
||||
abort("dispatch_after: negative delay \{delay_ms}ms")
|
||||
}
|
||||
let timer = { deadline: self.now_ms + delay_ms.to_int64(), runnable, }
|
||||
// Keep timers sorted by deadline; equal deadlines keep insertion order.
|
||||
let mut index = self.timers.length()
|
||||
while index > 0 && self.timers[index - 1].deadline > timer.deadline {
|
||||
index = index - 1
|
||||
}
|
||||
self.timers.insert(index, timer)
|
||||
}
|
||||
|
||||
///|
|
||||
pub impl Dispatcher for TestDispatcher with fn now(self) {
|
||||
self.now_ms
|
||||
}
|
||||
|
||||
///|
|
||||
/// Moves timers whose deadline has passed into the run queue.
|
||||
fn TestDispatcher::fire_due_timers(self : TestDispatcher) -> Unit {
|
||||
while !self.timers.is_empty() && self.timers[0].deadline <= self.now_ms {
|
||||
self.queue.push_back(self.timers.remove(0).runnable)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Runs one ready callback; false if none is ready.
|
||||
pub fn TestDispatcher::tick(self : TestDispatcher) -> Bool {
|
||||
self.fire_due_timers()
|
||||
match self.queue.pop_front() {
|
||||
Some(runnable) => {
|
||||
runnable()
|
||||
true
|
||||
}
|
||||
None => false
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Runs callbacks until none is ready without advancing the clock (GPUI:
|
||||
/// `run_until_parked`).
|
||||
pub fn TestDispatcher::run_until_parked(self : TestDispatcher) -> Unit {
|
||||
while self.tick() {
|
||||
()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Advances the virtual clock by `ms`, firing timers in deadline order and
|
||||
/// running everything they wake (GPUI: `advance_clock`).
|
||||
pub fn TestDispatcher::advance_clock(self : TestDispatcher, ms : Int32) -> Unit {
|
||||
guard ms >= 0 else { abort("advance_clock: negative duration \{ms}ms") }
|
||||
let target = self.now_ms + ms.to_int64()
|
||||
while true {
|
||||
self.run_until_parked()
|
||||
if !self.timers.is_empty() && self.timers[0].deadline <= target {
|
||||
self.now_ms = self.timers[0].deadline
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
self.now_ms = target
|
||||
}
|
||||
|
||||
///|
|
||||
/// Whether any callback is ready or any timer is pending.
|
||||
pub fn TestDispatcher::has_pending_work(self : TestDispatcher) -> Bool {
|
||||
!self.queue.is_empty() || !self.timers.is_empty()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Number of pending timers.
|
||||
pub fn TestDispatcher::pending_timer_count(self : TestDispatcher) -> Int32 {
|
||||
self.timers.length()
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
///|
|
||||
fn setup() -> (@executor.TestDispatcher, @executor.Executor) {
|
||||
let dispatcher = @executor.TestDispatcher::new()
|
||||
(dispatcher, @executor.Executor::new(dispatcher))
|
||||
}
|
||||
|
||||
///|
|
||||
fn[T] result_of(task : @executor.Task[T]) -> T? {
|
||||
task.try_result() catch {
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
suberror Boom {
|
||||
Boom(String)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Port of the scheduler crate's `test_foreground_executor_spawn`.
|
||||
test "spawn runs on the dispatcher" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let task = executor.spawn(fn() { 42 })
|
||||
// Nothing runs until the dispatcher is driven.
|
||||
assert_false(task.is_ready())
|
||||
dispatcher.run_until_parked()
|
||||
assert_true(task.is_ready())
|
||||
assert_eq(result_of(task), Some(42))
|
||||
assert_eq(result_of(@executor.Task::ready("now")), Some("now"))
|
||||
}
|
||||
|
||||
///|
|
||||
/// Like the scheduler crate's `test_foreground_ordering`: tasks start in
|
||||
/// spawn order.
|
||||
test "tasks run in spawn order" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let trace = []
|
||||
for i in 0..<10 {
|
||||
executor.spawn(fn() { trace.push(i) }).detach()
|
||||
}
|
||||
dispatcher.run_until_parked()
|
||||
assert_eq(trace, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
||||
}
|
||||
|
||||
///|
|
||||
/// Port of the scheduler crate's `test_timer_ordering`.
|
||||
test "timers fire in deadline order on the virtual clock" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let order = []
|
||||
for delay in [100, 50, 150] {
|
||||
executor
|
||||
.spawn(async fn() {
|
||||
executor.sleep(delay)
|
||||
order.push((delay, executor.now()))
|
||||
})
|
||||
.detach()
|
||||
}
|
||||
dispatcher.run_until_parked()
|
||||
assert_eq(order, [])
|
||||
dispatcher.advance_clock(60)
|
||||
assert_eq(order, [(50, 50L)])
|
||||
assert_eq(executor.now(), 60L)
|
||||
dispatcher.advance_clock(1000)
|
||||
assert_eq(order, [(50, 50L), (100, 100L), (150, 150L)])
|
||||
assert_false(dispatcher.has_pending_work())
|
||||
}
|
||||
|
||||
///|
|
||||
test "tasks await tasks and errors propagate" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let inner = executor.spawn(async fn() {
|
||||
executor.sleep(10)
|
||||
20
|
||||
})
|
||||
let outer = executor.spawn(async fn() { inner.wait() + 1 })
|
||||
let failing : @executor.Task[Int32] = executor.spawn(fn() raise {
|
||||
raise Boom("bad")
|
||||
})
|
||||
let observer = executor.spawn(async fn() {
|
||||
try failing.wait() catch {
|
||||
Boom(message) => "caught \{message}"
|
||||
_ => "other"
|
||||
} noraise {
|
||||
_ => "no error"
|
||||
}
|
||||
})
|
||||
dispatcher.advance_clock(10)
|
||||
assert_eq(result_of(outer), Some(21))
|
||||
assert_eq(result_of(observer), Some("caught bad"))
|
||||
let raised = try failing.try_result() catch {
|
||||
Boom(_) => true
|
||||
_ => false
|
||||
} noraise {
|
||||
_ => false
|
||||
}
|
||||
assert_true(raised)
|
||||
}
|
||||
|
||||
///|
|
||||
test "cancel before start: the body never runs" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let ran = Ref(false)
|
||||
let task = executor.spawn(fn() { ran.val = true })
|
||||
task.cancel()
|
||||
dispatcher.run_until_parked()
|
||||
assert_false(ran.val)
|
||||
assert_true(task.is_cancelled())
|
||||
let raised = try task.try_result() catch {
|
||||
@executor.TaskCancelled => true
|
||||
_ => false
|
||||
} noraise {
|
||||
_ => false
|
||||
}
|
||||
assert_true(raised)
|
||||
}
|
||||
|
||||
///|
|
||||
test "cancel while suspended unwinds the task and notifies waiters" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let log = []
|
||||
let sleeper = executor.spawn(async fn() {
|
||||
defer log.push("cleanup")
|
||||
log.push("sleeping")
|
||||
executor.sleep(1000)
|
||||
log.push("woke up")
|
||||
})
|
||||
let waiter = executor.spawn(async fn() {
|
||||
try sleeper.wait() catch {
|
||||
@executor.TaskCancelled => "sleeper cancelled"
|
||||
_ => "other error"
|
||||
} noraise {
|
||||
_ => "finished"
|
||||
}
|
||||
})
|
||||
dispatcher.run_until_parked()
|
||||
assert_eq(log, ["sleeping"])
|
||||
sleeper.cancel()
|
||||
dispatcher.run_until_parked()
|
||||
assert_eq(log, ["sleeping", "cleanup"])
|
||||
assert_eq(result_of(waiter), Some("sleeper cancelled"))
|
||||
// The timer still fires later, but nothing resumes.
|
||||
dispatcher.advance_clock(2000)
|
||||
assert_eq(log, ["sleeping", "cleanup"])
|
||||
// Cancelling a finished task does nothing.
|
||||
waiter.cancel()
|
||||
assert_false(waiter.is_cancelled())
|
||||
}
|
||||
|
||||
///|
|
||||
test "cancelled timers report cancellation" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let timer = executor.timer(50)
|
||||
timer.cancel()
|
||||
assert_true(timer.is_cancelled())
|
||||
dispatcher.advance_clock(100)
|
||||
assert_true(timer.is_cancelled())
|
||||
}
|
||||
|
||||
///|
|
||||
test "a task can cancel itself" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let log = []
|
||||
let task_ref : Ref[@executor.Task[Unit]?] = Ref(None)
|
||||
let task = executor.spawn(async fn() {
|
||||
defer log.push("unwound")
|
||||
task_ref.val.unwrap().cancel()
|
||||
log.push("still running until the next suspension")
|
||||
executor.yield_now()
|
||||
log.push("never")
|
||||
})
|
||||
task_ref.val = Some(task)
|
||||
dispatcher.run_until_parked()
|
||||
assert_eq(log, ["still running until the next suspension", "unwound"])
|
||||
assert_true(task.is_cancelled())
|
||||
}
|
||||
|
||||
///|
|
||||
test "yield_now interleaves tasks" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let trace = []
|
||||
for name in ["a", "b"] {
|
||||
executor
|
||||
.spawn(async fn() {
|
||||
for i in 0..<3 {
|
||||
trace.push("\{name}\{i}")
|
||||
executor.yield_now()
|
||||
}
|
||||
})
|
||||
.detach()
|
||||
}
|
||||
dispatcher.run_until_parked()
|
||||
assert_eq(trace, ["a0", "b0", "a1", "b1", "a2", "b2"])
|
||||
}
|
||||
|
||||
///|
|
||||
test "tick runs one step at a time" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let trace = []
|
||||
executor.spawn(fn() { trace.push(1) }).detach()
|
||||
executor.spawn(fn() { trace.push(2) }).detach()
|
||||
assert_true(dispatcher.tick())
|
||||
assert_eq(trace, [1])
|
||||
assert_true(dispatcher.tick())
|
||||
assert_false(dispatcher.tick())
|
||||
assert_eq(trace, [1, 2])
|
||||
assert_eq(dispatcher.pending_timer_count(), 0)
|
||||
}
|
||||
|
||||
///|
|
||||
test "panic on a task waiting for itself" {
|
||||
let (dispatcher, executor) = setup()
|
||||
let task_ref : Ref[@executor.Task[Unit]?] = Ref(None)
|
||||
let task = executor.spawn(async fn() { task_ref.val.unwrap().wait() })
|
||||
task_ref.val = Some(task)
|
||||
dispatcher.run_until_parked()
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
///|
|
||||
test "panic on waiting outside a task" {
|
||||
let dispatcher = TestDispatcher::new()
|
||||
let task = Executor::new(dispatcher).timer(1)
|
||||
// A coroutine that is not a task: `wait` cannot suspend it.
|
||||
run_async(() => {
|
||||
capture_cancellation(() => task.wait(), handler=() => ()) catch {
|
||||
_ => ()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import {
|
||||
"moonbitlang/core/deque",
|
||||
}
|
||||
|
||||
// The coroutine intrinsics (%async.*) are experimental.
|
||||
|
||||
options(
|
||||
"allow-experimental-packages": true,
|
||||
experimental: true,
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "experiments/gpui/executor"
|
||||
|
||||
import {
|
||||
"moonbitlang/core/debug",
|
||||
}
|
||||
|
||||
// Values
|
||||
|
||||
// Errors
|
||||
#derive(@debug.Debug)
|
||||
pub suberror TaskCancelled
|
||||
|
||||
// Types and methods
|
||||
pub struct Executor {
|
||||
// private fields
|
||||
}
|
||||
pub fn Executor::new(&Dispatcher) -> Self
|
||||
pub fn Executor::now(Self) -> Int64
|
||||
pub async fn Executor::sleep(Self, Int32) -> Unit
|
||||
pub fn[T] Executor::spawn(Self, async () -> T) -> Task[T]
|
||||
pub fn Executor::timer(Self, Int32) -> Task[Unit]
|
||||
pub async fn Executor::yield_now(Self) -> Unit
|
||||
|
||||
pub struct Task[T] {
|
||||
// private fields
|
||||
}
|
||||
pub fn[T] Task::cancel(Self[T]) -> Unit
|
||||
pub fn[T] Task::detach(Self[T]) -> Unit
|
||||
pub fn[T] Task::is_cancelled(Self[T]) -> Bool
|
||||
pub fn[T] Task::is_ready(Self[T]) -> Bool
|
||||
pub fn[T] Task::ready(T) -> Self[T]
|
||||
pub fn[T] Task::try_result(Self[T]) -> T? raise
|
||||
pub async fn[T] Task::wait(Self[T]) -> T
|
||||
|
||||
pub struct TestDispatcher {
|
||||
// private fields
|
||||
}
|
||||
pub fn TestDispatcher::advance_clock(Self, Int32) -> Unit
|
||||
pub fn TestDispatcher::has_pending_work(Self) -> Bool
|
||||
pub fn TestDispatcher::new() -> Self
|
||||
pub fn TestDispatcher::pending_timer_count(Self) -> Int32
|
||||
pub fn TestDispatcher::run_until_parked(Self) -> Unit
|
||||
pub fn TestDispatcher::tick(Self) -> Bool
|
||||
pub impl Dispatcher for TestDispatcher
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
pub(open) trait Dispatcher {
|
||||
fn dispatch(Self, () -> Unit) -> Unit
|
||||
fn dispatch_after(Self, Int32, () -> Unit) -> Unit
|
||||
fn now(Self) -> Int64
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// Tasks and executors, ported from gpui/src/executor.rs and the `scheduler`
|
||||
// crate (crates/scheduler/src/executor.rs).
|
||||
//
|
||||
// Deviations from GPUI:
|
||||
// - Dropping a GPUI `Task` cancels it. There is no `Drop` in MoonBit: a task
|
||||
// runs to completion unless `cancel()` is called. `detach()` is kept for
|
||||
// parity.
|
||||
// - There is one thread: background and foreground executors schedule on the
|
||||
// same dispatcher (as GPUI's single-threaded web backend does).
|
||||
// - Durations are milliseconds (`Int`); `now()` is milliseconds (`Int64`).
|
||||
|
||||
///|
|
||||
/// Raised by `Task::wait` when the task was cancelled.
|
||||
#derive(Debug)
|
||||
pub suberror TaskCancelled
|
||||
|
||||
///|
|
||||
priv enum Outcome[T] {
|
||||
Pending
|
||||
Done(T)
|
||||
Failed(Error)
|
||||
Cancelled
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct TaskState[T] {
|
||||
mut outcome : Outcome[T]
|
||||
waiters : Array[Coroutine]
|
||||
mut coroutine : Coroutine?
|
||||
/// Cancels work that is not a coroutine (timers).
|
||||
mut on_cancel : (() -> Unit)?
|
||||
}
|
||||
|
||||
///|
|
||||
/// The result of asynchronous work (GPUI: `Task<T>`). Await it with `wait`.
|
||||
pub struct Task[T] {
|
||||
priv state : TaskState[T]
|
||||
}
|
||||
|
||||
///|
|
||||
fn[T] TaskState::new() -> TaskState[T] {
|
||||
{ outcome: Pending, waiters: [], coroutine: None, on_cancel: None, }
|
||||
}
|
||||
|
||||
///|
|
||||
fn[T] TaskState::complete(self : TaskState[T], outcome : Outcome[T]) -> Unit {
|
||||
guard self.outcome is Pending else { return }
|
||||
self.outcome = outcome
|
||||
let waiters = self.waiters.copy()
|
||||
self.waiters.clear()
|
||||
for waiter in waiters {
|
||||
waiter.wake()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// A task that is already complete (GPUI: `Task::ready`).
|
||||
pub fn[T] Task::ready(value : T) -> Task[T] {
|
||||
{ state: { ..TaskState::new(), outcome: Done(value), }, }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Whether the task has finished: completed, failed or cancelled.
|
||||
pub fn[T] Task::is_ready(self : Task[T]) -> Bool {
|
||||
!(self.state.outcome is Pending)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Whether the task was cancelled.
|
||||
pub fn[T] Task::is_cancelled(self : Task[T]) -> Bool {
|
||||
self.state.outcome is Cancelled
|
||||
}
|
||||
|
||||
///|
|
||||
/// Lets the task run to completion without anyone awaiting it. In MoonBit
|
||||
/// this is the default; kept for GPUI parity.
|
||||
pub fn[T] Task::detach(self : Task[T]) -> Unit {
|
||||
ignore(self)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Cancels the task. A running task is resumed with a cancellation signal at
|
||||
/// its next suspension point, unwinding it (running `defer` blocks). Waiters
|
||||
/// get `TaskCancelled`. No effect on finished tasks.
|
||||
pub fn[T] Task::cancel(self : Task[T]) -> Unit {
|
||||
guard self.state.outcome is Pending else { return }
|
||||
match (self.state.coroutine, self.state.on_cancel) {
|
||||
(Some(coroutine), _) => coroutine.cancel()
|
||||
(None, Some(on_cancel)) => on_cancel()
|
||||
(None, None) => self.state.complete(Cancelled)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// The result if the task has finished: `Some(value)`, or raises the task's
|
||||
/// error (or `TaskCancelled`); `None` while it is pending.
|
||||
pub fn[T] Task::try_result(self : Task[T]) -> T? raise {
|
||||
match self.state.outcome {
|
||||
Pending => None
|
||||
Done(value) => Some(value)
|
||||
Failed(error) => raise error
|
||||
Cancelled => raise TaskCancelled
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Waits for the task from inside another task and returns its value. Raises
|
||||
/// the task's error, or `TaskCancelled`.
|
||||
pub async fn[T] Task::wait(self : Task[T]) -> T {
|
||||
let state = self.state
|
||||
while state.outcome is Pending {
|
||||
let coroutine = current_coroutine("Task::wait")
|
||||
if state.coroutine is Some(own) && physical_equal(own, coroutine) {
|
||||
abort("a task cannot wait for itself")
|
||||
}
|
||||
state.waiters.push(coroutine)
|
||||
suspend(coroutine)
|
||||
}
|
||||
match state.outcome {
|
||||
Done(value) => value
|
||||
Failed(error) => raise error
|
||||
Cancelled => raise TaskCancelled
|
||||
Pending => abort("unreachable: task still pending after wait")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Spawns tasks and timers on a dispatcher (GPUI: `ForegroundExecutor` and
|
||||
/// `BackgroundExecutor`, which coincide on one thread).
|
||||
pub struct Executor {
|
||||
priv scheduler : Scheduler
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Executor::new(dispatcher : &Dispatcher) -> Executor {
|
||||
{ scheduler: { dispatcher, }, }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Runs `f` as a task, starting on the next dispatcher turn.
|
||||
pub fn[T] Executor::spawn(self : Executor, f : async () -> T) -> Task[T] {
|
||||
let state : TaskState[T] = TaskState::new()
|
||||
let coroutine = self.scheduler.spawn(
|
||||
async fn() {
|
||||
let value = f()
|
||||
state.complete(Done(value))
|
||||
},
|
||||
fn() { state.complete(Cancelled) },
|
||||
fn(error) { state.complete(Failed(error)) },
|
||||
fn() { },
|
||||
)
|
||||
state.coroutine = Some(coroutine)
|
||||
{ state, }
|
||||
}
|
||||
|
||||
///|
|
||||
/// A task that completes after `ms` milliseconds (GPUI: `timer`).
|
||||
pub fn Executor::timer(self : Executor, ms : Int32) -> Task[Unit] {
|
||||
let state : TaskState[Unit] = TaskState::new()
|
||||
state.on_cancel = Some(fn() { state.complete(Cancelled) })
|
||||
self.scheduler.dispatcher.dispatch_after(ms, fn() { state.complete(Done(())) })
|
||||
{ state, }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Suspends the current task for `ms` milliseconds.
|
||||
pub async fn Executor::sleep(self : Executor, ms : Int32) -> Unit {
|
||||
self.timer(ms).wait()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Lets other ready tasks run before continuing.
|
||||
pub async fn Executor::yield_now(self : Executor) -> Unit {
|
||||
let coroutine = current_coroutine("Executor::yield_now")
|
||||
ignore(self)
|
||||
coroutine.wake()
|
||||
suspend(coroutine)
|
||||
}
|
||||
|
||||
///|
|
||||
/// The dispatcher's clock, in milliseconds.
|
||||
pub fn Executor::now(self : Executor) -> Int64 {
|
||||
self.scheduler.dispatcher.now()
|
||||
}
|
||||
Reference in new issue
Block a user