Skip to main content

kernel/
async_host.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Portable async-host boundary traits.
5//!
6//! `kernel` names the runtime/host seam in terms of a small,
7//! object-safe task-spawning interface so native and wasm hosts can choose
8//! different executor models without changing runtime code.
9
10use std::any::Any;
11use std::marker::PhantomData;
12
13use crossbeam_channel::{Receiver, TryRecvError};
14use futures_util::future::BoxFuture;
15
16/// Boxed blocking-task result used at the object-safe trait boundary.
17pub type ErasedBlockingResult = Box<dyn Any + Send>;
18
19/// Boxed blocking-task work item used at the object-safe trait boundary.
20pub type BoxedBlockingWork = Box<dyn FnOnce() -> ErasedBlockingResult + Send + 'static>;
21
22/// Object-safe host-provided async spawner.
23///
24/// `spawn_blocking` is exposed as an erased operation on the trait so the
25/// runtime can hold `Arc<dyn AsyncSpawner>`. Typed callers use the helper
26/// [`spawn_blocking`] wrapper below, which downcasts the boxed result back to
27/// the requested type.
28pub trait AsyncSpawner: Send + Sync {
29    /// Spawn a supervised async task.
30    fn spawn_supervised(
31        &self,
32        label: &'static str,
33        task: BoxFuture<'static, ()>,
34    ) -> Result<(), SpawnError>;
35
36    /// Spawn a blocking task and return an erased result receiver.
37    fn spawn_blocking_erased(
38        &self,
39        label: &'static str,
40        work: BoxedBlockingWork,
41    ) -> Result<Receiver<ErasedBlockingResult>, SpawnError>;
42
43    /// Broadcast cancellation to all supervised tasks.
44    fn request_cancel(&self);
45
46    /// Has cancellation already been requested?
47    fn is_cancelled(&self) -> bool;
48
49    /// Request cancellation and wait for supervised tasks to terminate.
50    fn shutdown(&self) -> BoxFuture<'static, ()>;
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum SpawnError {
55    /// This host does not support the requested spawn kind.
56    Unsupported,
57    /// The runtime is shutting down and rejected the task.
58    ShuttingDown,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum BlockingTryRecvError {
63    Empty,
64    Disconnected,
65    TypeMismatch,
66}
67
68/// Typed wrapper over an erased blocking-task result channel.
69pub struct BlockingTaskReceiver<T> {
70    inner: Receiver<ErasedBlockingResult>,
71    marker: PhantomData<T>,
72}
73
74impl<T> BlockingTaskReceiver<T> {
75    pub fn new(inner: Receiver<ErasedBlockingResult>) -> Self {
76        Self {
77            inner,
78            marker: PhantomData,
79        }
80    }
81}
82
83impl<T> BlockingTaskReceiver<T>
84where
85    T: Send + 'static,
86{
87    pub fn try_recv(&self) -> Result<T, BlockingTryRecvError> {
88        match self.inner.try_recv() {
89            Ok(value) => value
90                .downcast::<T>()
91                .map(|typed| *typed)
92                .map_err(|_| BlockingTryRecvError::TypeMismatch),
93            Err(TryRecvError::Empty) => Err(BlockingTryRecvError::Empty),
94            Err(TryRecvError::Disconnected) => Err(BlockingTryRecvError::Disconnected),
95        }
96    }
97}
98
99/// Spawn a blocking task through an object-safe [`AsyncSpawner`] and recover
100/// a typed result receiver on the caller side.
101pub fn spawn_blocking<T, F>(
102    spawner: &dyn AsyncSpawner,
103    label: &'static str,
104    work: F,
105) -> Result<BlockingTaskReceiver<T>, SpawnError>
106where
107    T: Send + 'static,
108    F: FnOnce() -> T + Send + 'static,
109{
110    let rx = spawner.spawn_blocking_erased(label, Box::new(move || Box::new(work())))?;
111    Ok(BlockingTaskReceiver::new(rx))
112}
113
114#[cfg(test)]
115mod tests {
116    use std::sync::Arc;
117    use std::sync::atomic::{AtomicBool, Ordering};
118
119    use crossbeam_channel::bounded;
120
121    use super::{
122        AsyncSpawner, BlockingTaskReceiver, BlockingTryRecvError, BoxedBlockingWork, SpawnError,
123        spawn_blocking,
124    };
125
126    #[derive(Default)]
127    struct MockAsyncSpawner {
128        cancelled: Arc<AtomicBool>,
129    }
130
131    impl AsyncSpawner for MockAsyncSpawner {
132        fn spawn_supervised(
133            &self,
134            _label: &'static str,
135            _task: futures_util::future::BoxFuture<'static, ()>,
136        ) -> Result<(), SpawnError> {
137            if self.cancelled.load(Ordering::SeqCst) {
138                return Err(SpawnError::ShuttingDown);
139            }
140            Ok(())
141        }
142
143        fn spawn_blocking_erased(
144            &self,
145            _label: &'static str,
146            work: BoxedBlockingWork,
147        ) -> Result<crossbeam_channel::Receiver<super::ErasedBlockingResult>, SpawnError> {
148            if self.cancelled.load(Ordering::SeqCst) {
149                return Err(SpawnError::ShuttingDown);
150            }
151            let (tx, rx) = bounded(1);
152            let _ = tx.send(work());
153            Ok(rx)
154        }
155
156        fn request_cancel(&self) {
157            self.cancelled.store(true, Ordering::SeqCst);
158        }
159
160        fn is_cancelled(&self) -> bool {
161            self.cancelled.load(Ordering::SeqCst)
162        }
163
164        fn shutdown(&self) -> futures_util::future::BoxFuture<'static, ()> {
165            let cancelled = Arc::clone(&self.cancelled);
166            Box::pin(async move {
167                cancelled.store(true, Ordering::SeqCst);
168            })
169        }
170    }
171
172    #[test]
173    fn spawn_blocking_returns_typed_value() {
174        let spawner = MockAsyncSpawner::default();
175        let rx = spawn_blocking(&spawner, "test_blocking", || 42usize)
176            .expect("spawn_blocking should succeed");
177
178        assert_eq!(rx.try_recv(), Ok(42));
179    }
180
181    #[test]
182    fn blocking_task_receiver_reports_type_mismatch() {
183        let (tx, rx) = bounded(1);
184        tx.send(Box::new("wrong-type".to_string()) as super::ErasedBlockingResult)
185            .expect("send should succeed");
186        let rx = BlockingTaskReceiver::<usize>::new(rx);
187
188        assert_eq!(rx.try_recv(), Err(BlockingTryRecvError::TypeMismatch));
189    }
190
191    #[test]
192    fn spawn_blocking_rejects_new_work_after_cancel() {
193        let spawner = MockAsyncSpawner::default();
194        spawner.request_cancel();
195
196        let result = spawn_blocking(&spawner, "test_blocking", || 42usize);
197
198        assert!(matches!(result, Err(SpawnError::ShuttingDown)));
199    }
200}