Skip to main content

formars_ui/
form.rs

1//! `<Form>` submit wrapper and outcome mapping.
2
3use formars_signals::{FormController, FormSnapshot, FormaError, SubmitError};
4use leptos::callback::Callback;
5use leptos::prelude::*;
6use leptos::task::spawn_local;
7use reactive_graph::traits::Update;
8use std::future::Future;
9
10/// Mirrors [`SubmitError`] arms plus success, delivered to the caller's
11/// `on_outcome` callback.
12#[derive(Clone, Debug)]
13pub enum SubmitOutcome<T, E> {
14    /// The handler resolved `Ok(t)`.
15    Success(T),
16    /// The handler ran and failed with its own error. The caller MAY map
17    /// payloads back with [`FormController::apply_server_errors`].
18    HandlerError(E),
19    /// Whole-form sync validation rejected the form BEFORE the handler was
20    /// constructed. Per-field `visible_errors` already reflect violations;
21    /// `<Form>` performs no additional error injection.
22    ValidationFailed(FormaError),
23}
24
25/// Routes a composed submit result into the caller-facing outcome enum.
26/// Pure: no reactivity, no allocation beyond the payload move.
27pub(crate) fn map_outcome<T, E>(result: Result<T, SubmitError<E>>) -> SubmitOutcome<T, E> {
28    match result {
29        Ok(t) => SubmitOutcome::Success(t),
30        Err(SubmitError::Validation(e)) => SubmitOutcome::ValidationFailed(e),
31        Err(SubmitError::Handler(e)) => SubmitOutcome::HandlerError(e),
32    }
33}
34
35/// Total guard-acquisition attempts: 1 initial + 7 retries under transient
36/// `RwLock` contention (`None` misreports).
37pub(crate) const BEGIN_ATTEMPT_MAX_TRIES: usize = 8;
38
39/// Begins one submit attempt: the in-flight guard (defensive double-submit
40/// shield complementing the reactively disabled button) followed by the
41/// synchronous `submitted` flip that activates visibility gates BEFORE any
42/// async work (FU-FM-2). Returns `false` when an attempt is already running.
43///
44/// Acquisition is an atomic CAS over `is_submitting`, retried up to
45/// [`BEGIN_ATTEMPT_MAX_TRIES`] under transient `RwLock` contention (`None`
46/// results): the signal's internal write lock is held across read+write, so
47/// among arbitrarily many concurrent callers (the controller is `Sync`)
48/// EXACTLY ONE observes `false` and flips it; every loser observes `true`,
49/// returns `false` IMMEDIATELY — definitive losses never spend retry budget —
50/// with no flag write and no notified reactive write. The `submitted` flip
51/// happens only for the unique winner, AFTER acquisition.
52///
53/// `is_submitting` flips true SYNCHRONOUSLY here — not on the composed
54/// future's first poll — so two same-tick submit events cannot both pass the
55/// guard. The controller's drop guard (engaged when the future first polls)
56/// resets the flag exactly once, on every exit path including cancellation.
57///
58/// # First-poll engagement and scheduler pairing
59///
60/// Because the [`SubmittingGuard`] engages only at the composed future's
61/// FIRST poll (not at composition time), a scheduler that composes the future
62/// but drops it BEFORE the first poll leaves `is_submitting` stuck `true` —
63/// the reset never runs. `spawn_local` is the documented safe pairing: it
64/// always polls the futures it accepts, so the guard engages immediately on
65/// every spawned attempt.
66pub(crate) fn begin_attempt(controller: &FormController) -> bool {
67    let mut acquired = None;
68    for _ in 0..BEGIN_ATTEMPT_MAX_TRIES {
69        match controller.is_submitting().try_maybe_update(|in_flight| {
70            if *in_flight {
71                (false, false)
72            } else {
73                *in_flight = true;
74                (true, true)
75            }
76        }) {
77            Some(result) => {
78                acquired = Some(result);
79                break;
80            }
81            None => std::thread::yield_now(),
82        }
83    }
84    // None = RwLock `WouldBlock` contention misreport for Arc-backed storage
85    // (never disposal); retried up to the bounded BEGIN_ATTEMPT_MAX_TRIES
86    // budget before degrading to not-acquired, so exhaustion still surfaces
87    // as "attempt rejected".
88    if acquired.unwrap_or(false) {
89        controller.submitted().set(true);
90        true
91    } else {
92        false
93    }
94}
95
96/// Drives one attempt's composed future to its caller-facing outcome:
97/// sync validation gate (handler never built on failure), snapshot,
98/// `is_submitting` bracketing across all paths, then [`map_outcome`].
99pub(crate) async fn finish_attempt<T, E, F, Fut>(
100    controller: &FormController,
101    handler: F,
102) -> SubmitOutcome<T, E>
103where
104    T: 'static,
105    E: 'static,
106    F: FnOnce(FormSnapshot) -> Fut,
107    Fut: Future<Output = Result<T, E>>,
108{
109    let result = controller.on_submit(handler).await;
110    map_outcome(result)
111}
112
113/// Encapsulates async form submission over a [`FormController`].
114///
115/// Per attempt: `prevent_default()` first, then the in-flight guard, the
116/// synchronous `submitted` flip, and the deliberately non-`Send` composed
117/// future driven via `spawn_local` (client-local task; NEVER tokio::spawn).
118///
119/// # SSR exclusion (v0)
120///
121/// Markup may render server-side, but submit execution is client-path only:
122/// `spawn_local` requires a local-task executor unavailable on server
123/// threads, and the composed future is intentionally not `Send`, so it can
124/// never be tokio-spawned.
125#[component]
126// reason: typed-builder consumes props by value; component fns are never called directly
127#[allow(
128    clippy::needless_pass_by_value,
129    reason = "leptos typed-builder prop convention"
130)]
131pub fn Form<T, E, F, Fut>(
132    controller: FormController,
133    #[prop(into)] on_outcome: Callback<SubmitOutcome<T, E>>,
134    on_submit: F,
135    #[prop(optional)] submit_label: Option<String>,
136    children: Children,
137) -> impl IntoView
138where
139    T: 'static,
140    E: 'static,
141    F: Fn(FormSnapshot) -> Fut + Clone + 'static,
142    Fut: Future<Output = Result<T, E>> + 'static,
143{
144    let ctrl_for_button = controller.clone();
145    view! {
146        <form on:submit=move |ev| {
147            ev.prevent_default();
148            if !begin_attempt(&controller) {
149                return;
150            }
151            // each attempt passes a fresh clone of the persistent `Fn`
152            // into a fresh composed future
153                let handler = on_submit.clone();
154                let outcome_cb = on_outcome;
155                let ctrl = controller.clone();
156            spawn_local(async move {
157                let outcome = finish_attempt(&ctrl, handler).await;
158                outcome_cb.run(outcome);
159            });
160        }>
161            {children()}
162            {move || {
163                submit_label.clone().map(|label| {
164                    let is_submitting = ctrl_for_button.is_submitting();
165                    view! {
166                        <button type="submit" disabled=move || is_submitting.get()>
167                            {label}
168                        </button>
169                    }
170                })
171            }}
172        </form>
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use formars_signals::{FieldPath, IssueCode};
180    use std::borrow::Cow;
181
182    /// Budget contract (spec Domain 1): 8 = 1 initial attempt + 7 retries,
183    /// spent ONLY on transient `None` (`RwLock` contention misreports).
184    #[test]
185    fn begin_attempt_budget_is_exactly_eight_total_attempts() {
186        assert_eq!(
187            BEGIN_ATTEMPT_MAX_TRIES, 8,
188            "8 = 1 initial attempt + 7 retries under transient contention"
189        );
190    }
191
192    fn sample_error() -> FormaError {
193        FormaError {
194            issues: vec![formars_signals::FormaIssue {
195                path: FieldPath::key("email"),
196                code: IssueCode::Min,
197                message: Cow::Borrowed("too short"),
198                params: Vec::new(),
199            }],
200        }
201    }
202
203    #[test]
204    fn ok_maps_to_success_preserving_payload() {
205        let mapped: SubmitOutcome<u32, String> = map_outcome(Ok(7u32));
206        assert!(
207            matches!(mapped, SubmitOutcome::Success(7)),
208            "Ok must map to Success carrying the payload"
209        );
210    }
211
212    #[test]
213    fn validation_error_maps_to_validation_failed_with_payload() {
214        let mapped: SubmitOutcome<(), FormaError> =
215            map_outcome(Err(SubmitError::Validation(sample_error())));
216        match mapped {
217            SubmitOutcome::ValidationFailed(e) => {
218                assert_eq!(e.issues.len(), 1, "validation payload must be preserved");
219                assert_eq!(e.issues[0].path, FieldPath::key("email"));
220            }
221            other => panic!("expected ValidationFailed, got {other:?}"),
222        }
223    }
224
225    #[test]
226    fn handler_error_maps_to_handler_error_preserving_e() {
227        let mapped: SubmitOutcome<(), FormaError> =
228            map_outcome(Err(SubmitError::Handler(sample_error())));
229        match mapped {
230            SubmitOutcome::HandlerError(e) => {
231                assert_eq!(e.issues.len(), 1, "handler error payload E preserved");
232            }
233            other => panic!("expected HandlerError, got {other:?}"),
234        }
235    }
236}
237
238/// FU-FM-2/3/5 glue-level tests over the composed future, driven by
239/// `block_on` — mirroring exactly what `<Form>`'s submit handler does
240/// (native-only; `spawn_local` itself is exercised on the wasm target).
241#[cfg(test)]
242mod glue {
243    use super::*;
244    use formars_core::prelude::*;
245    use formars_signals::ValidateOn;
246    use futures::executor::block_on;
247    use reactive_graph::traits::Get;
248    use std::cell::RefCell;
249    use std::rc::Rc;
250
251    fn controller_with_invalid_email() -> FormController {
252        let mut c = FormController::new(ValidateOn::Submit);
253        c.register(FieldPath::key("email"), Box::new(string().min(8).email()))
254            .unwrap();
255        c.field(&FieldPath::key("email")).unwrap().set_str("ab");
256        c
257    }
258
259    fn controller_with_valid_email() -> FormController {
260        let mut c = FormController::new(ValidateOn::Submit);
261        c.register(FieldPath::key("email"), Box::new(string().min(8).email()))
262            .unwrap();
263        c.field(&FieldPath::key("email"))
264            .unwrap()
265            .set_str("user@example.com");
266        c
267    }
268
269    /// The exact two-step sequence `<Form>` performs per attempt (extracted
270    /// so native tests drive the real code path).
271    fn form_attempt<T, E, F, Fut>(
272        controller: &FormController,
273        handler: F,
274    ) -> impl Future<Output = SubmitOutcome<T, E>>
275    where
276        T: 'static,
277        E: 'static,
278        F: FnOnce(FormSnapshot) -> Fut,
279        Fut: Future<Output = Result<T, E>>,
280    {
281        let proceed = begin_attempt(controller);
282        let ctrl = controller.clone();
283        async move {
284            if proceed {
285                finish_attempt(&ctrl, handler).await
286            } else {
287                unreachable!("fresh controllers are never mid-submit")
288            }
289        }
290    }
291
292    #[test]
293    fn fm2_submitted_flip_precedes_future() {
294        let controller = controller_with_valid_email();
295        let observed = Rc::new(RefCell::new(None));
296        let obs = observed.clone();
297        let view = controller.clone();
298        block_on(form_attempt(&controller, move |_snap| {
299            *obs.borrow_mut() = Some(view.submitted().get());
300            async { Ok::<(), std::convert::Infallible>(()) }
301        }));
302        assert_eq!(
303            *observed.borrow(),
304            Some(true),
305            "`submitted` must read true at the first handler await point"
306        );
307        assert!(controller.submitted().get());
308    }
309
310    #[test]
311    fn fm3_non_send_handler_accepted() {
312        let controller = controller_with_valid_email();
313        // Rc-backed non-Send state captured by the handler future.
314        let state = Rc::new(RefCell::new(String::from("local")));
315        let captured = state.clone();
316        let outcome = block_on(finish_attempt(&controller, move |_snap| {
317            let captured = captured.clone();
318            async move {
319                captured.borrow_mut().push_str("-done");
320                Ok::<String, std::convert::Infallible>(captured.borrow().clone())
321            }
322        }));
323        match outcome {
324            SubmitOutcome::Success(s) => assert_eq!(s, "local-done"),
325            other => panic!("non-Send handler must complete, got {other:?}"),
326        }
327        assert_eq!(state.borrow().as_str(), "local-done");
328    }
329
330    #[test]
331    fn fm5_invalid_blocks_handler() {
332        let controller = controller_with_invalid_email();
333        let invoked = Rc::new(RefCell::new(false));
334        let flag = invoked.clone();
335        let outcome = block_on(finish_attempt(&controller, move |_snap| {
336            flag.replace(true); // proof-of-invocation marker
337            async { Ok::<(), std::convert::Infallible>(()) }
338        }));
339        assert!(
340            matches!(outcome, SubmitOutcome::ValidationFailed(_)),
341            "validation failure must surface as ValidationFailed"
342        );
343        assert!(
344            !*invoked.borrow(),
345            "handler must never be constructed when validation fails"
346        );
347    }
348
349    #[test]
350    fn fm5_valid_brackets_is_submitting_on_success_and_error() {
351        for expect_ok in [true, false] {
352            let controller = controller_with_valid_email();
353            let during = Rc::new(RefCell::new(None));
354            let d = during.clone();
355            let c2 = controller.clone();
356            let outcome = block_on(finish_attempt(&controller, move |_snap| {
357                let d = d.clone();
358                let c3 = c2.clone();
359                async move {
360                    d.replace(Some(c3.is_submitting().get()));
361                    if expect_ok {
362                        Ok::<(), String>(())
363                    } else {
364                        Err(String::from("boom"))
365                    }
366                }
367            }));
368            assert_eq!(
369                *during.borrow(),
370                Some(true),
371                "is_submitting true while handler pending"
372            );
373            assert!(
374                !controller.is_submitting().get(),
375                "bracket closes after settle"
376            );
377            if expect_ok {
378                assert!(matches!(outcome, SubmitOutcome::Success(())));
379            } else {
380                assert!(
381                    matches!(&outcome, SubmitOutcome::HandlerError(e) if e == "boom"),
382                    "handler error path must also close the bracket"
383                );
384            }
385        }
386    }
387
388    #[test]
389    fn fm5_success_surfaced_once_through_callback() {
390        let controller = controller_with_valid_email();
391        let collected: std::sync::Arc<std::sync::Mutex<Vec<SubmitOutcome<(), String>>>> =
392            std::sync::Arc::default();
393        let sink = collected.clone();
394        let on_outcome = Callback::new(move |o: SubmitOutcome<(), String>| {
395            sink.lock().unwrap().push(o);
396        });
397        // Exactly what <Form>'s spawned task does:
398        let outcome = block_on(finish_attempt(&controller, |_snap| async {
399            Ok::<(), String>(())
400        }));
401        on_outcome.run(outcome);
402        let got = collected.lock().unwrap();
403        assert_eq!(got.len(), 1, "success delivered exactly once");
404        assert!(matches!(got[0], SubmitOutcome::Success(())));
405    }
406
407    #[test]
408    fn guard_rejects_second_synchronous_attempt() {
409        // Two submit events in the same tick: the first flips `is_submitting`
410        // synchronously inside begin_attempt (before any future is polled),
411        // so the second must be rejected.
412        let controller = controller_with_valid_email();
413        assert!(begin_attempt(&controller), "first attempt proceeds");
414        assert!(
415            !begin_attempt(&controller),
416            "second same-tick attempt must be rejected"
417        );
418        assert!(controller.is_submitting().get());
419        // Driving the composed future still resets the flag exactly once.
420        let outcome: SubmitOutcome<(), std::convert::Infallible> =
421            block_on(finish_attempt(&controller, |_snap| async { Ok(()) }));
422        assert!(matches!(outcome, SubmitOutcome::Success(())));
423        assert!(
424            !controller.is_submitting().get(),
425            "drop guard closes the bracket after the attempt settles"
426        );
427    }
428
429    #[test]
430    fn guard_rejects_attempt_while_in_flight() {
431        use reactive_graph::traits::Set;
432        let controller = controller_with_valid_email();
433        // Simulate mid-flight state set from elsewhere; begin_attempt must
434        // observe it and reject the attempt.
435        controller.is_submitting().set(true);
436        assert!(
437            !begin_attempt(&controller),
438            "in-flight guard must reject attempts while submitting"
439        );
440    }
441
442    /// Losing callers leave NO trace: a rejected attempt neither flips
443    /// `submitted` nor disturbs the winner's in-flight acquisition.
444    #[test]
445    fn cas_loser_leaves_no_trace() {
446        use reactive_graph::traits::Set;
447        let controller = controller_with_valid_email();
448        controller.is_submitting().set(true);
449        assert!(!begin_attempt(&controller), "loser must be rejected");
450        assert!(
451            !controller.submitted().get(),
452            "`submitted` byte-identical after the loser: still false"
453        );
454        assert!(
455            controller.is_submitting().get(),
456            "in-flight flag unchanged by the loser"
457        );
458    }
459
460    /// Cross-thread CAS pin (spec Domain 3): T threads × R rounds, every
461    /// round start synchronized on a barrier, ZERO sleeps. Exactly ONE
462    /// caller may win `begin_attempt` per round; the unique winner settles
463    /// via the real `finish_attempt` path so the flag restores through the
464    /// actual drop-guard between rounds. Deterministic assertion under ANY
465    /// interleaving: either the acquisition is atomic or the per-round
466    /// counts expose the TOCTOU.
467    ///
468    /// Two barriers per round keep the accounting airtight: `started`
469    /// releases the round together, and `attempted` guarantees every thread
470    /// has contested THIS round before the winner settles — without it, a
471    /// fast winner's drop-guard reset could leak into a lagging contender's
472    /// same-round attempt (an artifact of the harness, not of the CAS).
473    #[test]
474    fn cas_exactly_one_winner_per_round_across_threads() {
475        use std::sync::{Arc, Barrier, Mutex};
476
477        const THREADS: usize = 8;
478        const ROUNDS: usize = 16;
479
480        let controller = Arc::new(controller_with_valid_email());
481        let winners: Arc<Mutex<Vec<usize>>> = Arc::default();
482        let started = Arc::new(Barrier::new(THREADS));
483        let attempted = Arc::new(Barrier::new(THREADS));
484
485        let workers: Vec<_> = (0..THREADS)
486            .map(|_| {
487                let controller = controller.clone();
488                let winners = winners.clone();
489                let started = started.clone();
490                let attempted = attempted.clone();
491                std::thread::spawn(move || {
492                    for round in 0..ROUNDS {
493                        started.wait();
494                        // Losers perform NOTHING after receiving false.
495                        if begin_attempt(&controller) {
496                            winners.lock().unwrap().push(round);
497                            // THE WINNER settles only after every contender
498                            // has contested this round, through the real
499                            // drop-guard path so the flag restores strictly
500                            // between rounds.
501                            attempted.wait();
502                            let outcome: SubmitOutcome<(), std::convert::Infallible> =
503                                block_on(finish_attempt(&controller, |_snap| async { Ok(()) }));
504                            assert!(
505                                matches!(outcome, SubmitOutcome::Success(())),
506                                "winner's attempt must settle cleanly"
507                            );
508                        } else {
509                            attempted.wait();
510                        }
511                    }
512                })
513            })
514            .collect();
515        for worker in workers {
516            worker.join().expect("no worker panics");
517        }
518
519        let wins = winners.lock().unwrap().clone();
520        let mut per_round = [0usize; ROUNDS];
521        for round in &wins {
522            per_round[*round] += 1;
523        }
524        assert!(
525            per_round.iter().all(|&count| count == 1),
526            "exactly ONE winner per round required; got {per_round:?} \
527             (total {} over {ROUNDS} rounds)",
528            wins.len()
529        );
530        assert_eq!(wins.len(), ROUNDS, "exactly R winners across R rounds");
531        assert!(
532            !controller.is_submitting().get(),
533            "flag fully restored after join"
534        );
535    }
536}