Skip to main content

kernel/
async_request.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Portable state machine for frame-bounded async requests.
5//!
6//! Shell-side session state often needs to track "a request is in
7//! flight; when it completes, the result lands here" — the omnibar
8//! provider mailbox, deferred intent resolution, clip-capture round
9//! trips, etc. The pre-M4 pattern embedded `crossbeam_channel`
10//! receivers inside the session state, which is fine on desktop but
11//! doesn't compile to `wasm32-unknown-unknown` (crossbeam_channel
12//! needs `std::thread`).
13//!
14//! `AsyncRequestState<T>` is the portable replacement: pure data, no
15//! threading primitives inside. A host-side driver owns the actual
16//! channel / future / fetch, and deposits results into this state
17//! when ready. The shell-state side just reads and reacts.
18//!
19//! Concretely:
20//!
21//! - **Shell state** holds `AsyncRequestState<T>`. Calling code
22//!   transitions via [`arm_pending`], [`resolve`], [`interrupt`],
23//!   [`clear`]. Generation counter lets the state reject stale late
24//!   results from requests that have since been superseded.
25//! - **Host driver** (one per session or one per request kind) owns
26//!   the concrete async machinery — `crossbeam_channel::Receiver<T>`
27//!   / `tokio::sync::oneshot` / `futures::channel` / etc. Polls at
28//!   frame boundaries and calls [`resolve`] / [`interrupt`] on the
29//!   state it shepherds.
30//!
31//! The state type has no threading or time dependencies, so it is
32//! safe to place inside types that belong in a portable shell-state
33//! sub-crate targeting `wasm32-unknown-unknown` and `wasip2`.
34//!
35//! [`arm_pending`]: AsyncRequestState::arm_pending
36//! [`resolve`]: AsyncRequestState::resolve
37//! [`interrupt`]: AsyncRequestState::interrupt
38//! [`clear`]: AsyncRequestState::clear
39
40use serde::{Deserialize, Serialize};
41
42/// Frame-bounded state of a host-driven async request.
43///
44/// Generic over the result payload `T`. The enum is always fully
45/// deterministic — no internal threading, no hidden waiting. Hosts
46/// bridge their concrete async primitives (crossbeam / tokio /
47/// futures) into this state by calling the transition methods at
48/// frame boundaries.
49///
50/// The `generation` counter inside `Pending` and `Ready` lets callers
51/// distinguish a result for the current request from a late result
52/// for a request that has been superseded. The pattern:
53///
54/// 1. Caller initiates request, calls [`arm_pending`]; state stores
55///    `generation = N`.
56/// 2. Caller initiates a newer request before the first completes;
57///    state moves to `generation = N + 1`, the old request's result
58///    is still en route on the host driver's side.
59/// 3. The old result arrives at the host driver. Driver calls
60///    [`resolve`] with `generation = N`; the state is at `N + 1`, so
61///    the state rejects the stale value.
62/// 4. The new result arrives. Driver calls [`resolve`] with
63///    `generation = N + 1`; the state accepts and transitions to
64///    `Ready { generation: N + 1, value }`.
65///
66/// [`arm_pending`]: Self::arm_pending
67/// [`resolve`]: Self::resolve
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69pub enum AsyncRequestState<T> {
70    /// No request is in flight and no result is pending consumption.
71    Idle,
72    /// A request has been kicked off. `generation` uniquely identifies
73    /// this request; a late result with a smaller generation is
74    /// stale and should be dropped.
75    Pending { generation: u64 },
76    /// A result is ready and has not yet been consumed.
77    Ready { generation: u64, value: T },
78    /// The pending request was interrupted: the driver dropped its
79    /// sender, the request was explicitly cancelled, or the state was
80    /// re-armed before the result arrived. Treat as "the work happened
81    /// or didn't, but don't wait for a value".
82    Interrupted,
83}
84
85impl<T> Default for AsyncRequestState<T> {
86    fn default() -> Self {
87        Self::Idle
88    }
89}
90
91impl<T> AsyncRequestState<T> {
92    /// `true` when a request is in flight — the caller has armed the
93    /// state and is awaiting the driver's resolution.
94    pub fn is_pending(&self) -> bool {
95        matches!(self, Self::Pending { .. })
96    }
97
98    /// `true` when a result is ready to be consumed via [`take`].
99    ///
100    /// [`take`]: Self::take
101    pub fn is_ready(&self) -> bool {
102        matches!(self, Self::Ready { .. })
103    }
104
105    /// Current request generation, if any. Returns `None` for
106    /// `Idle`/`Interrupted`.
107    pub fn generation(&self) -> Option<u64> {
108        match self {
109            Self::Idle | Self::Interrupted => None,
110            Self::Pending { generation } | Self::Ready { generation, .. } => Some(*generation),
111        }
112    }
113
114    /// Transition to `Pending` with the supplied generation. Typically
115    /// the caller tracks the next generation externally (e.g. an
116    /// AtomicU64) and bumps on each new request so stale results from
117    /// previous requests are rejected by [`resolve`].
118    ///
119    /// Returns the prior state so the caller can inspect whether a
120    /// previous request was mid-flight (useful for logging /
121    /// diagnostics).
122    ///
123    /// [`resolve`]: Self::resolve
124    pub fn arm_pending(&mut self, generation: u64) -> Self
125    where
126        T: Clone,
127    {
128        let prior = self.clone();
129        *self = Self::Pending { generation };
130        prior
131    }
132
133    /// Deposit a result for a specific generation. If the state is
134    /// `Pending { generation == requested }`, transitions to
135    /// `Ready { generation, value }` and returns `true`. Otherwise
136    /// (stale generation, idle, or already-ready), the value is
137    /// discarded and returns `false` — the caller can use the return
138    /// value for diagnostics.
139    pub fn resolve(&mut self, generation: u64, value: T) -> bool {
140        match self {
141            Self::Pending {
142                generation: pending,
143            } if *pending == generation => {
144                *self = Self::Ready { generation, value };
145                true
146            }
147            _ => false,
148        }
149    }
150
151    /// Mark the request as interrupted. Idempotent.
152    pub fn interrupt(&mut self) {
153        *self = Self::Interrupted;
154    }
155
156    /// Reset to `Idle`, discarding any in-flight request or pending
157    /// result.
158    pub fn clear(&mut self) {
159        *self = Self::Idle;
160    }
161
162    /// Consume a ready result. Returns `Some(value)` and resets the
163    /// state to `Idle` if a result was ready; `None` otherwise (the
164    /// state is left unchanged in that case).
165    pub fn take(&mut self) -> Option<T> {
166        if matches!(self, Self::Ready { .. }) {
167            match std::mem::replace(self, Self::Idle) {
168                Self::Ready { value, .. } => Some(value),
169                _ => unreachable!(),
170            }
171        } else {
172            None
173        }
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn default_is_idle() {
183        let state: AsyncRequestState<u32> = Default::default();
184        assert!(matches!(state, AsyncRequestState::Idle));
185    }
186
187    #[test]
188    fn arm_pending_transitions_from_idle_and_reports_prior() {
189        let mut state: AsyncRequestState<u32> = AsyncRequestState::Idle;
190        let prior = state.arm_pending(7);
191        assert!(matches!(prior, AsyncRequestState::Idle));
192        assert!(state.is_pending());
193        assert_eq!(state.generation(), Some(7));
194    }
195
196    #[test]
197    fn arm_pending_bumps_generation_and_reports_prior_pending() {
198        let mut state: AsyncRequestState<u32> = AsyncRequestState::Idle;
199        state.arm_pending(7);
200        let prior = state.arm_pending(8);
201        assert!(matches!(
202            prior,
203            AsyncRequestState::Pending { generation: 7 }
204        ));
205        assert_eq!(state.generation(), Some(8));
206    }
207
208    #[test]
209    fn resolve_accepts_matching_generation() {
210        let mut state: AsyncRequestState<u32> = AsyncRequestState::Idle;
211        state.arm_pending(3);
212        let accepted = state.resolve(3, 42);
213        assert!(accepted);
214        assert!(state.is_ready());
215        assert_eq!(state.take(), Some(42));
216        assert!(matches!(state, AsyncRequestState::Idle));
217    }
218
219    #[test]
220    fn resolve_rejects_stale_generation() {
221        // Classic stale-late-result case: request 1 goes out, caller
222        // supersedes with request 2, then request 1's result arrives.
223        // State should discard request 1's value.
224        let mut state: AsyncRequestState<u32> = AsyncRequestState::Idle;
225        state.arm_pending(1);
226        state.arm_pending(2);
227        let accepted = state.resolve(1, 42);
228        assert!(!accepted);
229        assert!(state.is_pending());
230        assert_eq!(state.generation(), Some(2));
231    }
232
233    #[test]
234    fn resolve_rejects_on_idle() {
235        let mut state: AsyncRequestState<u32> = AsyncRequestState::Idle;
236        let accepted = state.resolve(1, 42);
237        assert!(!accepted);
238        assert!(matches!(state, AsyncRequestState::Idle));
239    }
240
241    #[test]
242    fn interrupt_moves_pending_to_interrupted() {
243        let mut state: AsyncRequestState<u32> = AsyncRequestState::Idle;
244        state.arm_pending(5);
245        state.interrupt();
246        assert!(matches!(state, AsyncRequestState::Interrupted));
247        assert_eq!(state.generation(), None);
248    }
249
250    #[test]
251    fn clear_from_any_state_returns_to_idle() {
252        let mut state: AsyncRequestState<u32> = AsyncRequestState::Idle;
253        state.arm_pending(1);
254        state.resolve(1, 42);
255        state.clear();
256        assert!(matches!(state, AsyncRequestState::Idle));
257    }
258
259    #[test]
260    fn take_without_ready_leaves_state_unchanged() {
261        let mut state: AsyncRequestState<u32> = AsyncRequestState::Idle;
262        state.arm_pending(1);
263        assert_eq!(state.take(), None);
264        assert!(state.is_pending());
265    }
266
267    #[test]
268    fn serde_json_round_trips_each_variant() {
269        let variants: Vec<AsyncRequestState<String>> = vec![
270            AsyncRequestState::Idle,
271            AsyncRequestState::Pending { generation: 42 },
272            AsyncRequestState::Ready {
273                generation: 42,
274                value: "result".to_string(),
275            },
276            AsyncRequestState::Interrupted,
277        ];
278        for state in variants {
279            let encoded = serde_json::to_string(&state).expect("serialize");
280            let decoded: AsyncRequestState<String> =
281                serde_json::from_str(&encoded).expect("deserialize");
282            assert_eq!(decoded, state);
283        }
284    }
285
286    #[test]
287    fn stale_late_result_example_flow() {
288        // End-to-end walk of the stale-generation scenario from the
289        // doc comment, pinned as a test so the documented contract
290        // stays honest.
291        let mut state: AsyncRequestState<String> = AsyncRequestState::Idle;
292
293        // 1. Caller arms for generation 10.
294        state.arm_pending(10);
295        assert_eq!(state.generation(), Some(10));
296
297        // 2. Before 10's result arrives, a newer request supersedes
298        //    it at generation 11.
299        state.arm_pending(11);
300
301        // 3. 10's result arrives late on the host driver. Rejected.
302        let accepted_stale = state.resolve(10, "old".to_string());
303        assert!(!accepted_stale);
304        assert_eq!(state.generation(), Some(11));
305
306        // 4. 11's result arrives. Accepted.
307        let accepted_fresh = state.resolve(11, "new".to_string());
308        assert!(accepted_fresh);
309        assert_eq!(state.take().as_deref(), Some("new"));
310    }
311}