formars_signals/controller.rs
1//! The form controller: an insertion-ordered registry of erased field cells.
2
3use std::future::Future;
4use std::sync::{Arc, Mutex, MutexGuard};
5
6use reactive_graph::computed::ArcMemo;
7use reactive_graph::signal::ArcRwSignal;
8use reactive_graph::traits::{Get, Set, Update};
9
10use formars_core::error::{FieldPath, FormaError, FormaIssue};
11use formars_core::schema::DynSchema;
12use formars_core::value::Value;
13
14use crate::field::{FieldCell, FieldHandle, ValidateOn};
15use crate::submit::{FormSnapshot, SubmitError};
16use crate::validation::{display_gate, group_issues, stamp_issues};
17
18/// Error returned by [`FormController::register`].
19#[derive(Clone, Debug, PartialEq)]
20pub enum RegisterError {
21 /// The path is already registered; the existing field was left untouched.
22 Duplicate {
23 /// The offending path.
24 path: FieldPath,
25 },
26}
27
28pub(crate) struct Inner {
29 pub(crate) default_validate_on: ValidateOn,
30 pub(crate) submitted: ArcRwSignal<bool>,
31 pub(crate) is_submitting: ArcRwSignal<bool>,
32 pub(crate) unmatched_server: ArcRwSignal<Vec<FormaIssue>>,
33 /// Bumped on every registration so memos reading the (non-reactive)
34 /// registry mutex re-run when fields are added after their first read.
35 pub(crate) registration_epoch: ArcRwSignal<usize>,
36 pub(crate) fields: Mutex<Vec<(FieldPath, FieldCell, FieldHandle)>>,
37}
38
39struct FieldMemos {
40 errors: ArcMemo<Vec<FormaIssue>>,
41 visible: ArcMemo<Vec<FormaIssue>>,
42}
43
44/// RAII bracket for `is_submitting`: true on creation, false on drop, so a
45/// cancelled (dropped) submit future never leaves the flag stuck true.
46struct SubmittingGuard(ArcRwSignal<bool>);
47
48impl SubmittingGuard {
49 fn engage(flag: ArcRwSignal<bool>) -> Self {
50 flag.set(true);
51 Self(flag)
52 }
53}
54
55impl Drop for SubmittingGuard {
56 fn drop(&mut self) {
57 self.0.set(false);
58 }
59}
60
61struct ResetTargets {
62 value: ArcRwSignal<Value>,
63 initial: Value,
64 touched: ArcRwSignal<bool>,
65 server: ArcRwSignal<Vec<FormaIssue>>,
66 baseline: ArcRwSignal<Value>,
67}
68
69/// Controller-owned registry of form fields.
70///
71/// Owns every value signal and state cell; callers only receive
72/// [`FieldHandle`] accessors. Clones share the same underlying signals and
73/// memos, so there is exactly one source of truth per field value. Memos
74/// created owner-less (headless) are never disposed — acceptable because the
75/// controller lives for the form's lifetime.
76///
77/// v0 fields anchor their state to a `Value` snapshot taken at registration;
78/// that snapshot anchors [`FieldHandle::dirty`], [`FormController::reset`],
79/// and the server-baseline comparison. Default registration snapshots the
80/// empty-string `Value`; [`FormController::register_initial`] and
81/// [`FormController::register_initial_with`] snapshot a caller-supplied
82/// value instead (for prefilled fields). The snapshot is immutable after
83/// registration.
84#[derive(Clone)]
85pub struct FormController {
86 pub(crate) inner: Arc<Inner>,
87 pub(crate) form_errors: ArcMemo<Vec<FormaIssue>>,
88}
89
90impl FormController {
91 /// Creates a controller with the given default validation timing.
92 ///
93 /// # Panics
94 ///
95 /// Only if the registry mutex is poisoned by a panic in another thread
96 /// holding it (never in normal use).
97 #[must_use]
98 pub fn new(default_validate_on: ValidateOn) -> Self {
99 let inner = Arc::new(Inner {
100 default_validate_on,
101 submitted: ArcRwSignal::new(false),
102 is_submitting: ArcRwSignal::new(false),
103 unmatched_server: ArcRwSignal::new(Vec::new()),
104 registration_epoch: ArcRwSignal::new(0),
105 fields: Mutex::new(Vec::new()),
106 });
107 let for_aggregate = inner.clone();
108 let form_errors = ArcMemo::new(move |_| {
109 // Track the epoch so later registrations invalidate the aggregate;
110 // the mutex read below is invisible to the reactive graph.
111 let _epoch = for_aggregate.registration_epoch.get();
112 let visible_per_field: Vec<ArcMemo<Vec<FormaIssue>>> = {
113 let fields = for_aggregate
114 .fields
115 .lock()
116 .expect("formars-signals registry mutex poisoned");
117 fields
118 .iter()
119 .map(|(_, c, _)| c.visible_errors.clone())
120 .collect()
121 };
122 let mut out = Vec::new();
123 for visible in visible_per_field {
124 out.extend(visible.get());
125 }
126 // Bounded read instead of raw `.get()`: same contention
127 // hardening as every other controller-side signal read. This is
128 // safe INSIDE a memo derivation because `try_get` registers the
129 // dependency even when the read misses (reactive_graph tracks
130 // BEFORE attempting the read), so a fallback-extended aggregate
131 // is transient: the writer whose lock caused the miss marks this
132 // memo dirty again when its `.set()` completes, and the next
133 // read observes the real value. Yielding is bounded and cannot
134 // deadlock: signal writers never wait on memo computation.
135 out.extend(get_value_bounded(&for_aggregate.unmatched_server).unwrap_or_default());
136 out
137 });
138 Self { inner, form_errors }
139 }
140
141 /// Registers a field using the controller-default timing mode, rejecting
142 /// duplicate paths (fail-fast at the bug site: a double render or
143 /// copy-paste build surfaces here instead of forking state invisibly).
144 ///
145 /// # Errors
146 ///
147 /// Returns [`RegisterError::Duplicate`] if `path` is already registered.
148 pub fn register(
149 &mut self,
150 path: FieldPath,
151 schema: Box<dyn DynSchema>,
152 ) -> Result<FieldHandle, RegisterError> {
153 self.register_inner(path, schema, None, Value::from(""))
154 }
155
156 /// Registers a field with an explicit timing mode overriding the
157 /// controller default.
158 ///
159 /// # Errors
160 ///
161 /// Returns [`RegisterError::Duplicate`] if `path` is already registered.
162 pub fn register_with(
163 &mut self,
164 path: FieldPath,
165 schema: Box<dyn DynSchema>,
166 validate_on: ValidateOn,
167 ) -> Result<FieldHandle, RegisterError> {
168 self.register_inner(path, schema, Some(validate_on), Value::from(""))
169 }
170
171 /// Registers a prefilled field using the controller-default timing mode,
172 /// with `initial` as the dirty/reset/server-baseline anchor instead of
173 /// the empty-string default. The snapshot is immutable after
174 /// registration — no re-anchoring API exists.
175 ///
176 /// `initial` is NOT validated against the field's schema at registration
177 /// time; if it violates constraints, the error memo reports those issues
178 /// immediately (identical to registering then setting the value).
179 ///
180 /// # Errors
181 ///
182 /// Returns [`RegisterError::Duplicate`] if `path` is already registered;
183 /// the existing field is left untouched.
184 pub fn register_initial(
185 &mut self,
186 path: FieldPath,
187 schema: Box<dyn DynSchema>,
188 initial: Value,
189 ) -> Result<FieldHandle, RegisterError> {
190 self.register_inner(path, schema, None, initial)
191 }
192
193 /// Same as [`FormController::register_initial`] plus an explicit timing
194 /// mode overriding the controller default, symmetric with
195 /// [`FormController::register_with`].
196 ///
197 /// `initial` is NOT validated against the field's schema at registration
198 /// time; if it violates constraints, the error memo reports those issues
199 /// immediately (identical to registering then setting the value).
200 ///
201 /// # Errors
202 ///
203 /// Returns [`RegisterError::Duplicate`] if `path` is already registered;
204 /// the existing field is left untouched.
205 pub fn register_initial_with(
206 &mut self,
207 path: FieldPath,
208 schema: Box<dyn DynSchema>,
209 validate_on: ValidateOn,
210 initial: Value,
211 ) -> Result<FieldHandle, RegisterError> {
212 self.register_inner(path, schema, Some(validate_on), initial)
213 }
214
215 fn register_inner(
216 &self,
217 path: FieldPath,
218 schema: Box<dyn DynSchema>,
219 override_on: Option<ValidateOn>,
220 initial: Value,
221 ) -> Result<FieldHandle, RegisterError> {
222 let value = ArcRwSignal::new(initial.clone());
223 let touched = ArcRwSignal::new(false);
224 let server = ArcRwSignal::new(Vec::<FormaIssue>::new());
225 let server_baseline = ArcRwSignal::new(initial.clone());
226 let schema: Arc<dyn DynSchema> = schema.into();
227 let validate_on = override_on.unwrap_or(self.inner.default_validate_on);
228
229 let dirty_value = value.clone();
230 let dirty_initial = initial.clone();
231 let dirty = ArcMemo::new(move |_| dirty_value.get() != dirty_initial);
232
233 let errors_schema = Arc::clone(&schema);
234 let errors_value = value.clone();
235 let errors_path = path.clone();
236 let errors = ArcMemo::new(move |_| {
237 stamp_issues(
238 errors_schema.validate_value(&errors_value.get()),
239 &errors_path,
240 )
241 });
242
243 let gate = display_gate(&touched, &self.inner.submitted, validate_on);
244
245 let visible_gate = gate.clone();
246 let visible_errors_memo = errors.clone();
247 let visible_value = value.clone();
248 let visible_baseline = server_baseline.clone();
249 let visible_server = server.clone();
250 let visible_errors = ArcMemo::new(move |_| {
251 let mut out = if visible_gate.get() {
252 visible_errors_memo.get()
253 } else {
254 Vec::new()
255 };
256 if visible_value.get() == visible_baseline.get() {
257 out.extend(visible_server.get());
258 }
259 out
260 });
261
262 let handle = FieldHandle {
263 path: path.clone(),
264 value: value.clone(),
265 touched: touched.clone(),
266 dirty,
267 errors,
268 visible_errors: visible_errors.clone(),
269 validate_on,
270 };
271 let cell = FieldCell {
272 initial,
273 value,
274 touched,
275 schema,
276 validate_on,
277 server,
278 server_baseline,
279 visible_errors,
280 };
281
282 let mut fields = self.lock_fields();
283 if fields.iter().any(|(p, _, _)| *p == path) {
284 return Err(RegisterError::Duplicate { path });
285 }
286 fields.push((path, cell, handle.clone()));
287 drop(fields);
288 self.inner.registration_epoch.update(|n| *n += 1);
289 Ok(handle)
290 }
291
292 /// Looks up the handle for a registered path.
293 ///
294 /// The returned handle is a cheap clone sharing the same underlying cells.
295 #[must_use]
296 pub fn field(&self, path: &FieldPath) -> Option<FieldHandle> {
297 let fields = self.lock_fields();
298 fields
299 .iter()
300 .find(|(p, _, _)| p == path)
301 .map(|(_, _, h)| h.clone())
302 }
303
304 /// The resolved validation-timing mode for `path`, or `None` when the
305 /// path is not registered.
306 #[must_use]
307 pub fn effective_validate_on(&self, path: &FieldPath) -> Option<ValidateOn> {
308 let fields = self.lock_fields();
309 fields
310 .iter()
311 .find(|(p, _, _)| p == path)
312 .map(|(_, c, _)| c.validate_on)
313 }
314
315 /// Marks the field touched — the blur seam driving visibility gates.
316 pub fn mark_touched(&self, path: &FieldPath) {
317 let touched = {
318 let fields = self.lock_fields();
319 fields
320 .iter()
321 .find(|(p, _, _)| p == path)
322 .map(|(_, c, _)| c.touched.clone())
323 };
324 if let Some(touched) = touched {
325 touched.set(true);
326 }
327 }
328
329 /// Eagerly evaluates the field's error memos, synchronously — no await,
330 /// no scheduling (FSV-2). Because the memos are lazy, any consumer read
331 /// recomputes stale values on demand anyway; this only warms the memo
332 /// caches so a later `.get()` finds fresh values already computed.
333 pub fn revalidate(&self, path: &FieldPath) {
334 let memos: Option<FieldMemos> = {
335 let fields = self.lock_fields();
336 fields
337 .iter()
338 .find(|(p, _, _)| p == path)
339 .map(|(_, c, h)| FieldMemos {
340 errors: h.errors.clone(),
341 visible: c.visible_errors.clone(),
342 })
343 };
344 if let Some(FieldMemos { errors, visible }) = memos {
345 let _ = errors.get();
346 let _ = visible.get();
347 }
348 }
349
350 /// The form-level submit-attempt flag feeding every display gate.
351 #[must_use]
352 pub fn submitted(&self) -> ArcRwSignal<bool> {
353 self.inner.submitted.clone()
354 }
355
356 /// The in-flight submit flag: true between the snapshot gate and the
357 /// handler future settling, across success and failure alike.
358 #[must_use]
359 pub fn is_submitting(&self) -> ArcRwSignal<bool> {
360 self.inner.is_submitting.clone()
361 }
362
363 /// Reactive aggregate of every field's display-gated issues plus
364 /// form-level (unmatched) server issues.
365 #[must_use]
366 pub fn form_errors(&self) -> ArcMemo<Vec<FormaIssue>> {
367 self.form_errors.clone()
368 }
369
370 /// Merges server-side issues into field state. Issues addressed to
371 /// registered paths REPLACE that field's server cells; unknown or ROOT
372 /// paths land in the form-level unmatched collection. A subsequent edit
373 /// to a field hides its stale server issues until the next apply.
374 ///
375 /// The known-path list and every field's current value are captured under
376 /// ONE registry acquisition, so a concurrent edit can never anchor a
377 /// baseline to a value torn against a stale grouping snapshot; all signal
378 /// writes happen after the lock is released.
379 pub fn apply_server_errors(&self, error: &FormaError) {
380 /// One captured field: path, its server/baseline cells, value snapshot.
381 type Captured = (
382 FieldPath,
383 ArcRwSignal<Vec<FormaIssue>>,
384 ArcRwSignal<Value>,
385 Value,
386 );
387 // ONE acquisition: (path, server cell, baseline cell, value snapshot)
388 // captured atomically. Only clones and one RwSignal primitive read
389 // happen under the lock — no user/schema code, no memos, no awaits.
390 let captured: Vec<Captured> = {
391 let fields = self.lock_fields();
392 fields
393 .iter()
394 .map(|(p, c, _)| {
395 (
396 p.clone(),
397 c.server.clone(),
398 c.server_baseline.clone(),
399 get_value(&c.value),
400 )
401 })
402 .collect()
403 };
404 let known: Vec<FieldPath> = captured.iter().map(|(p, ..)| p.clone()).collect();
405 let (per_field, unmatched) = group_issues(error.issues.clone(), &known);
406 for (path, server, baseline, current) in captured {
407 let matched = per_field.get(&path).cloned().unwrap_or_default();
408 server.set(matched);
409 baseline.set(current);
410 }
411 self.inner.unmatched_server.set(unmatched);
412 }
413
414 /// Validates the whole form synchronously against each field's schema.
415 ///
416 /// Independent of display gates — a hidden (untouched) violation still
417 /// fails submission.
418 ///
419 /// # Errors
420 ///
421 /// Returns every violated field's issues, in declaration order, when any
422 /// registered field fails.
423 pub fn validate(&self) -> Result<(), FormaError> {
424 let checks: Vec<(FieldPath, Arc<dyn DynSchema>, Value)> = {
425 let fields = self.lock_fields();
426 fields
427 .iter()
428 .map(|(p, c, _)| (p.clone(), Arc::clone(&c.schema), get_value(&c.value)))
429 .collect()
430 };
431 let mut issues = Vec::new();
432 for (path, schema, value) in checks {
433 issues.extend(stamp_issues(schema.validate_value(&value), &path));
434 }
435 if issues.is_empty() {
436 Ok(())
437 } else {
438 Err(FormaError { issues })
439 }
440 }
441
442 /// Takes a point-in-time copy of all field values in declaration order.
443 #[must_use]
444 pub fn snapshot(&self) -> FormSnapshot {
445 let entries: Vec<(FieldPath, Value)> = {
446 let fields = self.lock_fields();
447 fields
448 .iter()
449 .map(|(p, c, _)| (p.clone(), get_value(&c.value)))
450 .collect()
451 };
452 FormSnapshot { entries }
453 }
454
455 /// Composes the submit boundary as a plain future: whole-form sync
456 /// validation first (a failure resolves with [`SubmitError::Validation`]
457 /// and never constructs `handler`), then a [`FormSnapshot`] gate,
458 /// `is_submitting` bracketing the attempt via a drop guard — the flag
459 /// resets on success, handler error, validation failure, AND when the
460 /// composed future is dropped (cancelled) mid-flight. No spawner
461 /// required; the caller owns scheduling.
462 ///
463 /// This never flips the [`FormController::submitted`] flag: the caller
464 /// owns that (formars-ui's form glue flips it before awaiting), so headless
465 /// callers who skip the flip keep Submit-gated errors hidden.
466 pub fn on_submit<T, E, F, Fut>(
467 &self,
468 handler: F,
469 ) -> impl Future<Output = Result<T, SubmitError<E>>>
470 where
471 F: FnOnce(FormSnapshot) -> Fut,
472 Fut: Future<Output = Result<T, E>>,
473 {
474 let this = self.clone();
475 async move {
476 // Engaged before validation so a synchronous pre-flip (see the
477 // UI-side double-submit guard) is always reset exactly once, on
478 // every exit path including cancellation.
479 let _guard = SubmittingGuard::engage(this.inner.is_submitting.clone());
480 if let Err(err) = this.validate() {
481 return Err(SubmitError::Validation(err));
482 }
483 let form = this.snapshot();
484 let result = handler(form).await;
485 result.map_err(SubmitError::Handler)
486 }
487 }
488
489 /// Restores every field to its pristine registered state and clears all
490 /// form-level (unmatched) server issues.
491 ///
492 /// The [`FormController::submitted`] flag is deliberately NOT cleared:
493 /// the caller owns it, mirroring [`FormController::on_submit`] (which
494 /// never flips it).
495 pub fn reset(&self) {
496 let restored: Vec<ResetTargets> = {
497 let fields = self.lock_fields();
498 fields
499 .iter()
500 .map(|(_, c, _)| ResetTargets {
501 value: c.value.clone(),
502 initial: c.initial.clone(),
503 touched: c.touched.clone(),
504 server: c.server.clone(),
505 baseline: c.server_baseline.clone(),
506 })
507 .collect()
508 };
509 for ResetTargets {
510 value,
511 initial,
512 touched,
513 server,
514 baseline,
515 } in restored
516 {
517 value.set(initial.clone());
518 touched.set(false);
519 server.set(Vec::new());
520 baseline.set(initial);
521 }
522 // Outside the registry mutex (targets collected and the guard dropped
523 // above — same discipline as `apply_server_errors`); the form_errors
524 // aggregate memo re-reads this signal, so invalidation flows on its own.
525 self.inner.unmatched_server.set(Vec::new());
526 }
527
528 pub(crate) fn lock_fields(&self) -> MutexGuard<'_, Vec<(FieldPath, FieldCell, FieldHandle)>> {
529 self.inner
530 .fields
531 .lock()
532 .expect("formars-signals registry mutex poisoned")
533 }
534}
535
536/// Reads a field's current value without the disposal-misreport panic.
537///
538/// `ArcRwSignal::get` panics when its underlying `try_read` returns `None`,
539/// which happens not only on genuine disposal but also on a transient
540/// `WouldBlock` while another thread holds the write lock mid-`.set()`
541/// (`reactive_graph` misreports contention as disposal — see the crate-level
542/// docs). The registry mutex does NOT exclude external `.set()` callers, so
543/// every controller-side reader (`apply_server_errors`, `validate`,
544/// `snapshot`, and the `form_errors` aggregate memo) goes through
545/// [`get_value_bounded`] instead of panicking: a failed attempt means
546/// "momentarily locked by a writer", never a torn read.
547///
548/// Retries are BOUNDED at [`GET_VALUE_MAX_ATTEMPTS`]. A `None` that persists
549/// past the bound is presumed genuine disposal ("not usable", per the
550/// crate-level guidance) and degrades defensively: the read resolves to
551/// [`Value::Null`] instead of livelocking or panicking. Baselines anchored to
552/// [`Value::Null`] mismatch every real value, so the usual staleness gate
553/// hides server issues that could not be verified against a live read.
554pub(crate) const GET_VALUE_MAX_ATTEMPTS: usize = 1024;
555
556/// Bounded retry read shared by every controller-side signal access:
557/// returns the current value, or `None` after [`GET_VALUE_MAX_ATTEMPTS`]
558/// contended attempts (presumed genuine disposal).
559///
560/// Uses `try_get`, which registers the reactive dependency even when the
561/// read itself fails (`reactive_graph` subscribes BEFORE attempting the
562/// read), so callers inside memo derivations remain wired to the writer
563/// whose contention caused the miss and recompute once it lands. The
564/// yield-spin is bounded and deadlock-free: signal writers never wait on
565/// reader-side computation.
566pub(crate) fn get_value_bounded<T: Clone + 'static>(signal: &ArcRwSignal<T>) -> Option<T> {
567 for _ in 0..GET_VALUE_MAX_ATTEMPTS {
568 if let Some(v) = signal.try_get() {
569 return Some(v);
570 }
571 std::thread::yield_now();
572 }
573 None
574}
575
576pub(crate) fn get_value(signal: &ArcRwSignal<Value>) -> Value {
577 get_value_bounded(signal).unwrap_or(Value::Null)
578}