Skip to main content

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