use crate::signal::{batch, create_signal, ReadSignal, WriteSignal};
use std::cell::Cell;
use std::future::Future;
use std::rc::Rc;
pub struct Action<I, O: 'static> {
pending: ReadSignal<bool>,
value: ReadSignal<Option<O>>,
error: ReadSignal<Option<String>>,
set_pending: WriteSignal<bool>,
set_value: WriteSignal<Option<O>>,
set_error: WriteSignal<Option<String>>,
run: Rc<dyn Fn(I) -> GuardedFuture<O>>,
generation: Rc<Cell<u64>>,
}
use std::pin::Pin;
impl<I, O: 'static> Clone for Action<I, O> {
fn clone(&self) -> Self {
Self {
pending: self.pending.clone(),
value: self.value.clone(),
error: self.error.clone(),
set_pending: self.set_pending.clone(),
set_value: self.set_value.clone(),
set_error: self.set_error.clone(),
run: self.run.clone(),
generation: self.generation.clone(),
}
}
}
impl<I, O> Action<I, O>
where
I: 'static,
O: Clone + 'static,
{
pub fn pending(&self) -> ReadSignal<bool> {
self.pending.clone()
}
pub fn value(&self) -> ReadSignal<Option<O>> {
self.value.clone()
}
pub fn error(&self) -> ReadSignal<Option<String>> {
self.error.clone()
}
pub fn dispatch(&self, input: I) {
let set_pending = self.set_pending.clone();
let set_value = self.set_value.clone();
let set_error = self.set_error.clone();
run_guarded(
&self.generation,
|| {
batch(|| {
self.set_pending.set(true);
self.set_error.set(None);
})
},
|| (self.run)(input),
move |outcome| {
set_pending.set(false);
match outcome {
Ok(value) => set_value.set(Some(value)),
Err(message) => set_error.set(Some(message)),
}
},
);
}
}
pub fn create_action<I, O, F, Fut, E>(f: F) -> Action<I, O>
where
I: 'static,
O: Clone + 'static,
F: Fn(I) -> Fut + 'static,
Fut: Future<Output = Result<O, E>> + 'static,
E: std::fmt::Display + 'static,
{
let (pending, set_pending) = create_signal(false);
let (value, set_value) = create_signal(None);
let (error, set_error) = create_signal(None);
Action {
pending,
value,
error,
set_pending,
set_value,
set_error,
run: flatten_display_errors(f),
generation: Rc::new(Cell::new(0)),
}
}
pub(crate) type GuardedFuture<T> = Pin<Box<dyn Future<Output = Result<T, String>>>>;
pub(crate) fn flatten_display_errors<I, T, F, Fut, E>(f: F) -> Rc<dyn Fn(I) -> GuardedFuture<T>>
where
F: Fn(I) -> Fut + 'static,
Fut: Future<Output = Result<T, E>> + 'static,
E: std::fmt::Display + 'static,
{
Rc::new(move |input| {
let fut = f(input);
Box::pin(async move { fut.await.map_err(|e| e.to_string()) })
})
}
pub(crate) fn run_guarded<T: 'static>(
generation: &Rc<Cell<u64>>,
begin: impl FnOnce(),
make_future: impl FnOnce() -> GuardedFuture<T>,
apply: impl FnOnce(Result<T, String>) + 'static,
) {
if !DISPATCH_HAS_EXECUTOR {
return;
}
run_on_executor(generation, begin, make_future, apply);
}
fn run_on_executor<T: 'static>(
generation: &Rc<Cell<u64>>,
begin: impl FnOnce(),
make_future: impl FnOnce() -> GuardedFuture<T>,
apply: impl FnOnce(Result<T, String>) + 'static,
) {
let current = generation.get().wrapping_add(1);
generation.set(current);
let future = make_future();
begin();
let expected = generation.clone();
spawn_local_task(async move {
let outcome = CatchUnwind { inner: future }.await;
if expected.get() != current {
return;
}
batch(|| apply(outcome));
});
}
struct CatchUnwind<T> {
inner: GuardedFuture<T>,
}
impl<T> Future for CatchUnwind<T> {
type Output = Result<T, String>;
fn poll(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
let inner = &mut self.get_mut().inner;
let result =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| inner.as_mut().poll(cx)));
match result {
Ok(poll) => poll,
Err(payload) => std::task::Poll::Ready(Err(panic_message(payload))),
}
}
}
fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
if let Some(message) = payload.downcast_ref::<&str>() {
(*message).to_string()
} else if let Some(message) = payload.downcast_ref::<String>() {
message.clone()
} else {
"operation panicked".to_string()
}
}
#[cfg(target_arch = "wasm32")]
pub(crate) const DISPATCH_HAS_EXECUTOR: bool = true;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const DISPATCH_HAS_EXECUTOR: bool = false;
#[cfg(target_arch = "wasm32")]
pub(crate) fn spawn_local_task<F>(future: F)
where
F: Future<Output = ()> + 'static,
{
wasm_bindgen_futures::spawn_local(future);
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn spawn_local_task<F>(future: F)
where
F: Future<Output = ()> + 'static,
{
drop(future);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dispatch_is_inert_during_server_side_rendering() {
let action = create_action(|input: u32| async move { Ok::<_, String>(input * 2) });
for _ in 0..3 {
action.dispatch(21);
}
assert!(
!action.pending().get(),
"dispatch must not latch pending where there is no executor to clear it"
);
assert_eq!(action.value().get(), None);
assert_eq!(action.error().get(), None);
}
#[test]
fn the_signals_are_readable_and_idle_before_any_dispatch() {
let action = create_action(|_: ()| async move { Ok::<_, String>(1u32) });
assert!(!action.pending().get());
assert_eq!(action.value().get(), None);
assert_eq!(action.error().get(), None);
}
#[test]
fn clones_share_the_same_signals_natively() {
let action = create_action(|_: ()| async move { Ok::<_, String>(1u32) });
let observer = action.clone();
action.dispatch(());
assert!(!observer.pending().get());
assert_eq!(observer.value().get(), None);
}
#[test]
fn a_panicking_future_factory_does_not_reach_begin() {
let generation = Rc::new(Cell::new(0u64));
let began = Rc::new(Cell::new(false));
let began_probe = began.clone();
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
run_on_executor(
&generation,
move || began_probe.set(true),
|| -> GuardedFuture<u32> { panic!("building the operation failed") },
|_outcome| {},
);
}));
assert!(panicked.is_err(), "the factory panic must propagate");
assert!(
!began.get(),
"begin must not run when the factory panics: pending would latch \
with no future left to clear it"
);
}
#[test]
fn a_panicking_operation_resolves_to_the_error_outcome() {
let future: GuardedFuture<u32> = Box::pin(async { panic!("operation failed mid-flight") });
let outcome = tokio_test::block_on(CatchUnwind { inner: future });
match outcome {
Err(message) => assert!(
message.contains("operation failed mid-flight"),
"the panic message must reach the error state, got: {message}"
),
Ok(_) => panic!("a panicking operation must resolve to Err"),
}
}
}