Skip to main content

hazard3_sync/
rpc_service.rs

1//! Async interface for dispatching `FnOnce(&mut T) -> R` jobs to a dedicated
2//! runner task with exclusive access to `T`.
3//!
4//! Callers submit an `FnOnce(&mut T) -> R` via [`RpcService::call`].
5//! A dedicated runner, started with [`RpcService::run`], executes
6//! closures one at a time with exclusive `&mut T` access and sends
7//! results back. Closures and return values are stored inline in a
8//! fixed-size slot of `S` bytes, checked at compile time.
9
10// It is sometimes useful to defer work from async tasks to a dedicated runner —
11// for example to serialize access to a shared resource, or to run blocking
12// operations in a lower-priority task without stalling the caller's executor.
13// Channels and signals can achieve this, but require the user to define an
14// RPC-like message protocol typically resulting in lots of boilerplate. Ideally,
15// callers could just submit an FnOnce(&mut T) -> R on a shared T owned by a runner
16// task, with a simple call()/run() interface that handles the rest.
17//
18// ## Design requirements
19// Ideally, each call should be able to have different F and R types. Since the
20// runner task will be unaware of the exact F and R, we will need to erase the type
21// of the closure and its return value.
22//
23// Like the existing primitives in embassy-sync, call() and run() should be
24// cancel-safe. Here, this means that dropping the future at any time must
25// leave the service in a consistent and recoverable state.
26//
27// Concretely, when a call future is dropped, either:
28//   - the closure was not yet written to the slot and is simply dropped, or
29//   - the closure was already written to the slot and will be executed to
30//     completion by the next run(), with the result being discarded.
31// In both cases, the service should remain usable and apply backpressure
32// correctly s.t new callers are simply blocked until the slot is free again.
33//
34// Since run() can also be cancelled, it would be reasonable for it to also
35// be restartable, that is, a new run() call must be able to pick up where the
36// previous one left off, recovering any stale work before accepting new work.
37//
38// ## Implementation
39// Fundamentally, we need some shared memory between the caller and the runner
40// for the closure and its return value.
41//
42// Stack-pinned memory on the caller side is not an option since after
43// submission, the runner may still be reading F or writing R when the
44// caller is dropped. We cannot block in Drop to wait for it to finish,
45// and also cannot interrupt the runner mid-execution either. So instead
46// of living on the stack, our closure and result will live in a shared
47// fixed-size byte buffer ("slot"), owned by the RpcService with access
48// coordinated by a handshake protocol.
49//
50// The slot (`Storage<S>`) is a statically sized S-byte buffer. The caller writes
51// its closure F into the slot via a pointer cast, then sends an erased function
52// pointer to run_job::<T, R, F, S> through the job signal. The runner calls
53// this function pointer, which takes F out of the slot, executes it, and
54// writes R back. The slot also stores a type-erased drop function so that
55// whoever cleans up can drop the contents without knowing the concrete type.
56//
57// Coordination uses a SlotState behind a blocking mutex and three signals:
58//
59//   - state (`Mutex<RefCell<SlotState>>`): a boolean `free` flag and a
60//     WakerRegistration. When a caller tries to acquire the slot and it
61//     is not free, the caller registers its waker here and returns
62//     Pending. When the runner finishes a job and marks the slot free,
63//     it wakes the registered waker
64//   - job (`Signal<RunFn>`): caller -> runner. Carries the type-erased function
65//     pointer and wakes the runner to start executing when the slot is filled
66//   - done (`Signal<()>`): runner -> caller. Notifies the caller that the result
67//     of the call R is ready in the slot.
68//   - ack (`Signal<()>`): caller -> runner. Tells the runner the caller is
69//     done reading R and the slot can be cleaned up.
70//
71// The protocol:
72// ```text
73//   caller                           runner
74//     |                                |
75//     |---- acquire slot ------------->|
76//     |       store F into slot        |
77//     |---- signal job --------------->|
78//     |                          take F, execute it, store R
79//     |<--- signal done ---------------|
80//     |       take R from slot         |
81//     |---- signal ack --------------->|
82//     |                          drop slot contents, mark slot free
83//     |                                |
84// ```
85// Slot ownership changes according to the protocol:
86//   - caller owns the slot between acquiring it and signalling job
87//   - runner owns the slot between receiving job and signalling done
88//   - caller owns the slot between receiving done and signalling ack
89//   - runner owns the slot between receiving ack and marking the slot free
90//
91// To support cancellation and restartabilty of run(), we can extend the above
92// with a few flags:
93//   - `running`: prevents concurrent `run()` calls. This is cleared by
94//     a drop guard so a new `run()` can start after the old one is dropped.
95//   - `needs_recovery`: is set while a job is in-flight. If the
96//     runner task is dropped while this is true, the next `run()` waits for
97//     the caller's ack and cleans up before accepting new work.
98//
99// The slot starts free, so callers can acquire and submit before any runner
100// is active. The job will be processed once `run()` is called.
101//
102// ```text
103//   caller                          runner
104//     |                               |
105//     |                         [running = true, drop guard armed]
106//     |                               |
107//     |--- acquire slot ------------->|
108//     |    store F in slot            |
109//     |--- signal job --------------->|
110//     |                         [needs_recovery = true]
111//     |                         take F, execute it, store R
112//     |<-- signal done ---------------|
113//     |    take R from slot           |
114//     |--- signal ack --------------->|
115//     |                         drop slot contents
116//     |                         [needs_recovery = false]
117//     |                         mark slot free
118//     |                               |
119// ```
120// `run()` can be dropped at any of its await points (job.wait, ack.wait).
121// If dropped while needs_recovery is true, the slot may still contain
122// data and the caller may still be active. The next run() checks
123// needs_recovery, waits for the caller's ack, and cleans up before
124// entering the main loop.
125//
126// The key invariant is that **every job signal is eventually followed by an
127// ack signal**, provided the caller is eventually dropped. CallFuture::drop
128// sends an ack if the closure was already written to the slot, which guarantees
129// the runner (or the next runner, after recovery) can always make progress.
130//
131// Closures and return types should avoid unwinding, but it is sound. If `f(state)` panics,
132// `needs_recovery` will stay set and `done` is never signaled. The caller blocks
133// until it is dropped, at which point its Drop signals ack and the next `run()` can
134// recover. This provides us with recovery after drop, but there is **no liveness guarantee**!
135// If the caller is never dropped, the service will be blocked.
136//
137// In the case that `R`'s destructor panics during cleanup, the `FinishGuard` in
138// `wait_ack_and_finish` ensures the slot is still freed and `needs_recovery` is cleared.
139// The destructor's side effects will be lost but the service remains usable.
140
141use core::cell::{Cell, RefCell, UnsafeCell};
142use core::future::Future;
143use core::marker::PhantomData;
144use core::mem::{self, MaybeUninit};
145use core::pin::Pin;
146use core::task::{Context, Poll};
147
148use crate::blocking_mutex::Mutex;
149use crate::blocking_mutex::raw::RawMutex;
150use crate::signal::Signal;
151use crate::waitqueue::WakerRegistration;
152
153/// Type-erased storage for closures and return values.
154///
155/// Invariants:
156/// - `drop_fn = Some(drop_glue::<T>)` iff the slot contains a live `T`
157/// - `store<T>()` writes a `T` and arms `drop_fn`
158/// - `take<T>()` reads a `T` out and clears `drop_fn`
159/// - `drop_contents()` drops in place if occupied; no-op if empty
160#[repr(C, align(8))] // TODO: this is fixed at ≥8-byte alignment. Is there a better option?
161struct Storage<const S: usize> {
162    buf: UnsafeCell<MaybeUninit<[u8; S]>>,
163    drop_fn: UnsafeCell<Option<unsafe fn(&Self)>>,
164}
165
166impl<const S: usize> Storage<S> {
167    const fn new() -> Self {
168        Self {
169            buf: UnsafeCell::new(MaybeUninit::uninit()),
170            drop_fn: UnsafeCell::new(None),
171        }
172    }
173
174    /// # Safety
175    /// Slot must be empty. `size_of::<T>() <= S` and `align_of::<T>() <= align_of::<Self>()`.
176    unsafe fn store<T>(&self, val: T) {
177        // SAFETY: caller guarantees the slot is empty and T fits.
178        unsafe {
179            (*self.buf.get()).as_mut_ptr().cast::<T>().write(val);
180            *self.drop_fn.get() = Some(Self::drop_typed::<T>);
181        }
182    }
183
184    /// # Safety
185    /// Slot must contain a live `T`.
186    unsafe fn take<T>(&self) -> T {
187        // SAFETY: caller guarantees a live T is in the slot.
188        unsafe {
189            let val = (*self.buf.get()).as_ptr().cast::<T>().read();
190            *self.drop_fn.get() = None;
191            val
192        }
193    }
194
195    /// # Safety
196    /// Caller must have exclusive access.
197    ///
198    /// # Panic behavior
199    /// If the stored value's destructor panics, `drop_fn` is already
200    /// cleared so double-drop won't occur
201    unsafe fn drop_contents(&self) {
202        // SAFETY: caller guarantees exclusive access.
203        unsafe {
204            if let Some(f) = (*self.drop_fn.get()).take() {
205                f(self);
206            }
207        }
208    }
209
210    /// # Safety
211    /// `slot` must currently contain a live `T`.
212    unsafe fn drop_typed<T>(slot: &Self) {
213        // SAFETY: caller guarantees the slot contains a live T.
214        unsafe {
215            core::ptr::drop_in_place((*slot.buf.get()).as_mut_ptr().cast::<T>());
216        }
217    }
218}
219
220impl<const S: usize> Drop for Storage<S> {
221    fn drop(&mut self) {
222        // SAFETY: &mut self guarantees exclusive access.
223        unsafe { self.drop_contents() };
224    }
225}
226
227type RunFn<T, const S: usize> = unsafe fn(&Storage<S>, &mut T);
228
229/// # Safety
230/// - `slot` must currently contain a live `F`.
231/// - `R` must fit in the slot.
232///
233/// After return, slot contains a live `R`.
234///
235/// # Panic behavior
236/// If `f(state)` panics, `F` has already been taken from the slot and `R` is
237/// never stored. The slot is left empty (`drop_fn` is `None`).
238unsafe fn run_job<T, R, F: FnOnce(&mut T) -> R, const S: usize>(slot: &Storage<S>, state: &mut T) {
239    // SAFETY: caller guarantees slot contains a live F and R fits.
240    unsafe {
241        let f: F = slot.take();
242        let res = f(state);
243        slot.store(res);
244    }
245}
246
247struct SlotState {
248    free: bool,
249    waker: WakerRegistration,
250}
251
252impl SlotState {
253    const EMPTY: Self = Self {
254        free: true,
255        waker: WakerRegistration::new(),
256    };
257}
258
259#[derive(Clone, Copy)]
260struct RunnerState {
261    running: bool,
262    needs_recovery: bool,
263}
264
265struct JobSlot<M: RawMutex, T, const S: usize> {
266    storage: Storage<S>,
267    state: Mutex<M, RefCell<SlotState>>,
268    job: Signal<M, RunFn<T, S>>,
269    done: Signal<M, ()>,
270    ack: Signal<M, ()>,
271}
272
273impl<M: RawMutex, T, const S: usize> JobSlot<M, T, S> {
274    const fn new() -> Self {
275        Self {
276            storage: Storage::new(),
277            state: Mutex::new(RefCell::new(SlotState::EMPTY)),
278            job: Signal::new(),
279            done: Signal::new(),
280            ack: Signal::new(),
281        }
282    }
283
284    fn with_slot_state<R>(&self, f: impl FnOnce(&mut SlotState) -> R) -> R {
285        self.state.lock(|rc| f(&mut *unwrap!(rc.try_borrow_mut())))
286    }
287
288    fn debug_assert_held(&self) {
289        let free = self.with_slot_state(|s| s.free);
290        debug_assert!(!free, "slot is free but expected to be held");
291    }
292
293    fn poll_acquire(&self, cx: &mut Context<'_>) -> Poll<()> {
294        self.with_slot_state(|s| {
295            if s.free {
296                s.free = false;
297                Poll::Ready(())
298            } else {
299                s.waker.register(cx.waker());
300                Poll::Pending
301            }
302        })
303    }
304
305    fn try_acquire(&self) -> bool {
306        self.with_slot_state(|s| {
307            let was_free = s.free;
308            s.free = false;
309            was_free
310        })
311    }
312
313    /// # Safety
314    /// Caller must have acquired the slot. F and R must fit.
315    unsafe fn submit<R, F: FnOnce(&mut T) -> R>(&self, f: F) {
316        // SAFETY: caller guarantees slot is acquired and F/R fit.
317        unsafe { self.storage.store(f) };
318        self.job.signal(run_job::<T, R, F, S>);
319    }
320
321    /// # Safety
322    /// Caller must have acquired the slot. F must fit.
323    unsafe fn submit_immediate<F: FnOnce(&mut T)>(&self, f: F) {
324        // SAFETY: caller guarantees slot is acquired and F fits.
325        unsafe { self.storage.store(f) };
326        // It is ok to pre-signal ack here because signal retains the value until
327        // consumed, and no CallFuture can send a competing ack until
328        // the runner completes this F.
329        self.ack.signal(());
330        self.job.signal(run_job::<T, (), F, S>);
331    }
332
333    fn mark_free(&self) {
334        self.with_slot_state(|s| {
335            s.free = true;
336            // TODO: check that waking inside the lock is ok
337            s.waker.wake();
338        });
339    }
340
341    fn poll_result<R>(&self, cx: &mut Context<'_>) -> Poll<R> {
342        // TODO: recreating the wait future each poll... Check if ok
343        let mut fut = self.done.wait();
344        match Pin::new(&mut fut).poll(cx) {
345            Poll::Pending => Poll::Pending,
346            Poll::Ready(()) => {
347                self.debug_assert_held();
348                // SAFETY: done was signaled, so the runner wrote R into the slot.
349                let result = unsafe { self.storage.take::<R>() };
350                self.ack.signal(());
351                Poll::Ready(result)
352            }
353        }
354    }
355
356    /// Wait for the caller's ack, then clean up the slot and mark it free.
357    ///
358    /// If the stored value's destructor panics under unwinding, the slot
359    /// is still reset and freed.
360    async fn wait_ack_and_finish(&self, runner_state: &Mutex<M, Cell<RunnerState>>) {
361        struct FinishGuard<'a, M: RawMutex, T, const S: usize> {
362            slot: &'a JobSlot<M, T, S>,
363            runner_state: &'a Mutex<M, Cell<RunnerState>>,
364        }
365        impl<M: RawMutex, T, const S: usize> Drop for FinishGuard<'_, M, T, S> {
366            fn drop(&mut self) {
367                self.runner_state.lock(|cell| {
368                    let mut s = cell.get();
369                    s.needs_recovery = false;
370                    cell.set(s);
371                });
372                self.slot.done.reset();
373                self.slot.mark_free();
374            }
375        }
376
377        self.ack.wait().await;
378        self.debug_assert_held();
379
380        let _guard = FinishGuard {
381            slot: self,
382            runner_state,
383        };
384        // SAFETY: ack received, so the caller is done with the slot.
385        // drop_contents() already guards against double drop.
386        unsafe { self.storage.drop_contents() };
387    }
388}
389
390/// Dispatch closures for execution on a dedicated runner task.
391///
392/// Callers submit an `FnOnce(&mut T) -> R` via [`call`](RpcService::call).
393/// The runner, started with [`run`](RpcService::run), executes closures one at a
394/// time with exclusive `&mut T` access and sends results back. Each call
395/// can return a different type.
396///
397/// Closures and return values are stored inline in a fixed-size slot of `S` bytes.
398/// Both the closure and the return type must fit within `S` bytes and require no
399/// more alignment than the slot. This is checked at compile time.
400///
401/// ## Example
402///
403/// ```rust,ignore
404/// static FS: RpcService<CriticalSectionRawMutex, Filesystem, 64> =
405///     RpcService::new();
406///
407/// // runner task
408/// FS.run(&mut filesystem).await;
409///
410/// // caller task
411/// let size = FS.call(|fs| fs.read_blocking(path).len()).await;
412/// ```
413pub struct RpcService<M: RawMutex, T, const S: usize> {
414    slot: JobSlot<M, T, S>,
415    runner_state: Mutex<M, Cell<RunnerState>>,
416}
417
418impl<M: RawMutex, T, const S: usize> RpcService<M, T, S> {
419    fn with_runner_state<R>(&self, f: impl FnOnce(&mut RunnerState) -> R) -> R {
420        self.runner_state.lock(|cell| {
421            let mut s = cell.get();
422            let r = f(&mut s);
423            cell.set(s);
424            r
425        })
426    }
427
428    /// Create a new `RpcService`.
429    pub const fn new() -> Self {
430        Self {
431            slot: JobSlot::new(),
432            runner_state: Mutex::new(Cell::new(RunnerState {
433                running: false,
434                needs_recovery: false,
435            })),
436        }
437    }
438
439    /// Submit a closure for execution on the runner.
440    ///
441    /// Fails at compile time if `F` or `R` exceeds the slot capacity `S`.
442    ///
443    /// **Note:** Under panic=unwind, if the closure panics, the returned future
444    /// will not complete; it must be dropped for the service to recover.
445    ///
446    /// ## Cancellation
447    ///
448    /// The returned future is cancel-safe: dropping it at any point is
449    /// sound and leaves the service in a usable state. When dropped, the
450    /// closure is either dropped without being called, or executed to
451    /// completion by the runner (with the return value discarded).
452    /// Execution requires that [`run()`](Self::run) is eventually polled
453    /// and the service is not dropped.
454    pub fn call<R, F>(&self, f: F) -> CallFuture<'_, M, T, R, F, S>
455    where
456        F: FnOnce(&mut T) -> R + Send + 'static,
457        R: Send + 'static,
458    {
459        const { assert_slot_fits::<F, R, S>() };
460
461        CallFuture {
462            svc: self,
463            f: Some(f),
464            phase: Phase::Acquiring,
465            _marker: PhantomData,
466        }
467    }
468
469    /// Try to submit a fire-and-forget closure without blocking.
470    ///
471    /// Returns `true` if the closure was submitted, `false` if the slot is busy.
472    /// A submitted closure will be executed during the next [`run()`](Self::run)
473    /// call. If no `run()` is currently active, it remains pending until one
474    /// starts. There is no way to retrieve a return value.
475    pub fn try_call_immediate<F>(&self, f: F) -> bool
476    where
477        F: FnOnce(&mut T) + Send + 'static,
478    {
479        const { assert_slot_fits::<F, (), S>() };
480
481        if !self.slot.try_acquire() {
482            return false;
483        }
484
485        // SAFETY: we just acquired the slot, F fits (compile-time check above).
486        unsafe { self.slot.submit_immediate(f) };
487        true
488    }
489
490    /// Run the service loop, executing closures submitted via [`call`](Self::call)
491    /// with exclusive `&mut T` access. This future must be polled (f.ex spawned as
492    /// a task) for callers to make progress.
493    ///
494    /// # Panics
495    ///
496    /// Panics if called while another `run()` is still active.
497    /// Sequential calls after a previous `run()` was dropped are fine.
498    ///
499    /// # Cancellation
500    ///
501    /// This future is cancel-safe. A subsequent call to `run()` will recover the
502    /// previous state and resume processing any in-flight call.
503    pub async fn run(&self, state: &mut T) -> ! {
504        struct RunGuard<'a, M: RawMutex> {
505            runner_state: &'a Mutex<M, Cell<RunnerState>>,
506        }
507        impl<M: RawMutex> Drop for RunGuard<'_, M> {
508            fn drop(&mut self) {
509                self.runner_state.lock(|cell| {
510                    let mut s = cell.get();
511                    s.running = false;
512                    cell.set(s);
513                });
514            }
515        }
516
517        let needs_recovery = self.with_runner_state(|s| {
518            if s.running {
519                panic!("RpcService::run() must not be called concurrently")
520            }
521            s.running = true;
522            s.needs_recovery
523        });
524        let _guard = RunGuard {
525            runner_state: &self.runner_state,
526        };
527
528        // If the previous runner was cancelled mid-job the caller might still
529        // be interacting with the slot. We must wait for it to finish (the caller
530        // always acks, either explicitly or via its Drop) and then clean up.
531        if needs_recovery {
532            self.slot.wait_ack_and_finish(&self.runner_state).await;
533        }
534
535        loop {
536            // Wait for a caller to submit a closure.
537            // This is a clean cancellation point because no job in flight
538            let run_fn = self.slot.job.wait().await;
539
540            // From here on we may need to recover if cancellation occurs
541            self.with_runner_state(|s| s.needs_recovery = true);
542
543            // SAFETY: slot contains a live F, run_fn matches its types.
544            // No other task can access the slot, because the caller is waiting on done.
545            // If the closure panics under unwinding, done is not signaled. The
546            // caller would then block until dropped, but dropping sends an ack
547            // and then allows for run to make progress.
548            unsafe { run_fn(&self.slot.storage, state) };
549            self.slot.done.signal(());
550
551            // Wait for the caller to read R and signal ack (or for
552            // CallFuture::drop to signal ack on cancellation), then
553            // clean up the slot and mark it free for the next caller.
554            // If cancelled here, needs_recovery is true and the next
555            // run() will wait for ack before touching the slot.
556            self.slot.wait_ack_and_finish(&self.runner_state).await;
557        }
558    }
559}
560
561// SAFETY: access to Storage is serialized by the call/run handshake protocol
562unsafe impl<M: RawMutex, T, const S: usize> Sync for RpcService<M, T, S>
563where
564    Mutex<M, RefCell<SlotState>>: Sync,
565    Mutex<M, Cell<RunnerState>>: Sync,
566    Signal<M, RunFn<T, S>>: Sync,
567    Signal<M, ()>: Sync,
568{
569}
570
571/// State of the [`CallFuture`]
572enum Phase {
573    Acquiring,
574    Submitted,
575    Done,
576}
577
578/// Future returned by [`RpcService::call`].
579///
580/// This future is cancel-safe. See [`RpcService::call`] for details.
581#[must_use = "futures do nothing unless you `.await` or poll them"]
582pub struct CallFuture<'a, M: RawMutex, T, R, F, const S: usize> {
583    svc: &'a RpcService<M, T, S>,
584    f: Option<F>,
585    phase: Phase,
586    _marker: PhantomData<R>,
587}
588
589impl<M: RawMutex, T, R, F, const S: usize> Unpin for CallFuture<'_, M, T, R, F, S> {}
590
591impl<M, T, R, F, const S: usize> Future for CallFuture<'_, M, T, R, F, S>
592where
593    M: RawMutex,
594    F: FnOnce(&mut T) -> R + Send + 'static,
595    R: Send + 'static,
596{
597    type Output = R;
598
599    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R> {
600        loop {
601            match self.phase {
602                Phase::Acquiring => match self.svc.slot.poll_acquire(cx) {
603                    Poll::Pending => return Poll::Pending,
604                    Poll::Ready(()) => {
605                        let f = self.f.take().unwrap();
606                        // SAFETY: we just acquired the slot, F and R fit (compile-time check in call())
607                        unsafe { self.svc.slot.submit::<R, F>(f) };
608                        self.phase = Phase::Submitted;
609                    }
610                },
611                Phase::Submitted => {
612                    return match self.svc.slot.poll_result::<R>(cx) {
613                        Poll::Pending => Poll::Pending,
614                        Poll::Ready(result) => {
615                            self.phase = Phase::Done;
616                            Poll::Ready(result)
617                        }
618                    };
619                }
620                Phase::Done => panic!("CallFuture polled after completion"),
621            }
622        }
623    }
624}
625
626impl<M: RawMutex, T, R, F, const S: usize> Drop for CallFuture<'_, M, T, R, F, S> {
627    fn drop(&mut self) {
628        if matches!(self.phase, Phase::Submitted) {
629            // Future dropped after the closure was written to the slot.
630            // The runner will still finish executing the closure when polled, but we cannot
631            // touch the slot (because the runner may still be using it). We also must not
632            // block, so we signal ack so the runner can cleanup and accept new work.
633            // The two ack paths are mutually exclusive. Either the poll completes,
634            // so ack is sent in poll_result and phase moves to Done synchronously – or we're
635            // dropped while still in Submitted and the ack is sent here. Never both.
636            self.svc.slot.ack.signal(());
637        }
638    }
639}
640
641const fn assert_slot_fits<F, R, const S: usize>() {
642    core::assert!(mem::size_of::<F>() <= S, "closure must fit in slot, increase S");
643    core::assert!(mem::size_of::<R>() <= S, "return type must fit in slot, increase S");
644    core::assert!(
645        mem::align_of::<F>() <= mem::align_of::<Storage<S>>(),
646        "closure alignment must not exceed 8 bytes"
647    );
648    core::assert!(
649        mem::align_of::<R>() <= mem::align_of::<Storage<S>>(),
650        "return type alignment must not exceed 8 bytes"
651    );
652}
653
654#[cfg(test)]
655mod tests {
656    extern crate alloc;
657
658    use alloc::string::String;
659    use alloc::sync::Arc;
660    use alloc::vec::Vec;
661    use core::pin::pin;
662    use core::sync::atomic::{AtomicUsize, Ordering};
663
664    use super::*;
665    use crate::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
666
667    /// Run `caller` against `runner` until the caller completes.
668    async fn drive<R, N>(caller: impl Future<Output = R>, runner: impl Future<Output = N>) -> R {
669        let caller = pin!(caller);
670        let runner = pin!(runner);
671        match futures_util::future::select(caller, runner).await {
672            futures_util::future::Either::Left((r, _)) => r,
673            futures_util::future::Either::Right(_) => unreachable!(),
674        }
675    }
676
677    fn add(n: i32) -> impl FnOnce(&mut i32) -> i32 + Send + 'static {
678        move |s| {
679            *s += n;
680            *s
681        }
682    }
683
684    #[futures_test::test]
685    async fn basic() {
686        static SVC: RpcService<CriticalSectionRawMutex, i32, 64> = RpcService::new();
687        let mut state = 0i32;
688        assert_eq!(drive(SVC.call(add(10)), SVC.run(&mut state)).await, 10);
689    }
690
691    #[futures_test::test]
692    async fn different_return_types() {
693        let svc: RpcService<NoopRawMutex, Vec<String>, 256> = RpcService::new();
694        let mut state = Vec::from([String::from("hello")]);
695        drive(
696            async {
697                assert_eq!(svc.call(|s| s.len()).await, 1);
698                svc.call(|s| s.push("world".into())).await;
699                assert_eq!(svc.call(|s| s.join(" ")).await, "hello world");
700            },
701            svc.run(&mut state),
702        )
703        .await;
704    }
705
706    #[futures_test::test]
707    async fn cancel_before_acquire_then_next_call() {
708        let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
709        let mut state = 0i32;
710        let r = drive(
711            async {
712                let first = svc.call(add(10));
713                let mut first = pin!(first);
714                assert!(futures_util::poll!(first.as_mut()).is_pending());
715
716                {
717                    let fut = svc.call(add(100));
718                    let mut fut = pin!(fut);
719                    assert!(
720                        futures_util::poll!(fut.as_mut()).is_pending(),
721                        "should be pending waiting for slot"
722                    );
723                }
724
725                first.await
726            },
727            svc.run(&mut state),
728        )
729        .await;
730        assert_eq!(r, 10);
731    }
732
733    #[futures_test::test]
734    #[should_panic(expected = "must not be called concurrently")]
735    async fn concurrent_run_panics() {
736        let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
737        let mut s1 = 0;
738        let mut s2 = 0;
739        let a = svc.run(&mut s1);
740        let b = svc.run(&mut s2);
741        let mut a = pin!(a);
742        let mut b = pin!(b);
743        let _ = futures_util::poll!(a.as_mut());
744        let _ = futures_util::poll!(b.as_mut());
745    }
746
747    #[futures_test::test]
748    async fn restart_after_cancel_mid_job() {
749        let svc: RpcService<NoopRawMutex, (), 64> = RpcService::new();
750        let mut state = ();
751
752        let drop_count = Arc::new(AtomicUsize::new(0));
753
754        struct Tracked(Arc<AtomicUsize>);
755        impl Drop for Tracked {
756            fn drop(&mut self) {
757                self.0.fetch_add(1, Ordering::Relaxed);
758            }
759        }
760
761        {
762            let runner = svc.run(&mut state);
763            let mut runner = pin!(runner);
764            let _ = futures_util::poll!(runner.as_mut());
765
766            {
767                let dc = drop_count.clone();
768                let fut = svc.call(move |_| Tracked(dc));
769                let mut fut = pin!(fut);
770                let _ = futures_util::poll!(fut.as_mut());
771                let _ = futures_util::poll!(runner.as_mut());
772            }
773            // Runner dropped while needs_recovery is true.
774        }
775
776        assert_eq!(
777            drop_count.load(Ordering::Relaxed),
778            0,
779            "R should not be dropped before recovery"
780        );
781
782        {
783            let runner = svc.run(&mut state);
784            let mut runner = pin!(runner);
785            let _ = futures_util::poll!(runner.as_mut());
786
787            assert_eq!(drop_count.load(Ordering::Relaxed), 1, "recovery should drop R");
788
789            assert_eq!(drive(svc.call(|_| 42u32), runner).await, 42);
790        }
791    }
792
793    #[futures_test::test]
794    async fn restart_many_cycles() {
795        let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
796        let mut state = 0i32;
797
798        for _ in 0..10 {
799            drive(svc.call(add(1)), svc.run(&mut state)).await;
800        }
801
802        assert_eq!(state, 10);
803    }
804
805    #[futures_test::test]
806    async fn zero_sized_return() {
807        let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
808        let mut state = 0i32;
809        drive(
810            svc.call(|s| {
811                *s += 1;
812            }),
813            svc.run(&mut state),
814        )
815        .await;
816    }
817
818    #[futures_test::test]
819    async fn drop_glue_on_service_drop() {
820        let drop_count = Arc::new(AtomicUsize::new(0));
821
822        struct Payload(Arc<AtomicUsize>);
823        impl Drop for Payload {
824            fn drop(&mut self) {
825                self.0.fetch_add(1, Ordering::Relaxed);
826            }
827        }
828
829        {
830            let svc: RpcService<NoopRawMutex, (), 64> = RpcService::new();
831            let mut state = ();
832            let dc = drop_count.clone();
833            let caller = async {
834                let fut = svc.call(move |_| Payload(dc));
835                let mut fut = pin!(fut);
836                assert!(futures_util::poll!(fut.as_mut()).is_pending());
837            };
838            let runner = svc.run(&mut state);
839            let mut runner = pin!(runner);
840            let _ = futures_util::poll!(runner.as_mut());
841            let mut caller = pin!(caller);
842            let _ = futures_util::poll!(caller.as_mut());
843            let _ = futures_util::poll!(runner.as_mut());
844            drop(caller);
845            let _ = futures_util::poll!(runner.as_mut());
846        }
847        assert_eq!(
848            drop_count.load(Ordering::Relaxed),
849            1,
850            "service drop should drop slot contents"
851        );
852    }
853
854    #[futures_test::test]
855    async fn cancel_after_submit_no_leak() {
856        let drop_count = Arc::new(AtomicUsize::new(0));
857
858        struct Heavy(Arc<AtomicUsize>, #[allow(dead_code)] [u8; 4096]);
859        impl Drop for Heavy {
860            fn drop(&mut self) {
861                self.0.fetch_add(1, Ordering::Relaxed);
862            }
863        }
864
865        let svc: RpcService<NoopRawMutex, (), 4160> = RpcService::new();
866        let mut state = ();
867
868        let runner = svc.run(&mut state);
869        let mut runner = pin!(runner);
870        let _ = futures_util::poll!(runner.as_mut());
871
872        {
873            let dc = drop_count.clone();
874            let fut = svc.call(move |_| Heavy(dc, [0xAB; 4096]));
875            let mut fut = pin!(fut);
876            let _ = futures_util::poll!(fut.as_mut());
877            let _ = futures_util::poll!(runner.as_mut());
878        }
879        assert_eq!(
880            drop_count.load(Ordering::Relaxed),
881            0,
882            "R should not be dropped before runner cleanup"
883        );
884
885        let _ = futures_util::poll!(runner.as_mut());
886
887        drive(svc.call(|_| 42u32), runner).await;
888
889        assert_eq!(
890            drop_count.load(Ordering::Relaxed),
891            1,
892            "runner should drop R during cleanup"
893        );
894    }
895
896    #[futures_test::test]
897    async fn try_call_immediate() {
898        let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
899        let mut state = 0i32;
900
901        assert!(svc.try_call_immediate(|s| *s += 1)); // slot starts free
902        assert!(!svc.try_call_immediate(|s| *s += 100)); // slot busy
903
904        {
905            let runner = svc.run(&mut state);
906            let mut runner = pin!(runner);
907            let _ = futures_util::poll!(runner.as_mut());
908            let _ = futures_util::poll!(runner.as_mut());
909
910            assert_eq!(drive(svc.call(|_| 42u32), runner).await, 42);
911        }
912
913        assert_eq!(state, 1);
914    }
915
916    #[test]
917    #[cfg(feature = "std")]
918    fn destructor_panic_recovery() {
919        // Destructor of return value panics during cleanup after caller was dropped.
920        // FinishGuard should recover the service
921        extern crate std;
922        use std::panic::{AssertUnwindSafe, catch_unwind};
923
924        struct PanicOnDrop;
925        impl Drop for PanicOnDrop {
926            fn drop(&mut self) {
927                panic!("destructor panic");
928            }
929        }
930
931        let svc: RpcService<NoopRawMutex, (), 64> = RpcService::new();
932        let mut state = ();
933
934        let result = catch_unwind(AssertUnwindSafe(|| {
935            futures_executor::block_on(async {
936                let runner = svc.run(&mut state);
937                let mut runner = pin!(runner);
938                let _ = futures_util::poll!(runner.as_mut());
939
940                {
941                    let fut = svc.call(|_| PanicOnDrop);
942                    let mut fut = pin!(fut);
943                    let _ = futures_util::poll!(fut.as_mut());
944                    let _ = futures_util::poll!(runner.as_mut());
945                }
946
947                let _ = futures_util::poll!(runner.as_mut());
948            });
949        }));
950        assert!(result.is_err(), "destructor should have panicked");
951
952        futures_executor::block_on(async {
953            assert_eq!(drive(svc.call(|_| 42u32), svc.run(&mut state)).await, 42);
954        });
955    }
956
957    #[test]
958    #[cfg(feature = "std")]
959    fn closure_panic_recovery() {
960        // The closure panics during execution. Caller is dropped during
961        // unwind, should send ack, and the service recovers
962        extern crate std;
963        use std::panic::{AssertUnwindSafe, catch_unwind};
964
965        let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
966        let mut state = 0i32;
967
968        let result = catch_unwind(AssertUnwindSafe(|| {
969            futures_executor::block_on(async {
970                let fut = svc.call(|_: &mut i32| -> i32 { panic!("closure panic") });
971                let mut fut = pin!(fut);
972
973                let runner = svc.run(&mut state);
974                let mut runner = pin!(runner);
975                let _ = futures_util::poll!(runner.as_mut());
976                let _ = futures_util::poll!(fut.as_mut());
977                let _ = futures_util::poll!(runner.as_mut());
978            });
979        }));
980        assert!(result.is_err(), "closure should have panicked");
981
982        futures_executor::block_on(async {
983            assert_eq!(drive(svc.call(add(1)), svc.run(&mut state)).await, 1);
984        });
985    }
986
987    #[futures_test::test]
988    #[should_panic(expected = "polled after completion")]
989    async fn poll_after_completion_panics() {
990        let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
991        let mut state = 0i32;
992        let runner = svc.run(&mut state);
993        let mut runner = pin!(runner);
994        let _ = futures_util::poll!(runner.as_mut());
995
996        let fut = svc.call(add(1));
997        let mut fut = pin!(fut);
998
999        let _ = futures_util::poll!(fut.as_mut());
1000        let _ = futures_util::poll!(runner.as_mut());
1001        let _ = futures_util::poll!(fut.as_mut());
1002        let _ = futures_util::poll!(runner.as_mut());
1003
1004        let _ = futures_util::poll!(fut.as_mut()); // poll after Done
1005    }
1006
1007    #[futures_test::test]
1008    async fn restart_with_pending_job() {
1009        // Runner is dropped with a pending job in the slot. The
1010        // new runner should process it and not mark the slot free.
1011        let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
1012        let mut state = 0i32;
1013
1014        {
1015            let runner = svc.run(&mut state);
1016            let mut runner = pin!(runner);
1017            let _ = futures_util::poll!(runner.as_mut());
1018        }
1019
1020        let caller = svc.call(add(1));
1021        let mut caller = pin!(caller);
1022        let _ = futures_util::poll!(caller.as_mut());
1023
1024        assert_eq!(drive(caller, svc.run(&mut state)).await, 1);
1025    }
1026}