1use 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#[derive(Clone, Debug)]
13pub enum SubmitOutcome<T, E> {
14 Success(T),
16 HandlerError(E),
19 ValidationFailed(FormaError),
23}
24
25pub(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
35pub(crate) const BEGIN_ATTEMPT_MAX_TRIES: usize = 8;
38
39pub(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 if acquired.unwrap_or(false) {
89 controller.submitted().set(true);
90 true
91 } else {
92 false
93 }
94}
95
96pub(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#[component]
126#[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 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 #[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#[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 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 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); 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 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 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 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 controller.is_submitting().set(true);
436 assert!(
437 !begin_attempt(&controller),
438 "in-flight guard must reject attempts while submitting"
439 );
440 }
441
442 #[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 #[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 if begin_attempt(&controller) {
496 winners.lock().unwrap().push(round);
497 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}