use formars_signals::{FormController, FormSnapshot, FormaError, SubmitError};
use leptos::callback::Callback;
use leptos::prelude::*;
use leptos::task::spawn_local;
use reactive_graph::traits::Update;
use std::future::Future;
#[derive(Clone, Debug)]
pub enum SubmitOutcome<T, E> {
Success(T),
HandlerError(E),
ValidationFailed(FormaError),
}
pub(crate) fn map_outcome<T, E>(result: Result<T, SubmitError<E>>) -> SubmitOutcome<T, E> {
match result {
Ok(t) => SubmitOutcome::Success(t),
Err(SubmitError::Validation(e)) => SubmitOutcome::ValidationFailed(e),
Err(SubmitError::Handler(e)) => SubmitOutcome::HandlerError(e),
}
}
pub(crate) const BEGIN_ATTEMPT_MAX_TRIES: usize = 8;
pub(crate) fn begin_attempt(controller: &FormController) -> bool {
let mut acquired = None;
for _ in 0..BEGIN_ATTEMPT_MAX_TRIES {
match controller.is_submitting().try_maybe_update(|in_flight| {
if *in_flight {
(false, false)
} else {
*in_flight = true;
(true, true)
}
}) {
Some(result) => {
acquired = Some(result);
break;
}
None => std::thread::yield_now(),
}
}
if acquired.unwrap_or(false) {
controller.submitted().set(true);
true
} else {
false
}
}
pub(crate) async fn finish_attempt<T, E, F, Fut>(
controller: &FormController,
handler: F,
) -> SubmitOutcome<T, E>
where
T: 'static,
E: 'static,
F: FnOnce(FormSnapshot) -> Fut,
Fut: Future<Output = Result<T, E>>,
{
let result = controller.on_submit(handler).await;
map_outcome(result)
}
#[component]
#[allow(
clippy::needless_pass_by_value,
reason = "leptos typed-builder prop convention"
)]
pub fn Form<T, E, F, Fut>(
controller: FormController,
#[prop(into)] on_outcome: Callback<SubmitOutcome<T, E>>,
on_submit: F,
#[prop(optional)] submit_label: Option<String>,
children: Children,
) -> impl IntoView
where
T: 'static,
E: 'static,
F: Fn(FormSnapshot) -> Fut + Clone + 'static,
Fut: Future<Output = Result<T, E>> + 'static,
{
let ctrl_for_button = controller.clone();
view! {
<form on:submit=move |ev| {
ev.prevent_default();
if !begin_attempt(&controller) {
return;
}
let handler = on_submit.clone();
let outcome_cb = on_outcome;
let ctrl = controller.clone();
spawn_local(async move {
let outcome = finish_attempt(&ctrl, handler).await;
outcome_cb.run(outcome);
});
}>
{children()}
{move || {
submit_label.clone().map(|label| {
let is_submitting = ctrl_for_button.is_submitting();
view! {
<button type="submit" disabled=move || is_submitting.get()>
{label}
</button>
}
})
}}
</form>
}
}
#[cfg(test)]
mod tests {
use super::*;
use formars_signals::{FieldPath, IssueCode};
use std::borrow::Cow;
#[test]
fn begin_attempt_budget_is_exactly_eight_total_attempts() {
assert_eq!(
BEGIN_ATTEMPT_MAX_TRIES, 8,
"8 = 1 initial attempt + 7 retries under transient contention"
);
}
fn sample_error() -> FormaError {
FormaError {
issues: vec![formars_signals::FormaIssue {
path: FieldPath::key("email"),
code: IssueCode::Min,
message: Cow::Borrowed("too short"),
params: Vec::new(),
}],
}
}
#[test]
fn ok_maps_to_success_preserving_payload() {
let mapped: SubmitOutcome<u32, String> = map_outcome(Ok(7u32));
assert!(
matches!(mapped, SubmitOutcome::Success(7)),
"Ok must map to Success carrying the payload"
);
}
#[test]
fn validation_error_maps_to_validation_failed_with_payload() {
let mapped: SubmitOutcome<(), FormaError> =
map_outcome(Err(SubmitError::Validation(sample_error())));
match mapped {
SubmitOutcome::ValidationFailed(e) => {
assert_eq!(e.issues.len(), 1, "validation payload must be preserved");
assert_eq!(e.issues[0].path, FieldPath::key("email"));
}
other => panic!("expected ValidationFailed, got {other:?}"),
}
}
#[test]
fn handler_error_maps_to_handler_error_preserving_e() {
let mapped: SubmitOutcome<(), FormaError> =
map_outcome(Err(SubmitError::Handler(sample_error())));
match mapped {
SubmitOutcome::HandlerError(e) => {
assert_eq!(e.issues.len(), 1, "handler error payload E preserved");
}
other => panic!("expected HandlerError, got {other:?}"),
}
}
}
#[cfg(test)]
mod glue {
use super::*;
use formars_core::prelude::*;
use formars_signals::ValidateOn;
use futures::executor::block_on;
use reactive_graph::traits::Get;
use std::cell::RefCell;
use std::rc::Rc;
fn controller_with_invalid_email() -> FormController {
let mut c = FormController::new(ValidateOn::Submit);
c.register(FieldPath::key("email"), Box::new(string().min(8).email()))
.unwrap();
c.field(&FieldPath::key("email")).unwrap().set_str("ab");
c
}
fn controller_with_valid_email() -> FormController {
let mut c = FormController::new(ValidateOn::Submit);
c.register(FieldPath::key("email"), Box::new(string().min(8).email()))
.unwrap();
c.field(&FieldPath::key("email"))
.unwrap()
.set_str("user@example.com");
c
}
fn form_attempt<T, E, F, Fut>(
controller: &FormController,
handler: F,
) -> impl Future<Output = SubmitOutcome<T, E>>
where
T: 'static,
E: 'static,
F: FnOnce(FormSnapshot) -> Fut,
Fut: Future<Output = Result<T, E>>,
{
let proceed = begin_attempt(controller);
let ctrl = controller.clone();
async move {
if proceed {
finish_attempt(&ctrl, handler).await
} else {
unreachable!("fresh controllers are never mid-submit")
}
}
}
#[test]
fn fm2_submitted_flip_precedes_future() {
let controller = controller_with_valid_email();
let observed = Rc::new(RefCell::new(None));
let obs = observed.clone();
let view = controller.clone();
block_on(form_attempt(&controller, move |_snap| {
*obs.borrow_mut() = Some(view.submitted().get());
async { Ok::<(), std::convert::Infallible>(()) }
}));
assert_eq!(
*observed.borrow(),
Some(true),
"`submitted` must read true at the first handler await point"
);
assert!(controller.submitted().get());
}
#[test]
fn fm3_non_send_handler_accepted() {
let controller = controller_with_valid_email();
let state = Rc::new(RefCell::new(String::from("local")));
let captured = state.clone();
let outcome = block_on(finish_attempt(&controller, move |_snap| {
let captured = captured.clone();
async move {
captured.borrow_mut().push_str("-done");
Ok::<String, std::convert::Infallible>(captured.borrow().clone())
}
}));
match outcome {
SubmitOutcome::Success(s) => assert_eq!(s, "local-done"),
other => panic!("non-Send handler must complete, got {other:?}"),
}
assert_eq!(state.borrow().as_str(), "local-done");
}
#[test]
fn fm5_invalid_blocks_handler() {
let controller = controller_with_invalid_email();
let invoked = Rc::new(RefCell::new(false));
let flag = invoked.clone();
let outcome = block_on(finish_attempt(&controller, move |_snap| {
flag.replace(true); async { Ok::<(), std::convert::Infallible>(()) }
}));
assert!(
matches!(outcome, SubmitOutcome::ValidationFailed(_)),
"validation failure must surface as ValidationFailed"
);
assert!(
!*invoked.borrow(),
"handler must never be constructed when validation fails"
);
}
#[test]
fn fm5_valid_brackets_is_submitting_on_success_and_error() {
for expect_ok in [true, false] {
let controller = controller_with_valid_email();
let during = Rc::new(RefCell::new(None));
let d = during.clone();
let c2 = controller.clone();
let outcome = block_on(finish_attempt(&controller, move |_snap| {
let d = d.clone();
let c3 = c2.clone();
async move {
d.replace(Some(c3.is_submitting().get()));
if expect_ok {
Ok::<(), String>(())
} else {
Err(String::from("boom"))
}
}
}));
assert_eq!(
*during.borrow(),
Some(true),
"is_submitting true while handler pending"
);
assert!(
!controller.is_submitting().get(),
"bracket closes after settle"
);
if expect_ok {
assert!(matches!(outcome, SubmitOutcome::Success(())));
} else {
assert!(
matches!(&outcome, SubmitOutcome::HandlerError(e) if e == "boom"),
"handler error path must also close the bracket"
);
}
}
}
#[test]
fn fm5_success_surfaced_once_through_callback() {
let controller = controller_with_valid_email();
let collected: std::sync::Arc<std::sync::Mutex<Vec<SubmitOutcome<(), String>>>> =
std::sync::Arc::default();
let sink = collected.clone();
let on_outcome = Callback::new(move |o: SubmitOutcome<(), String>| {
sink.lock().unwrap().push(o);
});
let outcome = block_on(finish_attempt(&controller, |_snap| async {
Ok::<(), String>(())
}));
on_outcome.run(outcome);
let got = collected.lock().unwrap();
assert_eq!(got.len(), 1, "success delivered exactly once");
assert!(matches!(got[0], SubmitOutcome::Success(())));
}
#[test]
fn guard_rejects_second_synchronous_attempt() {
let controller = controller_with_valid_email();
assert!(begin_attempt(&controller), "first attempt proceeds");
assert!(
!begin_attempt(&controller),
"second same-tick attempt must be rejected"
);
assert!(controller.is_submitting().get());
let outcome: SubmitOutcome<(), std::convert::Infallible> =
block_on(finish_attempt(&controller, |_snap| async { Ok(()) }));
assert!(matches!(outcome, SubmitOutcome::Success(())));
assert!(
!controller.is_submitting().get(),
"drop guard closes the bracket after the attempt settles"
);
}
#[test]
fn guard_rejects_attempt_while_in_flight() {
use reactive_graph::traits::Set;
let controller = controller_with_valid_email();
controller.is_submitting().set(true);
assert!(
!begin_attempt(&controller),
"in-flight guard must reject attempts while submitting"
);
}
#[test]
fn cas_loser_leaves_no_trace() {
use reactive_graph::traits::Set;
let controller = controller_with_valid_email();
controller.is_submitting().set(true);
assert!(!begin_attempt(&controller), "loser must be rejected");
assert!(
!controller.submitted().get(),
"`submitted` byte-identical after the loser: still false"
);
assert!(
controller.is_submitting().get(),
"in-flight flag unchanged by the loser"
);
}
#[test]
fn cas_exactly_one_winner_per_round_across_threads() {
use std::sync::{Arc, Barrier, Mutex};
const THREADS: usize = 8;
const ROUNDS: usize = 16;
let controller = Arc::new(controller_with_valid_email());
let winners: Arc<Mutex<Vec<usize>>> = Arc::default();
let started = Arc::new(Barrier::new(THREADS));
let attempted = Arc::new(Barrier::new(THREADS));
let workers: Vec<_> = (0..THREADS)
.map(|_| {
let controller = controller.clone();
let winners = winners.clone();
let started = started.clone();
let attempted = attempted.clone();
std::thread::spawn(move || {
for round in 0..ROUNDS {
started.wait();
if begin_attempt(&controller) {
winners.lock().unwrap().push(round);
attempted.wait();
let outcome: SubmitOutcome<(), std::convert::Infallible> =
block_on(finish_attempt(&controller, |_snap| async { Ok(()) }));
assert!(
matches!(outcome, SubmitOutcome::Success(())),
"winner's attempt must settle cleanly"
);
} else {
attempted.wait();
}
}
})
})
.collect();
for worker in workers {
worker.join().expect("no worker panics");
}
let wins = winners.lock().unwrap().clone();
let mut per_round = [0usize; ROUNDS];
for round in &wins {
per_round[*round] += 1;
}
assert!(
per_round.iter().all(|&count| count == 1),
"exactly ONE winner per round required; got {per_round:?} \
(total {} over {ROUNDS} rounds)",
wins.len()
);
assert_eq!(wins.len(), ROUNDS, "exactly R winners across R rounds");
assert!(
!controller.is_submitting().get(),
"flag fully restored after join"
);
}
}