use core::cell::{Cell, RefCell, UnsafeCell};
use core::future::Future;
use core::marker::PhantomData;
use core::mem::{self, MaybeUninit};
use core::pin::Pin;
use core::task::{Context, Poll};
use crate::blocking_mutex::Mutex;
use crate::blocking_mutex::raw::RawMutex;
use crate::signal::Signal;
use crate::waitqueue::WakerRegistration;
#[repr(C, align(8))] struct Storage<const S: usize> {
buf: UnsafeCell<MaybeUninit<[u8; S]>>,
drop_fn: UnsafeCell<Option<unsafe fn(&Self)>>,
}
impl<const S: usize> Storage<S> {
const fn new() -> Self {
Self {
buf: UnsafeCell::new(MaybeUninit::uninit()),
drop_fn: UnsafeCell::new(None),
}
}
unsafe fn store<T>(&self, val: T) {
unsafe {
(*self.buf.get()).as_mut_ptr().cast::<T>().write(val);
*self.drop_fn.get() = Some(Self::drop_typed::<T>);
}
}
unsafe fn take<T>(&self) -> T {
unsafe {
let val = (*self.buf.get()).as_ptr().cast::<T>().read();
*self.drop_fn.get() = None;
val
}
}
unsafe fn drop_contents(&self) {
unsafe {
if let Some(f) = (*self.drop_fn.get()).take() {
f(self);
}
}
}
unsafe fn drop_typed<T>(slot: &Self) {
unsafe {
core::ptr::drop_in_place((*slot.buf.get()).as_mut_ptr().cast::<T>());
}
}
}
impl<const S: usize> Drop for Storage<S> {
fn drop(&mut self) {
unsafe { self.drop_contents() };
}
}
type RunFn<T, const S: usize> = unsafe fn(&Storage<S>, &mut T);
unsafe fn run_job<T, R, F: FnOnce(&mut T) -> R, const S: usize>(slot: &Storage<S>, state: &mut T) {
unsafe {
let f: F = slot.take();
let res = f(state);
slot.store(res);
}
}
struct SlotState {
free: bool,
waker: WakerRegistration,
}
impl SlotState {
const EMPTY: Self = Self {
free: true,
waker: WakerRegistration::new(),
};
}
#[derive(Clone, Copy)]
struct RunnerState {
running: bool,
needs_recovery: bool,
}
struct JobSlot<M: RawMutex, T, const S: usize> {
storage: Storage<S>,
state: Mutex<M, RefCell<SlotState>>,
job: Signal<M, RunFn<T, S>>,
done: Signal<M, ()>,
ack: Signal<M, ()>,
}
impl<M: RawMutex, T, const S: usize> JobSlot<M, T, S> {
const fn new() -> Self {
Self {
storage: Storage::new(),
state: Mutex::new(RefCell::new(SlotState::EMPTY)),
job: Signal::new(),
done: Signal::new(),
ack: Signal::new(),
}
}
fn with_slot_state<R>(&self, f: impl FnOnce(&mut SlotState) -> R) -> R {
self.state.lock(|rc| f(&mut *unwrap!(rc.try_borrow_mut())))
}
fn debug_assert_held(&self) {
let free = self.with_slot_state(|s| s.free);
debug_assert!(!free, "slot is free but expected to be held");
}
fn poll_acquire(&self, cx: &mut Context<'_>) -> Poll<()> {
self.with_slot_state(|s| {
if s.free {
s.free = false;
Poll::Ready(())
} else {
s.waker.register(cx.waker());
Poll::Pending
}
})
}
fn try_acquire(&self) -> bool {
self.with_slot_state(|s| {
let was_free = s.free;
s.free = false;
was_free
})
}
unsafe fn submit<R, F: FnOnce(&mut T) -> R>(&self, f: F) {
unsafe { self.storage.store(f) };
self.job.signal(run_job::<T, R, F, S>);
}
unsafe fn submit_immediate<F: FnOnce(&mut T)>(&self, f: F) {
unsafe { self.storage.store(f) };
self.ack.signal(());
self.job.signal(run_job::<T, (), F, S>);
}
fn mark_free(&self) {
self.with_slot_state(|s| {
s.free = true;
s.waker.wake();
});
}
fn poll_result<R>(&self, cx: &mut Context<'_>) -> Poll<R> {
let mut fut = self.done.wait();
match Pin::new(&mut fut).poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(()) => {
self.debug_assert_held();
let result = unsafe { self.storage.take::<R>() };
self.ack.signal(());
Poll::Ready(result)
}
}
}
async fn wait_ack_and_finish(&self, runner_state: &Mutex<M, Cell<RunnerState>>) {
struct FinishGuard<'a, M: RawMutex, T, const S: usize> {
slot: &'a JobSlot<M, T, S>,
runner_state: &'a Mutex<M, Cell<RunnerState>>,
}
impl<M: RawMutex, T, const S: usize> Drop for FinishGuard<'_, M, T, S> {
fn drop(&mut self) {
self.runner_state.lock(|cell| {
let mut s = cell.get();
s.needs_recovery = false;
cell.set(s);
});
self.slot.done.reset();
self.slot.mark_free();
}
}
self.ack.wait().await;
self.debug_assert_held();
let _guard = FinishGuard {
slot: self,
runner_state,
};
unsafe { self.storage.drop_contents() };
}
}
pub struct RpcService<M: RawMutex, T, const S: usize> {
slot: JobSlot<M, T, S>,
runner_state: Mutex<M, Cell<RunnerState>>,
}
impl<M: RawMutex, T, const S: usize> RpcService<M, T, S> {
fn with_runner_state<R>(&self, f: impl FnOnce(&mut RunnerState) -> R) -> R {
self.runner_state.lock(|cell| {
let mut s = cell.get();
let r = f(&mut s);
cell.set(s);
r
})
}
pub const fn new() -> Self {
Self {
slot: JobSlot::new(),
runner_state: Mutex::new(Cell::new(RunnerState {
running: false,
needs_recovery: false,
})),
}
}
pub fn call<R, F>(&self, f: F) -> CallFuture<'_, M, T, R, F, S>
where
F: FnOnce(&mut T) -> R + Send + 'static,
R: Send + 'static,
{
const { assert_slot_fits::<F, R, S>() };
CallFuture {
svc: self,
f: Some(f),
phase: Phase::Acquiring,
_marker: PhantomData,
}
}
pub fn try_call_immediate<F>(&self, f: F) -> bool
where
F: FnOnce(&mut T) + Send + 'static,
{
const { assert_slot_fits::<F, (), S>() };
if !self.slot.try_acquire() {
return false;
}
unsafe { self.slot.submit_immediate(f) };
true
}
pub async fn run(&self, state: &mut T) -> ! {
struct RunGuard<'a, M: RawMutex> {
runner_state: &'a Mutex<M, Cell<RunnerState>>,
}
impl<M: RawMutex> Drop for RunGuard<'_, M> {
fn drop(&mut self) {
self.runner_state.lock(|cell| {
let mut s = cell.get();
s.running = false;
cell.set(s);
});
}
}
let needs_recovery = self.with_runner_state(|s| {
if s.running {
panic!("RpcService::run() must not be called concurrently")
}
s.running = true;
s.needs_recovery
});
let _guard = RunGuard {
runner_state: &self.runner_state,
};
if needs_recovery {
self.slot.wait_ack_and_finish(&self.runner_state).await;
}
loop {
let run_fn = self.slot.job.wait().await;
self.with_runner_state(|s| s.needs_recovery = true);
unsafe { run_fn(&self.slot.storage, state) };
self.slot.done.signal(());
self.slot.wait_ack_and_finish(&self.runner_state).await;
}
}
}
unsafe impl<M: RawMutex, T, const S: usize> Sync for RpcService<M, T, S>
where
Mutex<M, RefCell<SlotState>>: Sync,
Mutex<M, Cell<RunnerState>>: Sync,
Signal<M, RunFn<T, S>>: Sync,
Signal<M, ()>: Sync,
{
}
enum Phase {
Acquiring,
Submitted,
Done,
}
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct CallFuture<'a, M: RawMutex, T, R, F, const S: usize> {
svc: &'a RpcService<M, T, S>,
f: Option<F>,
phase: Phase,
_marker: PhantomData<R>,
}
impl<M: RawMutex, T, R, F, const S: usize> Unpin for CallFuture<'_, M, T, R, F, S> {}
impl<M, T, R, F, const S: usize> Future for CallFuture<'_, M, T, R, F, S>
where
M: RawMutex,
F: FnOnce(&mut T) -> R + Send + 'static,
R: Send + 'static,
{
type Output = R;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R> {
loop {
match self.phase {
Phase::Acquiring => match self.svc.slot.poll_acquire(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(()) => {
let f = self.f.take().unwrap();
unsafe { self.svc.slot.submit::<R, F>(f) };
self.phase = Phase::Submitted;
}
},
Phase::Submitted => {
return match self.svc.slot.poll_result::<R>(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(result) => {
self.phase = Phase::Done;
Poll::Ready(result)
}
};
}
Phase::Done => panic!("CallFuture polled after completion"),
}
}
}
}
impl<M: RawMutex, T, R, F, const S: usize> Drop for CallFuture<'_, M, T, R, F, S> {
fn drop(&mut self) {
if matches!(self.phase, Phase::Submitted) {
self.svc.slot.ack.signal(());
}
}
}
const fn assert_slot_fits<F, R, const S: usize>() {
core::assert!(mem::size_of::<F>() <= S, "closure must fit in slot, increase S");
core::assert!(mem::size_of::<R>() <= S, "return type must fit in slot, increase S");
core::assert!(
mem::align_of::<F>() <= mem::align_of::<Storage<S>>(),
"closure alignment must not exceed 8 bytes"
);
core::assert!(
mem::align_of::<R>() <= mem::align_of::<Storage<S>>(),
"return type alignment must not exceed 8 bytes"
);
}
#[cfg(test)]
mod tests {
extern crate alloc;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::pin::pin;
use core::sync::atomic::{AtomicUsize, Ordering};
use super::*;
use crate::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
async fn drive<R, N>(caller: impl Future<Output = R>, runner: impl Future<Output = N>) -> R {
let caller = pin!(caller);
let runner = pin!(runner);
match futures_util::future::select(caller, runner).await {
futures_util::future::Either::Left((r, _)) => r,
futures_util::future::Either::Right(_) => unreachable!(),
}
}
fn add(n: i32) -> impl FnOnce(&mut i32) -> i32 + Send + 'static {
move |s| {
*s += n;
*s
}
}
#[futures_test::test]
async fn basic() {
static SVC: RpcService<CriticalSectionRawMutex, i32, 64> = RpcService::new();
let mut state = 0i32;
assert_eq!(drive(SVC.call(add(10)), SVC.run(&mut state)).await, 10);
}
#[futures_test::test]
async fn different_return_types() {
let svc: RpcService<NoopRawMutex, Vec<String>, 256> = RpcService::new();
let mut state = Vec::from([String::from("hello")]);
drive(
async {
assert_eq!(svc.call(|s| s.len()).await, 1);
svc.call(|s| s.push("world".into())).await;
assert_eq!(svc.call(|s| s.join(" ")).await, "hello world");
},
svc.run(&mut state),
)
.await;
}
#[futures_test::test]
async fn cancel_before_acquire_then_next_call() {
let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
let mut state = 0i32;
let r = drive(
async {
let first = svc.call(add(10));
let mut first = pin!(first);
assert!(futures_util::poll!(first.as_mut()).is_pending());
{
let fut = svc.call(add(100));
let mut fut = pin!(fut);
assert!(
futures_util::poll!(fut.as_mut()).is_pending(),
"should be pending waiting for slot"
);
}
first.await
},
svc.run(&mut state),
)
.await;
assert_eq!(r, 10);
}
#[futures_test::test]
#[should_panic(expected = "must not be called concurrently")]
async fn concurrent_run_panics() {
let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
let mut s1 = 0;
let mut s2 = 0;
let a = svc.run(&mut s1);
let b = svc.run(&mut s2);
let mut a = pin!(a);
let mut b = pin!(b);
let _ = futures_util::poll!(a.as_mut());
let _ = futures_util::poll!(b.as_mut());
}
#[futures_test::test]
async fn restart_after_cancel_mid_job() {
let svc: RpcService<NoopRawMutex, (), 64> = RpcService::new();
let mut state = ();
let drop_count = Arc::new(AtomicUsize::new(0));
struct Tracked(Arc<AtomicUsize>);
impl Drop for Tracked {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
}
{
let runner = svc.run(&mut state);
let mut runner = pin!(runner);
let _ = futures_util::poll!(runner.as_mut());
{
let dc = drop_count.clone();
let fut = svc.call(move |_| Tracked(dc));
let mut fut = pin!(fut);
let _ = futures_util::poll!(fut.as_mut());
let _ = futures_util::poll!(runner.as_mut());
}
}
assert_eq!(
drop_count.load(Ordering::Relaxed),
0,
"R should not be dropped before recovery"
);
{
let runner = svc.run(&mut state);
let mut runner = pin!(runner);
let _ = futures_util::poll!(runner.as_mut());
assert_eq!(drop_count.load(Ordering::Relaxed), 1, "recovery should drop R");
assert_eq!(drive(svc.call(|_| 42u32), runner).await, 42);
}
}
#[futures_test::test]
async fn restart_many_cycles() {
let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
let mut state = 0i32;
for _ in 0..10 {
drive(svc.call(add(1)), svc.run(&mut state)).await;
}
assert_eq!(state, 10);
}
#[futures_test::test]
async fn zero_sized_return() {
let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
let mut state = 0i32;
drive(
svc.call(|s| {
*s += 1;
}),
svc.run(&mut state),
)
.await;
}
#[futures_test::test]
async fn drop_glue_on_service_drop() {
let drop_count = Arc::new(AtomicUsize::new(0));
struct Payload(Arc<AtomicUsize>);
impl Drop for Payload {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
}
{
let svc: RpcService<NoopRawMutex, (), 64> = RpcService::new();
let mut state = ();
let dc = drop_count.clone();
let caller = async {
let fut = svc.call(move |_| Payload(dc));
let mut fut = pin!(fut);
assert!(futures_util::poll!(fut.as_mut()).is_pending());
};
let runner = svc.run(&mut state);
let mut runner = pin!(runner);
let _ = futures_util::poll!(runner.as_mut());
let mut caller = pin!(caller);
let _ = futures_util::poll!(caller.as_mut());
let _ = futures_util::poll!(runner.as_mut());
drop(caller);
let _ = futures_util::poll!(runner.as_mut());
}
assert_eq!(
drop_count.load(Ordering::Relaxed),
1,
"service drop should drop slot contents"
);
}
#[futures_test::test]
async fn cancel_after_submit_no_leak() {
let drop_count = Arc::new(AtomicUsize::new(0));
struct Heavy(Arc<AtomicUsize>, #[allow(dead_code)] [u8; 4096]);
impl Drop for Heavy {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
}
let svc: RpcService<NoopRawMutex, (), 4160> = RpcService::new();
let mut state = ();
let runner = svc.run(&mut state);
let mut runner = pin!(runner);
let _ = futures_util::poll!(runner.as_mut());
{
let dc = drop_count.clone();
let fut = svc.call(move |_| Heavy(dc, [0xAB; 4096]));
let mut fut = pin!(fut);
let _ = futures_util::poll!(fut.as_mut());
let _ = futures_util::poll!(runner.as_mut());
}
assert_eq!(
drop_count.load(Ordering::Relaxed),
0,
"R should not be dropped before runner cleanup"
);
let _ = futures_util::poll!(runner.as_mut());
drive(svc.call(|_| 42u32), runner).await;
assert_eq!(
drop_count.load(Ordering::Relaxed),
1,
"runner should drop R during cleanup"
);
}
#[futures_test::test]
async fn try_call_immediate() {
let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
let mut state = 0i32;
assert!(svc.try_call_immediate(|s| *s += 1)); assert!(!svc.try_call_immediate(|s| *s += 100));
{
let runner = svc.run(&mut state);
let mut runner = pin!(runner);
let _ = futures_util::poll!(runner.as_mut());
let _ = futures_util::poll!(runner.as_mut());
assert_eq!(drive(svc.call(|_| 42u32), runner).await, 42);
}
assert_eq!(state, 1);
}
#[test]
#[cfg(feature = "std")]
fn destructor_panic_recovery() {
extern crate std;
use std::panic::{AssertUnwindSafe, catch_unwind};
struct PanicOnDrop;
impl Drop for PanicOnDrop {
fn drop(&mut self) {
panic!("destructor panic");
}
}
let svc: RpcService<NoopRawMutex, (), 64> = RpcService::new();
let mut state = ();
let result = catch_unwind(AssertUnwindSafe(|| {
futures_executor::block_on(async {
let runner = svc.run(&mut state);
let mut runner = pin!(runner);
let _ = futures_util::poll!(runner.as_mut());
{
let fut = svc.call(|_| PanicOnDrop);
let mut fut = pin!(fut);
let _ = futures_util::poll!(fut.as_mut());
let _ = futures_util::poll!(runner.as_mut());
}
let _ = futures_util::poll!(runner.as_mut());
});
}));
assert!(result.is_err(), "destructor should have panicked");
futures_executor::block_on(async {
assert_eq!(drive(svc.call(|_| 42u32), svc.run(&mut state)).await, 42);
});
}
#[test]
#[cfg(feature = "std")]
fn closure_panic_recovery() {
extern crate std;
use std::panic::{AssertUnwindSafe, catch_unwind};
let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
let mut state = 0i32;
let result = catch_unwind(AssertUnwindSafe(|| {
futures_executor::block_on(async {
let fut = svc.call(|_: &mut i32| -> i32 { panic!("closure panic") });
let mut fut = pin!(fut);
let runner = svc.run(&mut state);
let mut runner = pin!(runner);
let _ = futures_util::poll!(runner.as_mut());
let _ = futures_util::poll!(fut.as_mut());
let _ = futures_util::poll!(runner.as_mut());
});
}));
assert!(result.is_err(), "closure should have panicked");
futures_executor::block_on(async {
assert_eq!(drive(svc.call(add(1)), svc.run(&mut state)).await, 1);
});
}
#[futures_test::test]
#[should_panic(expected = "polled after completion")]
async fn poll_after_completion_panics() {
let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
let mut state = 0i32;
let runner = svc.run(&mut state);
let mut runner = pin!(runner);
let _ = futures_util::poll!(runner.as_mut());
let fut = svc.call(add(1));
let mut fut = pin!(fut);
let _ = futures_util::poll!(fut.as_mut());
let _ = futures_util::poll!(runner.as_mut());
let _ = futures_util::poll!(fut.as_mut());
let _ = futures_util::poll!(runner.as_mut());
let _ = futures_util::poll!(fut.as_mut()); }
#[futures_test::test]
async fn restart_with_pending_job() {
let svc: RpcService<NoopRawMutex, i32, 64> = RpcService::new();
let mut state = 0i32;
{
let runner = svc.run(&mut state);
let mut runner = pin!(runner);
let _ = futures_util::poll!(runner.as_mut());
}
let caller = svc.call(add(1));
let mut caller = pin!(caller);
let _ = futures_util::poll!(caller.as_mut());
assert_eq!(drive(caller, svc.run(&mut state)).await, 1);
}
}