Skip to main content

kernel/
async_host.rs

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