Skip to main content

renox_core/
state_machine.rs

1//! State machines for models: declare a model's states and transitions
2//! once, and keep the history of every status change.
3//!
4//! A model implements [`StateMachine`] and describes its [`Machine`]: the
5//! states (with a tone and a terminal flag), and the [`Transition`]s between
6//! them with who may run each (a permission, a permission in the record's
7//! scope, or the system), the guards that must hold and the effects that run
8//! with it. The machine is plain data: [`Machine::mermaid`] draws it, and
9//! the engine and `available` read it.
10//!
11//! ```
12//! use renox::prelude::*;
13//! use renox::state_machine::{Machine, StateMachine, Transition};
14//!
15//! #[derive(DbEnum, Clone, Copy, PartialEq, Eq, Debug)]
16//! enum OrderStatus { Draft, Placed, Cancelled }
17//!
18//! #[derive(Model, serde::Serialize, Default, Clone)]
19//! struct Order { id: i64, status: String, lines: i64 }
20//!
21//! impl StateMachine for Order {
22//!     type State = OrderStatus;
23//!     const COLUMN: renox::db::Col<Self, OrderStatus> = renox::db::Col::new("status");
24//!
25//!     fn machine() -> Machine<Self> {
26//!         Machine::new()
27//!             .initial([OrderStatus::Draft])
28//!             .state(OrderStatus::Draft).tone("neutral")
29//!             .state(OrderStatus::Cancelled).tone("danger").terminal()
30//!             .transition(
31//!                 Transition::new("place")
32//!                     .from([OrderStatus::Draft])
33//!                     .to(OrderStatus::Placed)
34//!                     .permission("orders.place")
35//!                     .guard("has_lines", |order: &Order, _ctx| {
36//!                         Box::pin(async move {
37//!                             if order.lines > 0 { Ok(()) } else { Err("The order has no lines.".into()) }
38//!                         })
39//!                     }),
40//!             )
41//!             .transition(
42//!                 Transition::new("cancel")
43//!                     .from([OrderStatus::Draft, OrderStatus::Placed])
44//!                     .to(OrderStatus::Cancelled)
45//!                     .reason_required(),
46//!             )
47//!     }
48//! }
49//!
50//! assert!(Order::machine().mermaid().starts_with("stateDiagram-v2"));
51//! ```
52//!
53//! The storage every machine writes to is the `state_transitions` table (an
54//! every-app framework migration): one [`StateTransition`] row per change,
55//! written with [`TransitionRecord`] and read back with [`history`], oldest
56//! first, for an `<rx-history>` block.
57//!
58//! ```
59//! use renox::state_machine::{TransitionRecord, history};
60//! # async fn demo(db: renox::db::Db) -> renox::Result {
61//! TransitionRecord::new("orders", 42, "placed", "place")
62//!     .from("draft")
63//!     .actor(7)
64//!     .reason("customer paid by phone")
65//!     .record(&db)
66//!     .await?;
67//! let log = history(&db, "orders", 42).await?;
68//! assert_eq!(log[0].to_state, "placed");
69//! # Ok(()) }
70//! ```
71
72use std::collections::BTreeMap;
73use std::fmt;
74use std::future::Future;
75use std::marker::PhantomData;
76use std::sync::{Arc, PoisonError, RwLock};
77
78use futures_util::future::BoxFuture;
79use serde::Serialize;
80use serde_json::Value;
81
82use crate::auth::AuthUser;
83use crate::auth::permissions::Scope;
84use crate::db::{
85    Col, DateTime, Db, DbError, Executor, Json, Migration, Model, Row, Transaction, now, sql,
86};
87use crate::events::Event;
88use crate::{AppState, Result};
89
90pub(crate) const MIGRATION: Migration = crate::db::framework_migration!(
91    "state_machine",
92    "00010101000410_create_state_transitions_table"
93);
94
95/// One row of the `state_transitions` table: a status change of one record.
96#[derive(Debug, Clone, PartialEq, Serialize)]
97#[non_exhaustive]
98pub struct StateTransition {
99    /// The row id.
100    pub id: i64,
101    /// The model's table, e.g. `orders`.
102    pub model: String,
103    /// The record's key as text.
104    pub record_key: String,
105    /// The state it left; `None` for an insert (`insert_in_state`).
106    pub from_state: Option<String>,
107    /// The state it entered.
108    pub to_state: String,
109    /// The transition's name, e.g. `place`.
110    pub transition: String,
111    /// The user who ran it; `None` for a system transition.
112    pub actor_id: Option<i64>,
113    /// The reason given, if any.
114    pub reason: Option<String>,
115    /// Extra data kept with the change (`null` when none).
116    pub metadata: Value,
117    /// When it happened.
118    pub at: DateTime,
119}
120
121impl StateTransition {
122    fn from_row(row: &Row) -> std::result::Result<Self, DbError> {
123        let metadata: Json<Value> = row.try_get("metadata")?;
124        Ok(StateTransition {
125            id: row.try_get("id")?,
126            model: row.try_get("model")?,
127            record_key: row.try_get("record_key")?,
128            from_state: row.try_get("from_state")?,
129            to_state: row.try_get("to_state")?,
130            transition: row.try_get("transition")?,
131            actor_id: row.try_get("actor_id")?,
132            reason: row.try_get("reason")?,
133            metadata: metadata.0,
134            at: row.try_get("at")?,
135        })
136    }
137}
138
139/// A history row to write: build it, then [`record`](TransitionRecord::record)
140/// it on a `&Db` or inside the transition's transaction.
141#[derive(Debug, Clone, PartialEq)]
142#[must_use = "a transition record is only stored when you call `record`"]
143pub struct TransitionRecord {
144    model: String,
145    record_key: String,
146    from_state: Option<String>,
147    to_state: String,
148    transition: String,
149    actor_id: Option<i64>,
150    reason: Option<String>,
151    metadata: Value,
152}
153
154impl TransitionRecord {
155    /// A change of record `key` of `model` (its table) into `to_state`,
156    /// by the transition named `transition`.
157    pub fn new(
158        model: impl Into<String>,
159        key: impl ToString,
160        to_state: impl Into<String>,
161        transition: impl Into<String>,
162    ) -> Self {
163        TransitionRecord {
164            model: model.into(),
165            record_key: key.to_string(),
166            from_state: None,
167            to_state: to_state.into(),
168            transition: transition.into(),
169            actor_id: None,
170            reason: None,
171            metadata: Value::Null,
172        }
173    }
174
175    /// The state the record left (leave it out for an insert).
176    pub fn from(mut self, state: impl Into<String>) -> Self {
177        self.from_state = Some(state.into());
178        self
179    }
180
181    /// The user who ran it (leave it out for a system transition).
182    pub fn actor(mut self, user_id: i64) -> Self {
183        self.actor_id = Some(user_id);
184        self
185    }
186
187    /// Why it was done.
188    pub fn reason(mut self, reason: impl Into<String>) -> Self {
189        self.reason = Some(reason.into());
190        self
191    }
192
193    /// Extra data to keep with the change.
194    pub fn metadata(mut self, metadata: Value) -> Self {
195        self.metadata = metadata;
196        self
197    }
198
199    /// Writes the row and returns it as stored.
200    pub async fn record<'c>(self, db: impl Executor<'c>) -> Result<StateTransition> {
201        let at = now();
202        let id: i64 = sql("INSERT INTO state_transitions \
203             (model, record_key, from_state, to_state, transition, actor_id, reason, metadata, at) \
204             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
205        .bind(self.model.as_str())
206        .bind(self.record_key.as_str())
207        .bind(self.from_state.as_deref())
208        .bind(self.to_state.as_str())
209        .bind(self.transition.as_str())
210        .bind(self.actor_id)
211        .bind(self.reason.as_deref())
212        .bind(Json(self.metadata.clone()))
213        .bind(at)
214        .scalar(db)
215        .await?;
216        Ok(StateTransition {
217            id,
218            model: self.model,
219            record_key: self.record_key,
220            from_state: self.from_state,
221            to_state: self.to_state,
222            transition: self.transition,
223            actor_id: self.actor_id,
224            reason: self.reason,
225            metadata: self.metadata,
226            at,
227        })
228    }
229}
230
231/// Every change of record `key` of `model` (its table), oldest first.
232pub async fn history<'c>(
233    db: impl Executor<'c>,
234    model: &str,
235    key: impl ToString,
236) -> Result<Vec<StateTransition>> {
237    let rows = sql(
238        "SELECT id, model, record_key, from_state, to_state, transition, actor_id, reason, \
239         metadata, at FROM state_transitions WHERE model = ? AND record_key = ? ORDER BY id",
240    )
241    .bind(model)
242    .bind(key.to_string())
243    .fetch_all(db)
244    .await?;
245    rows.iter()
246        .map(StateTransition::from_row)
247        .collect::<std::result::Result<_, _>>()
248        .map_err(Into::into)
249}
250
251/// A model whose status column moves through a [`Machine`].
252///
253/// `State` is usually a `#[derive(DbEnum)]` enum: its text (`Display`) is the
254/// name of a state in the machine, in the history and in diagrams.
255pub trait StateMachine: Model {
256    /// The status type, e.g. an enum deriving `DbEnum`.
257    type State: Copy + PartialEq + fmt::Display + Send + Sync + 'static;
258
259    /// The status column.
260    const COLUMN: Col<Self, Self::State>;
261
262    /// The states and transitions. Built on each call; cheap, so call it
263    /// where you need it or keep the result.
264    fn machine() -> Machine<Self>;
265
266    /// The transitions `user` may run on this record now, for buttons and
267    /// menus: the user's permission (in the record's scope for
268    /// `permission_in`), the record's state and the guards all hold. System
269    /// transitions are left out. Nothing is written: the guards run (so they
270    /// must be side-effect free) and the interceptor is only asked to
271    /// [`preview`], which sets `requires_approval`.
272    fn available<'a>(
273        &'a self,
274        user: &'a AuthUser,
275        db: &'a Db,
276    ) -> impl Future<Output = Result<Vec<Available>>> + Send + 'a
277    where
278        Self: Sized,
279    {
280        available_for(self, user, db)
281    }
282
283    /// Inserts this record in `state` even though the machine's `initial`
284    /// states don't include it (an import, a fixture, a record born
285    /// mid-way), and writes a history row with no `from` state and `reason`.
286    /// Runs in `tx` and doesn't commit.
287    ///
288    /// The record's status must already be `state` (set the field first):
289    /// the argument is the explicit statement of the exception. A plain
290    /// `insert`/`save` of a record in a non-initial state is refused when the
291    /// machine declares `initial`.
292    fn insert_in_state<'a>(
293        &'a mut self,
294        tx: &'a mut Transaction,
295        state: Self::State,
296        reason: &'a str,
297    ) -> impl Future<Output = Result> + Send + 'a
298    where
299        Self: Sized,
300    {
301        insert_in_state_for(self, tx, state, reason)
302    }
303
304    /// Starts running the transition called `name` on this record; chain
305    /// `by` (or `by_system`), optionally `reason`, `input` and `meta`, and end
306    /// with `run` or `run_in`.
307    fn transition(&self, name: &str) -> TransitionBuilder<'_, Self>
308    where
309        Self: Sized,
310    {
311        TransitionBuilder {
312            record: self,
313            name: name.to_owned(),
314            actor: Actor::Unset,
315            reason: None,
316            input: Ok(Value::Null),
317            meta: Value::Null,
318        }
319    }
320}
321
322/// Why a transition did not run.
323#[derive(Debug)]
324#[non_exhaustive]
325pub enum TransitionError {
326    /// Nobody is logged in and the transition is not a system one.
327    Unauthenticated,
328    /// The user may not run this transition (or it is a system transition
329    /// and a user tried).
330    Forbidden,
331    /// The record is not in a state the transition leaves; holds the state
332    /// it is in.
333    NotFrom(String),
334    /// A guard said no; holds its message, safe to show.
335    Guard(String),
336    /// The record changed under the transition (another one ran first).
337    Conflict,
338    /// The machine has no transition of this name.
339    Unknown(String),
340    /// A `reason_required` transition ran without a reason.
341    ReasonRequired,
342    /// Anything else (the database, an effect).
343    Failed(crate::Error),
344}
345
346impl fmt::Display for TransitionError {
347    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348        match self {
349            TransitionError::Unauthenticated => f.write_str("log in to do this"),
350            TransitionError::Forbidden => f.write_str("you may not do this"),
351            TransitionError::NotFrom(state) => {
352                write!(f, "this can't be done from the state `{state}`")
353            }
354            TransitionError::Guard(message) => f.write_str(message),
355            TransitionError::Conflict => {
356                f.write_str("the record was changed by someone else; reload and try again")
357            }
358            TransitionError::Unknown(name) => write!(f, "there is no transition `{name}`"),
359            TransitionError::ReasonRequired => f.write_str("a reason is required"),
360            TransitionError::Failed(error) => write!(f, "the transition failed: {error:?}"),
361        }
362    }
363}
364
365impl std::error::Error for TransitionError {}
366
367impl From<crate::Error> for TransitionError {
368    fn from(error: crate::Error) -> Self {
369        TransitionError::Failed(error)
370    }
371}
372
373impl From<DbError> for TransitionError {
374    fn from(error: DbError) -> Self {
375        TransitionError::Failed(error.into())
376    }
377}
378
379/// What a guard or an effect sees of the run: who, why, and the input and
380/// metadata given with it.
381#[derive(Clone, Default)]
382pub struct TransitionCtx {
383    actor: Option<AuthUser>,
384    reason: Option<String>,
385    input: Value,
386    meta: Value,
387}
388
389impl TransitionCtx {
390    /// A context for `actor` (`None` for a system run), with no reason, no
391    /// input and no metadata.
392    pub fn new(actor: Option<AuthUser>) -> Self {
393        TransitionCtx {
394            actor,
395            ..Default::default()
396        }
397    }
398
399    /// Sets the reason.
400    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
401        self.reason = Some(reason.into());
402        self
403    }
404
405    /// Sets the input guards and effects read with [`TransitionCtx::input`].
406    pub fn with_input(mut self, input: Value) -> Self {
407        self.input = input;
408        self
409    }
410
411    /// Sets the metadata stored with the history row.
412    pub fn with_meta(mut self, meta: Value) -> Self {
413        self.meta = meta;
414        self
415    }
416
417    /// The user running the transition; `None` for a system run.
418    pub fn actor(&self) -> Option<&AuthUser> {
419        self.actor.as_ref()
420    }
421
422    /// The reason given, if any.
423    pub fn reason(&self) -> Option<&str> {
424        self.reason.as_deref()
425    }
426
427    /// The input given with the run, as JSON (`null` when none).
428    pub fn input(&self) -> &Value {
429        &self.input
430    }
431
432    /// The input, read as `T`.
433    pub fn input_as<T: serde::de::DeserializeOwned>(&self) -> std::result::Result<T, String> {
434        serde_json::from_value(self.input.clone()).map_err(|e| e.to_string())
435    }
436
437    /// The metadata stored with the history row (`null` when none).
438    pub fn meta(&self) -> &Value {
439        &self.meta
440    }
441}
442
443type GuardFn<M> = Arc<
444    dyn for<'a> Fn(&'a M, &'a TransitionCtx) -> BoxFuture<'a, std::result::Result<(), String>>
445        + Send
446        + Sync,
447>;
448type EffectFn<M> = Arc<
449    dyn for<'a> Fn(&'a M, &'a TransitionCtx, &'a mut Transaction) -> BoxFuture<'a, Result>
450        + Send
451        + Sync,
452>;
453type ScopeFn<M> = Arc<dyn Fn(&M) -> Scope + Send + Sync>;
454
455/// Who may run a transition.
456enum Access<M> {
457    /// Any logged-in user.
458    Authenticated,
459    /// A user holding the permission.
460    Permission(String),
461    /// A user holding the permission in the scope the function gives.
462    PermissionIn(String, ScopeFn<M>),
463    /// Only the system (`by_system`): scheduled tasks, listeners.
464    System,
465}
466
467/// One state of a [`Machine`]: its name, tone and whether it is terminal.
468#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
469#[non_exhaustive]
470pub struct StateDef {
471    /// The state's text, as stored.
472    pub name: String,
473    /// A tone for badges and steppers (`neutral`, `danger`, ...), if set.
474    pub tone: Option<String>,
475    /// No transition leaves a terminal state.
476    pub terminal: bool,
477}
478
479/// A change between states, built with [`Transition::new`].
480pub struct Transition<M: StateMachine> {
481    name: String,
482    label: Option<String>,
483    tone: Option<String>,
484    from: Vec<String>,
485    to: Option<String>,
486    reason_required: bool,
487    access: Access<M>,
488    guards: Vec<(String, GuardFn<M>)>,
489    effects: Vec<EffectFn<M>>,
490}
491
492impl<M: StateMachine> Transition<M> {
493    /// A transition called `name` (e.g. `place`), open to any logged-in user
494    /// until you restrict it with `permission`, `permission_in` or `system`.
495    pub fn new(name: impl Into<String>) -> Self {
496        Transition {
497            name: name.into(),
498            label: None,
499            tone: None,
500            from: Vec::new(),
501            to: None,
502            reason_required: false,
503            access: Access::Authenticated,
504            guards: Vec::new(),
505            effects: Vec::new(),
506        }
507    }
508
509    /// The states it may start from.
510    pub fn from<S: fmt::Display>(mut self, states: impl IntoIterator<Item = S>) -> Self {
511        self.from = states.into_iter().map(|s| s.to_string()).collect();
512        self
513    }
514
515    /// The state it ends in.
516    pub fn to(mut self, state: impl fmt::Display) -> Self {
517        self.to = Some(state.to_string());
518        self
519    }
520
521    /// The button text (default: the name with spaces, capitalised: `Mark paid`).
522    pub fn label(mut self, label: impl Into<String>) -> Self {
523        self.label = Some(label.into());
524        self
525    }
526
527    /// A tone for its button (`primary`, `danger`, ...).
528    pub fn tone(mut self, tone: impl Into<String>) -> Self {
529        self.tone = Some(tone.into());
530        self
531    }
532
533    /// The run must give a reason (the button asks for one).
534    pub fn reason_required(mut self) -> Self {
535        self.reason_required = true;
536        self
537    }
538
539    /// Only users holding `permission` (the `Permissions` module).
540    pub fn permission(mut self, permission: impl Into<String>) -> Self {
541        self.access = Access::Permission(permission.into());
542        self
543    }
544
545    /// Only users holding `permission` in the scope `scope` gives for the
546    /// record (e.g. its store), or globally.
547    pub fn permission_in(
548        mut self,
549        permission: impl Into<String>,
550        scope: impl Fn(&M) -> Scope + Send + Sync + 'static,
551    ) -> Self {
552        self.access = Access::PermissionIn(permission.into(), Arc::new(scope));
553        self
554    }
555
556    /// Only the system may run it (`by_system`), e.g. a scheduled task.
557    pub fn system(mut self) -> Self {
558        self.access = Access::System;
559        self
560    }
561
562    /// A condition that must hold: the closure returns `Ok(())` or
563    /// `Err(message)`. Guards run in the order added, also when asking which
564    /// actions are available, so they must not write anything. Name the
565    /// record's type on the closure's first parameter
566    /// (`|order: &Order, ctx| Box::pin(async move { .. })`), as the compiler
567    /// can't tell it from the chain.
568    pub fn guard<F>(mut self, name: impl Into<String>, guard: F) -> Self
569    where
570        F: for<'a> Fn(&'a M, &'a TransitionCtx) -> BoxFuture<'a, std::result::Result<(), String>>
571            + Send
572            + Sync
573            + 'static,
574    {
575        self.guards.push((name.into(), Arc::new(guard)));
576        self
577    }
578
579    /// Work that runs with the transition, in its transaction: if it fails,
580    /// the status change and the history row are rolled back. Effects run in
581    /// the order added.
582    pub fn effect<F>(mut self, effect: F) -> Self
583    where
584        F: for<'a> Fn(&'a M, &'a TransitionCtx, &'a mut Transaction) -> BoxFuture<'a, Result>
585            + Send
586            + Sync
587            + 'static,
588    {
589        self.effects.push(Arc::new(effect));
590        self
591    }
592
593    /// The transition's name.
594    pub fn name(&self) -> &str {
595        &self.name
596    }
597
598    /// The button text.
599    pub fn label_text(&self) -> String {
600        self.label.clone().unwrap_or_else(|| humanize(&self.name))
601    }
602
603    /// The button's tone, if set.
604    pub fn tone_name(&self) -> Option<&str> {
605        self.tone.as_deref()
606    }
607
608    /// The states it may start from.
609    pub fn from_states(&self) -> &[String] {
610        &self.from
611    }
612
613    /// The state it ends in.
614    pub fn to_state(&self) -> Option<&str> {
615        self.to.as_deref()
616    }
617
618    /// Whether a reason must be given.
619    pub fn needs_reason(&self) -> bool {
620        self.reason_required
621    }
622
623    /// Whether only the system may run it.
624    pub fn is_system(&self) -> bool {
625        matches!(self.access, Access::System)
626    }
627
628    /// The names of its guards, in order.
629    pub fn guard_names(&self) -> Vec<&str> {
630        self.guards.iter().map(|(n, _)| n.as_str()).collect()
631    }
632
633    /// Checks who is running it: authentication, then permission (in the
634    /// record's scope for `permission_in`). `actor` is `None` for a system
635    /// run, which only `system` transitions accept; a user may not run one.
636    pub fn check_access(
637        &self,
638        record: &M,
639        actor: Option<&AuthUser>,
640    ) -> std::result::Result<(), TransitionError> {
641        let Some(user) = actor else {
642            return if self.is_system() {
643                Ok(())
644            } else {
645                Err(TransitionError::Unauthenticated)
646            };
647        };
648        let allowed = match &self.access {
649            Access::Authenticated => true,
650            Access::Permission(p) => user.has_permission(p),
651            Access::PermissionIn(p, scope) => user.has_permission_in(p, &scope(record)),
652            Access::System => false,
653        };
654        if allowed {
655            Ok(())
656        } else {
657            Err(TransitionError::Forbidden)
658        }
659    }
660
661    /// Checks the record's current state is one the transition leaves.
662    pub fn check_from(
663        &self,
664        current: impl fmt::Display,
665    ) -> std::result::Result<(), TransitionError> {
666        let current = current.to_string();
667        if self.from.contains(&current) {
668            Ok(())
669        } else {
670            Err(TransitionError::NotFrom(current))
671        }
672    }
673
674    /// Runs the guards in order and stops at the first that says no.
675    pub async fn check_guards(
676        &self,
677        record: &M,
678        ctx: &TransitionCtx,
679    ) -> std::result::Result<(), TransitionError> {
680        for (_, guard) in &self.guards {
681            guard(record, ctx).await.map_err(TransitionError::Guard)?;
682        }
683        Ok(())
684    }
685
686    /// Runs the effects in order inside `tx`, stopping at the first failure.
687    pub async fn run_effects(
688        &self,
689        record: &M,
690        ctx: &TransitionCtx,
691        tx: &mut Transaction,
692    ) -> Result {
693        for effect in &self.effects {
694            effect(record, ctx, tx).await?;
695        }
696        Ok(())
697    }
698}
699
700/// `mark_paid` becomes `Mark paid`.
701fn humanize(name: &str) -> String {
702    let text = name.replace(['_', '-'], " ");
703    let mut chars = text.chars();
704    match chars.next() {
705        Some(first) => first.to_uppercase().chain(chars).collect(),
706        None => String::new(),
707    }
708}
709
710/// The states and transitions of a [`StateMachine`] model.
711pub struct Machine<M: StateMachine> {
712    states: Vec<StateDef>,
713    initial: Vec<String>,
714    transitions: Vec<Transition<M>>,
715    /// The state `tone` and `terminal` apply to.
716    last: Option<usize>,
717}
718
719impl<M: StateMachine> Default for Machine<M> {
720    fn default() -> Self {
721        Self::new()
722    }
723}
724
725impl<M: StateMachine> Machine<M> {
726    /// An empty machine.
727    pub fn new() -> Self {
728        Machine {
729            states: Vec::new(),
730            initial: Vec::new(),
731            transitions: Vec::new(),
732            last: None,
733        }
734    }
735
736    fn index_of(&mut self, name: &str) -> usize {
737        if let Some(i) = self.states.iter().position(|s| s.name == name) {
738            return i;
739        }
740        self.states.push(StateDef {
741            name: name.to_owned(),
742            tone: None,
743            terminal: false,
744        });
745        self.states.len() - 1
746    }
747
748    /// Declares a state, to describe with `tone` and `terminal`. States that
749    /// only transitions mention are declared implicitly.
750    pub fn state(mut self, state: impl fmt::Display) -> Self {
751        let i = self.index_of(&state.to_string());
752        self.last = Some(i);
753        self
754    }
755
756    /// Sets the tone (`neutral`, `danger`, ...) of the state just declared.
757    ///
758    /// # Panics
759    ///
760    /// When no `state` came before it.
761    pub fn tone(mut self, tone: impl Into<String>) -> Self {
762        let i = self.last.expect("`tone` follows `state`");
763        self.states[i].tone = Some(tone.into());
764        self
765    }
766
767    /// Marks the state just declared as terminal: no transition may leave it.
768    ///
769    /// # Panics
770    ///
771    /// When no `state` came before it.
772    pub fn terminal(mut self) -> Self {
773        let i = self.last.expect("`terminal` follows `state`");
774        self.states[i].terminal = true;
775        self
776    }
777
778    /// The states a new record may be inserted in. With none declared,
779    /// inserts are unrestricted.
780    pub fn initial<S: fmt::Display>(mut self, states: impl IntoIterator<Item = S>) -> Self {
781        let names: Vec<String> = states.into_iter().map(|s| s.to_string()).collect();
782        for name in &names {
783            self.index_of(name);
784        }
785        self.initial = names;
786        self
787    }
788
789    /// Adds a transition. Its states are declared if they were not.
790    ///
791    /// # Panics
792    ///
793    /// When it has no `to` state, no `from` state, leaves a terminal state,
794    /// or its name is already taken: a machine is code, so these are
795    /// mistakes found the first time it is built.
796    pub fn transition(mut self, transition: Transition<M>) -> Self {
797        let to = transition
798            .to
799            .clone()
800            .unwrap_or_else(|| panic!("transition `{}` has no `to` state", transition.name));
801        assert!(
802            !transition.from.is_empty(),
803            "transition `{}` has no `from` state",
804            transition.name
805        );
806        assert!(
807            self.transitions.iter().all(|t| t.name != transition.name),
808            "transition `{}` is defined twice",
809            transition.name
810        );
811        for name in transition.from.clone().iter().chain([&to]) {
812            self.index_of(name);
813        }
814        for from in &transition.from {
815            let terminal = self.states.iter().any(|s| &s.name == from && s.terminal);
816            assert!(
817                !terminal,
818                "transition `{}` leaves the terminal state `{from}`",
819                transition.name
820            );
821        }
822        self.last = None;
823        self.transitions.push(transition);
824        self
825    }
826
827    /// Every state, in the order declared.
828    pub fn states(&self) -> &[StateDef] {
829        &self.states
830    }
831
832    /// The states inserts are limited to; empty when unrestricted.
833    pub fn initial_states(&self) -> &[String] {
834        &self.initial
835    }
836
837    /// Every transition, in the order added.
838    pub fn transitions(&self) -> &[Transition<M>] {
839        &self.transitions
840    }
841
842    /// The transition called `name`.
843    pub fn find(&self, name: &str) -> std::result::Result<&Transition<M>, TransitionError> {
844        self.transitions
845            .iter()
846            .find(|t| t.name == name)
847            .ok_or_else(|| TransitionError::Unknown(name.to_owned()))
848    }
849
850    /// The transitions that leave `state`, in the order added.
851    pub fn from_state<'a>(
852        &'a self,
853        state: &'a str,
854    ) -> impl Iterator<Item = &'a Transition<M>> + 'a {
855        self.transitions
856            .iter()
857            .filter(move |t| t.from.iter().any(|f| f == state))
858    }
859
860    /// A Mermaid `stateDiagram-v2`: initial states are entered from `[*]`,
861    /// terminal states lead to `[*]`, and each arrow carries the
862    /// transition's name. Paste it in a Markdown page or the Mermaid editor.
863    pub fn mermaid(&self) -> String {
864        let mut out = String::from("stateDiagram-v2\n");
865        for name in &self.initial {
866            out.push_str(&format!("    [*] --> {}\n", mermaid_id(name)));
867        }
868        for t in &self.transitions {
869            let to = t.to.as_deref().unwrap_or_default();
870            for from in &t.from {
871                out.push_str(&format!(
872                    "    {} --> {}: {}\n",
873                    mermaid_id(from),
874                    mermaid_id(to),
875                    t.name
876                ));
877            }
878        }
879        for state in self.states.iter().filter(|s| s.terminal) {
880            out.push_str(&format!("    {} --> [*]\n", mermaid_id(&state.name)));
881        }
882        out
883    }
884}
885
886/// A state name as a Mermaid id (letters, digits and `_`).
887fn mermaid_id(name: &str) -> String {
888    name.chars()
889        .map(|c| if c.is_alphanumeric() { c } else { '_' })
890        .collect()
891}
892
893/// Who runs a transition.
894enum Actor {
895    /// Neither `by` nor `by_system` was called: refused as unauthenticated.
896    Unset,
897    User(Box<AuthUser>),
898    System,
899}
900
901/// A transition being set up, from [`StateMachine::transition`].
902#[must_use = "a transition only runs when you call `run` or `run_in`"]
903pub struct TransitionBuilder<'a, M: StateMachine> {
904    record: &'a M,
905    name: String,
906    actor: Actor,
907    reason: Option<String>,
908    input: std::result::Result<Value, String>,
909    meta: Value,
910}
911
912impl<M: StateMachine> TransitionBuilder<'_, M> {
913    /// The user running it.
914    pub fn by(mut self, user: &AuthUser) -> Self {
915        self.actor = Actor::User(Box::new(user.clone()));
916        self
917    }
918
919    /// Runs it as the system (a scheduled task, a listener): no user, no
920    /// actor in the history. Only `system` transitions accept this.
921    pub fn by_system(mut self) -> Self {
922        self.actor = Actor::System;
923        self
924    }
925
926    /// Why it is done (stored in the history).
927    pub fn reason(mut self, reason: impl Into<String>) -> Self {
928        self.reason = Some(reason.into());
929        self
930    }
931
932    /// Data for guards and effects, read with [`TransitionCtx::input`]. One
933    /// that can't be turned into JSON fails the run.
934    pub fn input<T: Serialize>(mut self, input: &T) -> Self {
935        self.input = serde_json::to_value(input).map_err(|e| e.to_string());
936        self
937    }
938
939    /// Extra data stored in the history row's `metadata` and carried on
940    /// [`Transitioned`].
941    pub fn meta(mut self, meta: Value) -> Self {
942        self.meta = meta;
943        self
944    }
945
946    /// Runs it in its own transaction, commits, then emits [`Transitioned`]
947    /// to the app's listeners. If a listener fails the status has changed
948    /// already: the error is returned but nothing is rolled back.
949    pub async fn run(self, state: &AppState) -> std::result::Result<Outcome<M>, TransitionError> {
950        let mut tx = state.db.begin().await?;
951        let outcome = self.run_in(&mut tx).await?;
952        tx.commit().await?;
953        if let Outcome::Done(done) = &outcome {
954            state.emit(done.clone()).await?;
955        }
956        Ok(outcome)
957    }
958
959    /// Runs it inside `tx` and does not commit. Emit the returned
960    /// [`Outcome`] with [`Outcome::emit`] once the transaction has committed.
961    ///
962    /// Checks, in order: who runs it (authentication, permission), the
963    /// record's state, the guards, the reason; then moves the status with
964    /// `UPDATE .. WHERE status = <the record's loaded status>` (no row
965    /// updated means someone else moved it first: `Conflict`), writes the
966    /// history row and runs the effects.
967    ///
968    /// When an interceptor is registered ([`set_interceptor`]) it runs after
969    /// the guards and the reason check. If it defers, nothing moves and no
970    /// effect runs: its own writes in `tx` stay, and the result is
971    /// [`Outcome::Pending`].
972    pub async fn run_in(
973        self,
974        tx: &mut Transaction,
975    ) -> std::result::Result<Outcome<M>, TransitionError> {
976        let machine = M::machine();
977        let transition = machine.find(&self.name)?;
978        let record = self.record;
979        let actor = match &self.actor {
980            Actor::Unset => return Err(TransitionError::Unauthenticated),
981            Actor::User(user) => Some(user.as_ref()),
982            Actor::System => None,
983        };
984        transition.check_access(record, actor)?;
985        let current = current_state(record)?;
986        transition.check_from(&current)?;
987        let input = self.input.map_err(|e| {
988            TransitionError::Failed(crate::Error::Internal(anyhow::anyhow!(
989                "the transition's input is not JSON: {e}"
990            )))
991        })?;
992        let mut ctx = TransitionCtx::new(actor.cloned())
993            .with_input(input)
994            .with_meta(self.meta.clone());
995        if let Some(reason) = &self.reason {
996            ctx = ctx.with_reason(reason.clone());
997        }
998        transition.check_guards(record, &ctx).await?;
999        if transition.needs_reason() && self.reason.as_deref().is_none_or(|r| r.trim().is_empty()) {
1000            return Err(TransitionError::ReasonRequired);
1001        }
1002        let to = transition
1003            .to_state()
1004            .expect("a built machine has a `to` state")
1005            .to_owned();
1006
1007        if let Some(interceptor) = interceptor() {
1008            let request = TransitionRequest {
1009                model: M::TABLE,
1010                key: record.id().to_string(),
1011                transition: transition.name().to_owned(),
1012                from: current.clone(),
1013                to: to.clone(),
1014                actor: actor.cloned(),
1015                reason: self.reason.clone(),
1016                input: ctx.input().clone(),
1017                meta: self.meta.clone(),
1018            };
1019            if let Decision::Defer(data) = interceptor.intercept(&request, &mut *tx).await? {
1020                return Ok(Outcome::Pending(Pending {
1021                    key: record.id(),
1022                    from: current,
1023                    to,
1024                    transition: transition.name().to_owned(),
1025                    actor_id: actor.map(|u| u.id),
1026                    reason: self.reason,
1027                    meta: self.meta,
1028                    data,
1029                }));
1030            }
1031        }
1032
1033        let column = M::COLUMN.name();
1034        let moved = sql(format!(
1035            "UPDATE {} SET {column} = ? WHERE id = ? AND {column} = ?",
1036            M::TABLE
1037        ))
1038        .bind(to.as_str())
1039        .bind(record.id())
1040        .bind(current.as_str())
1041        .execute(&mut *tx)
1042        .await?;
1043        if moved == 0 {
1044            return Err(TransitionError::Conflict);
1045        }
1046
1047        let mut row = TransitionRecord::new(M::TABLE, record.id(), to.as_str(), transition.name())
1048            .from(current.as_str())
1049            .metadata(self.meta.clone());
1050        if let Some(user) = actor {
1051            row = row.actor(user.id);
1052        }
1053        if let Some(reason) = &self.reason {
1054            row = row.reason(reason.clone());
1055        }
1056        row.record(&mut *tx).await?;
1057        transition.run_effects(record, &ctx, tx).await?;
1058
1059        Ok(Outcome::Done(Transitioned {
1060            key: record.id(),
1061            from: current,
1062            to,
1063            transition: transition.name().to_owned(),
1064            actor_id: actor.map(|u| u.id),
1065            reason: self.reason,
1066            meta: self.meta,
1067            _model: PhantomData,
1068        }))
1069    }
1070}
1071
1072tokio::task_local! {
1073    /// Set while `insert_in_state` inserts: the `initial` rule is skipped.
1074    static INSERT_ANY_STATE: ();
1075}
1076
1077/// The insert rule of a `#[model(state_machine)]` model, called by the
1078/// derive's `check_insert`: when the machine declares `initial` states, a new
1079/// record must be in one of them.
1080#[doc(hidden)]
1081pub fn check_insert<M: StateMachine>(record: &M) -> Result {
1082    if INSERT_ANY_STATE.try_with(|_| ()).is_ok() {
1083        return Ok(());
1084    }
1085    let machine = M::machine();
1086    let initial = machine.initial_states();
1087    if initial.is_empty() {
1088        return Ok(());
1089    }
1090    let current = current_state(record).map_err(TransitionError::into_error)?;
1091    if initial.contains(&current) {
1092        return Ok(());
1093    }
1094    Err(crate::Error::Status(
1095        axum::http::StatusCode::UNPROCESSABLE_ENTITY,
1096        format!(
1097            "a new {} can't start in the state `{current}` (it starts in {}); \
1098             use `insert_in_state` for an exception",
1099            M::TABLE,
1100            initial
1101                .iter()
1102                .map(|s| format!("`{s}`"))
1103                .collect::<Vec<_>>()
1104                .join(" or "),
1105        ),
1106    ))
1107}
1108
1109async fn insert_in_state_for<M: StateMachine>(
1110    record: &mut M,
1111    tx: &mut Transaction,
1112    state: M::State,
1113    reason: &str,
1114) -> Result {
1115    let current = current_state(record).map_err(TransitionError::into_error)?;
1116    let wanted = state.to_string();
1117    if current != wanted {
1118        return Err(anyhow::anyhow!(
1119            "insert_in_state: the record's status is `{current}`, not `{wanted}`; set it first"
1120        )
1121        .into());
1122    }
1123    INSERT_ANY_STATE.scope((), record.insert(&mut *tx)).await?;
1124    TransitionRecord::new(M::TABLE, record.id(), wanted, "insert")
1125        .reason(reason)
1126        .record(&mut *tx)
1127        .await?;
1128    Ok(())
1129}
1130
1131/// The record's loaded status, as the text the machine uses.
1132fn current_state<M: StateMachine>(record: &M) -> std::result::Result<String, TransitionError> {
1133    let column = M::COLUMN.name();
1134    let at = M::COLUMNS
1135        .iter()
1136        .filter(|c| **c != "id")
1137        .position(|c| *c == column);
1138    match at.and_then(|i| record.values().into_iter().nth(i)) {
1139        Some(crate::db::DbValue::Text(state)) => Ok(state),
1140        _ => Err(TransitionError::Failed(crate::Error::Internal(
1141            anyhow::anyhow!("the status column `{column}` is not a text column of the model"),
1142        ))),
1143    }
1144}
1145
1146/// A transition that happened. Listen for it with `App::listen`; it is
1147/// emitted by `run` after the commit, or by you with [`Transitioned::emit`]
1148/// after `run_in`'s transaction commits (it is not emitted on a rollback).
1149#[must_use = "emit it after the transaction commits"]
1150pub struct Transitioned<M: StateMachine> {
1151    /// The record's key.
1152    pub key: M::Key,
1153    /// The state it left.
1154    pub from: String,
1155    /// The state it entered.
1156    pub to: String,
1157    /// The transition's name.
1158    pub transition: String,
1159    /// The user who ran it; `None` for a system run.
1160    pub actor_id: Option<i64>,
1161    /// The reason given, if any.
1162    pub reason: Option<String>,
1163    /// The metadata stored with the history row (`null` when none).
1164    pub meta: Value,
1165    _model: PhantomData<fn() -> M>,
1166}
1167
1168impl<M: StateMachine> Clone for Transitioned<M> {
1169    fn clone(&self) -> Self {
1170        Transitioned {
1171            key: self.key.clone(),
1172            from: self.from.clone(),
1173            to: self.to.clone(),
1174            transition: self.transition.clone(),
1175            actor_id: self.actor_id,
1176            reason: self.reason.clone(),
1177            meta: self.meta.clone(),
1178            _model: PhantomData,
1179        }
1180    }
1181}
1182
1183impl<M: StateMachine> fmt::Debug for Transitioned<M> {
1184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1185        f.debug_struct("Transitioned")
1186            .field("model", &M::TABLE)
1187            .field("key", &self.key)
1188            .field("from", &self.from)
1189            .field("to", &self.to)
1190            .field("transition", &self.transition)
1191            .finish()
1192    }
1193}
1194
1195impl<M: StateMachine> Event for Transitioned<M> {}
1196
1197impl<M: StateMachine> Transitioned<M> {
1198    /// Emits it to the app's listeners (after the commit).
1199    pub async fn emit(self, state: &AppState) -> Result {
1200        state.emit(self).await
1201    }
1202}
1203
1204/// What a transition run came to: it moved, or an interceptor deferred it.
1205#[must_use = "emit a `Done` outcome after the transaction commits"]
1206pub enum Outcome<M: StateMachine> {
1207    /// The status moved; the history row and effects are in the transaction.
1208    Done(Transitioned<M>),
1209    /// An interceptor deferred it: the status did not move.
1210    Pending(Pending<M>),
1211}
1212
1213impl<M: StateMachine> Clone for Outcome<M> {
1214    fn clone(&self) -> Self {
1215        match self {
1216            Outcome::Done(done) => Outcome::Done(done.clone()),
1217            Outcome::Pending(pending) => Outcome::Pending(pending.clone()),
1218        }
1219    }
1220}
1221
1222impl<M: StateMachine> Outcome<M> {
1223    /// The [`Transitioned`] if the status moved.
1224    pub fn into_done(self) -> Option<Transitioned<M>> {
1225        match self {
1226            Outcome::Done(done) => Some(done),
1227            Outcome::Pending(_) => None,
1228        }
1229    }
1230
1231    /// Whether an interceptor deferred the run.
1232    pub fn is_pending(&self) -> bool {
1233        matches!(self, Outcome::Pending(_))
1234    }
1235
1236    /// Emits [`Transitioned`] to the app's listeners (after the commit) if
1237    /// the status moved; does nothing for a pending run.
1238    pub async fn emit(self, state: &AppState) -> Result {
1239        match self {
1240            Outcome::Done(done) => done.emit(state).await,
1241            Outcome::Pending(_) => Ok(()),
1242        }
1243    }
1244}
1245
1246/// A transition an interceptor deferred (for example until someone approves
1247/// it). The status has not moved.
1248#[non_exhaustive]
1249pub struct Pending<M: StateMachine> {
1250    /// The record's key.
1251    pub key: M::Key,
1252    /// The state it is still in.
1253    pub from: String,
1254    /// The state the transition would have entered.
1255    pub to: String,
1256    /// The transition's name.
1257    pub transition: String,
1258    /// The user who asked for it; `None` for a system run.
1259    pub actor_id: Option<i64>,
1260    /// The reason given, if any.
1261    pub reason: Option<String>,
1262    /// The metadata given with the run (`null` when none).
1263    pub meta: Value,
1264    /// What the interceptor returned with [`Decision::Defer`], e.g. the id of
1265    /// the request it stored.
1266    pub data: Value,
1267}
1268
1269impl<M: StateMachine> Clone for Pending<M> {
1270    fn clone(&self) -> Self {
1271        Pending {
1272            key: self.key.clone(),
1273            from: self.from.clone(),
1274            to: self.to.clone(),
1275            transition: self.transition.clone(),
1276            actor_id: self.actor_id,
1277            reason: self.reason.clone(),
1278            meta: self.meta.clone(),
1279            data: self.data.clone(),
1280        }
1281    }
1282}
1283
1284/// A transition about to run, as an interceptor sees it. It is the same for
1285/// every machine, so the model is its table name and the key is text.
1286#[derive(Clone)]
1287#[non_exhaustive]
1288pub struct TransitionRequest {
1289    /// The model's table.
1290    pub model: &'static str,
1291    /// The record's key, as text.
1292    pub key: String,
1293    /// The transition's name.
1294    pub transition: String,
1295    /// The state the record is in.
1296    pub from: String,
1297    /// The state the transition leads to.
1298    pub to: String,
1299    /// The user running it; `None` for a system run.
1300    pub actor: Option<AuthUser>,
1301    /// The reason given, if any.
1302    pub reason: Option<String>,
1303    /// The input given with the run (`null` when none).
1304    pub input: Value,
1305    /// The metadata given with the run (`null` when none).
1306    pub meta: Value,
1307}
1308
1309impl TransitionRequest {
1310    /// A request for `transition` on record `key` of `model`, moving `from`
1311    /// one state `to` another, with no actor, reason, input or metadata. For
1312    /// calling [`preview`] by hand.
1313    pub fn new(
1314        model: &'static str,
1315        key: impl ToString,
1316        transition: impl Into<String>,
1317        from: impl Into<String>,
1318        to: impl Into<String>,
1319    ) -> Self {
1320        TransitionRequest {
1321            model,
1322            key: key.to_string(),
1323            transition: transition.into(),
1324            from: from.into(),
1325            to: to.into(),
1326            actor: None,
1327            reason: None,
1328            input: Value::Null,
1329            meta: Value::Null,
1330        }
1331    }
1332
1333    /// Sets the input.
1334    pub fn with_input(mut self, input: Value) -> Self {
1335        self.input = input;
1336        self
1337    }
1338}
1339
1340/// What an interceptor decides for a run.
1341#[derive(Debug, Clone, PartialEq)]
1342pub enum Decision {
1343    /// Carry on: move the status and run the effects.
1344    Proceed,
1345    /// Do not move; the run ends as [`Outcome::Pending`] carrying this data.
1346    Defer(Value),
1347}
1348
1349/// What an interceptor says a run would do, without doing it (see
1350/// [`preview`]).
1351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1352pub enum Preview {
1353    /// It would go through.
1354    Proceed,
1355    /// It would be deferred: the action needs approval.
1356    RequiresApproval,
1357    /// A deferred run for this record and transition is already waiting.
1358    Pending,
1359}
1360
1361/// Hooks every transition of every machine, for things a guard can't do
1362/// because it may only say no, such as approvals.
1363///
1364/// Register one with [`set_interceptor`]. It runs after permission, `from`
1365/// and the guards, in the transition's transaction.
1366pub trait TransitionInterceptor: Send + Sync + 'static {
1367    /// Decides a run. Writes made through `tx` are kept whichever way it
1368    /// decides (and roll back with the transaction if the run later fails).
1369    fn intercept<'a>(
1370        &'a self,
1371        request: &'a TransitionRequest,
1372        tx: &'a mut Transaction,
1373    ) -> BoxFuture<'a, Result<Decision>>;
1374
1375    /// What [`TransitionInterceptor::intercept`] would decide, with no side
1376    /// effects: `available` calls it to mark actions. The default is
1377    /// [`Preview::Proceed`].
1378    fn preview<'a>(
1379        &'a self,
1380        request: &'a TransitionRequest,
1381        db: &'a Db,
1382    ) -> BoxFuture<'a, Result<Preview>> {
1383        let _ = (request, db);
1384        Box::pin(async { Ok(Preview::Proceed) })
1385    }
1386}
1387
1388static INTERCEPTOR: RwLock<Option<Arc<dyn TransitionInterceptor>>> = RwLock::new(None);
1389
1390/// Registers the interceptor for all machines, replacing any earlier one.
1391/// Call it once at startup.
1392pub fn set_interceptor(interceptor: impl TransitionInterceptor) {
1393    *INTERCEPTOR.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(interceptor));
1394}
1395
1396/// Removes the registered interceptor.
1397pub fn clear_interceptor() {
1398    *INTERCEPTOR.write().unwrap_or_else(PoisonError::into_inner) = None;
1399}
1400
1401fn interceptor() -> Option<Arc<dyn TransitionInterceptor>> {
1402    INTERCEPTOR
1403        .read()
1404        .unwrap_or_else(PoisonError::into_inner)
1405        .clone()
1406}
1407
1408/// Asks the registered interceptor what `request` would do, with no side
1409/// effects; [`Preview::Proceed`] when none is registered.
1410pub async fn preview(request: &TransitionRequest, db: &Db) -> Result<Preview> {
1411    match interceptor() {
1412        Some(interceptor) => interceptor.preview(request, db).await,
1413        None => Ok(Preview::Proceed),
1414    }
1415}
1416
1417/// A transition the user may run now (see [`StateMachine::available`]).
1418#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1419#[non_exhaustive]
1420pub struct Available {
1421    /// The transition's name, as `transition(name)` takes it.
1422    pub name: String,
1423    /// The text for its button.
1424    pub label: String,
1425    /// A tone for the button (`danger`, ...), if set.
1426    pub tone: Option<String>,
1427    /// The run must come with a reason; ask for one first.
1428    pub needs_reason: bool,
1429    /// The interceptor would defer it for approval (or a deferred run is
1430    /// already waiting).
1431    pub requires_approval: bool,
1432}
1433
1434async fn available_for<M: StateMachine>(
1435    record: &M,
1436    user: &AuthUser,
1437    db: &Db,
1438) -> Result<Vec<Available>> {
1439    let machine = M::machine();
1440    let current = current_state(record).map_err(TransitionError::into_error)?;
1441    let ctx = TransitionCtx::new(Some(user.clone()));
1442    let mut out = Vec::new();
1443    for transition in machine.from_state(&current) {
1444        if transition.is_system()
1445            || transition.check_access(record, Some(user)).is_err()
1446            || transition.check_guards(record, &ctx).await.is_err()
1447        {
1448            continue;
1449        }
1450        let to = transition.to_state().unwrap_or_default().to_owned();
1451        let mut request = TransitionRequest::new(
1452            M::TABLE,
1453            record.id(),
1454            transition.name(),
1455            current.as_str(),
1456            to,
1457        );
1458        request.actor = Some(user.clone());
1459        let requires_approval = preview(&request, db).await? != Preview::Proceed;
1460        out.push(Available {
1461            name: transition.name().to_owned(),
1462            label: transition.label_text(),
1463            tone: transition.tone_name().map(str::to_owned),
1464            needs_reason: transition.needs_reason(),
1465            requires_approval,
1466        });
1467    }
1468    Ok(out)
1469}
1470
1471impl TransitionError {
1472    /// The [`crate::Error`] it answers as: 401 for `Unauthenticated`, 403
1473    /// for `Forbidden`, 404 for `Unknown`, 422 (with the message) for
1474    /// `NotFrom`, `Guard`, `Conflict` and `ReasonRequired`; a `Failed` error
1475    /// is passed through. (No `From`, which the blanket `From<E: Into<anyhow::Error>>`
1476    /// impl of `Error` rules out.)
1477    pub fn into_error(self) -> crate::Error {
1478        match self {
1479            TransitionError::Unauthenticated => crate::Error::Unauthorized,
1480            TransitionError::Forbidden => crate::Error::Forbidden,
1481            TransitionError::Unknown(_) => crate::Error::NotFound,
1482            TransitionError::Failed(error) => error,
1483            other => crate::Error::Status(
1484                axum::http::StatusCode::UNPROCESSABLE_ENTITY,
1485                other.to_string(),
1486            ),
1487        }
1488    }
1489}
1490
1491impl axum::response::IntoResponse for TransitionError {
1492    /// Answers as [`TransitionError::into_error`], so a handler can return
1493    /// `Result<_, TransitionError>`.
1494    fn into_response(self) -> axum::response::Response {
1495        axum::response::IntoResponse::into_response(self.into_error())
1496    }
1497}
1498
1499/// One transition of a registered machine, as plain data.
1500#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1501#[non_exhaustive]
1502pub struct TransitionInfo {
1503    /// The transition's name.
1504    pub name: String,
1505    /// The text for its button.
1506    pub label: String,
1507    /// Its tone, if set.
1508    pub tone: Option<String>,
1509    /// The states it leaves.
1510    pub from: Vec<String>,
1511    /// The state it leads to.
1512    pub to: String,
1513    /// It needs a reason.
1514    pub needs_reason: bool,
1515    /// Only the system may run it.
1516    pub system: bool,
1517    /// The names of its guards, in order.
1518    pub guards: Vec<String>,
1519}
1520
1521/// A registered machine without its model type, for tools that look it up by
1522/// name (`rnx state:diagram`, the admin).
1523#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1524#[non_exhaustive]
1525pub struct MachineInfo {
1526    /// The model's type name, e.g. `Order`.
1527    pub model: String,
1528    /// The model's table.
1529    pub table: String,
1530    /// The states.
1531    pub states: Vec<StateDef>,
1532    /// The states a new record may start in (empty when unrestricted).
1533    pub initial: Vec<String>,
1534    /// The transitions.
1535    pub transitions: Vec<TransitionInfo>,
1536    /// The Mermaid diagram ([`Machine::mermaid`]).
1537    pub mermaid: String,
1538}
1539
1540static REGISTRY: RwLock<BTreeMap<String, MachineInfo>> = RwLock::new(BTreeMap::new());
1541
1542/// Makes `M`'s machine findable by name with [`machine_info`]. Call it at
1543/// startup for each machine; registering again replaces the entry.
1544pub fn register<M: StateMachine>() {
1545    let info = info_of::<M>();
1546    REGISTRY
1547        .write()
1548        .unwrap_or_else(PoisonError::into_inner)
1549        .insert(info.model.clone(), info);
1550}
1551
1552/// `M`'s machine as plain data, without registering it.
1553pub fn info_of<M: StateMachine>() -> MachineInfo {
1554    let machine = M::machine();
1555    let model = std::any::type_name::<M>()
1556        .rsplit("::")
1557        .next()
1558        .unwrap_or_default()
1559        .to_owned();
1560    MachineInfo {
1561        model,
1562        table: M::TABLE.to_owned(),
1563        states: machine.states().to_vec(),
1564        initial: machine.initial_states().to_vec(),
1565        transitions: machine
1566            .transitions()
1567            .iter()
1568            .map(|t| TransitionInfo {
1569                name: t.name().to_owned(),
1570                label: t.label_text(),
1571                tone: t.tone_name().map(str::to_owned),
1572                from: t.from_states().to_vec(),
1573                to: t.to_state().unwrap_or_default().to_owned(),
1574                needs_reason: t.needs_reason(),
1575                system: t.is_system(),
1576                guards: t.guard_names().into_iter().map(str::to_owned).collect(),
1577            })
1578            .collect(),
1579        mermaid: machine.mermaid(),
1580    }
1581}
1582
1583/// The registered machine whose model is called `name` (`Order`; the table
1584/// name `orders` works too, ignoring case), if any.
1585pub fn machine_info(name: &str) -> Option<MachineInfo> {
1586    let registry = REGISTRY.read().unwrap_or_else(PoisonError::into_inner);
1587    registry
1588        .values()
1589        .find(|m| m.model.eq_ignore_ascii_case(name) || m.table.eq_ignore_ascii_case(name))
1590        .cloned()
1591}
1592
1593/// The model names of all registered machines, sorted.
1594pub fn machine_names() -> Vec<String> {
1595    REGISTRY
1596        .read()
1597        .unwrap_or_else(PoisonError::into_inner)
1598        .keys()
1599        .cloned()
1600        .collect()
1601}
1602
1603/// The routes `<rx-transition-actions>` posts to: `POST
1604/// /{id}/transitions/{name}` runs the transition `name` on record `id` of
1605/// `M` as the logged-in user, with the form's optional `reason`, then goes
1606/// back to the page the form was on. Mount it under the model's path:
1607///
1608/// ```
1609/// use renox::prelude::*;
1610/// use renox::state_machine::{self, StateMachine};
1611///
1612/// fn orders<M: StateMachine + Send + Sync + 'static>() -> Routes {
1613///     // POST /orders/{id}/transitions/{name}
1614///     Routes::new().group("/orders", "orders.", state_machine::routes::<M>())
1615/// }
1616/// ```
1617///
1618/// A refusal answers like [`TransitionError::into_error`]: 401 when nobody is
1619/// logged in, 403 when the user may not run it (a system transition can't
1620/// be run from here), 404 for an unknown record or transition, 422 for a
1621/// state or guard that says no.
1622pub fn routes<M: StateMachine + Send + Sync + 'static>() -> crate::routing::Routes {
1623    crate::routing::Routes::new().post("/{id}/transitions/{name}", run_transition::<M>)
1624}
1625
1626#[derive(serde::Deserialize)]
1627struct ReasonForm {
1628    reason: Option<String>,
1629}
1630
1631async fn run_transition<M: StateMachine + Send + Sync + 'static>(
1632    axum::extract::State(state): axum::extract::State<AppState>,
1633    user: AuthUser,
1634    axum::extract::Path((id, name)): axum::extract::Path<(String, String)>,
1635    back: crate::Back,
1636    axum::extract::Form(form): axum::extract::Form<ReasonForm>,
1637) -> Result<crate::Back> {
1638    let key = id.parse::<M::Key>().map_err(|_| crate::Error::NotFound)?;
1639    let record = M::find(&state.db, key)
1640        .await?
1641        .ok_or(crate::Error::NotFound)?;
1642    let mut run = record.transition(&name).by(&user);
1643    let reason = form.reason.unwrap_or_default();
1644    let reason = reason.trim();
1645    if !reason.is_empty() {
1646        run = run.reason(reason);
1647    }
1648    // `run` emitted `Transitioned`; a deferred run (`Pending`) has nothing
1649    // more to do here, the page shows the state it is still in.
1650    let _outcome = run.run(&state).await.map_err(TransitionError::into_error)?;
1651    Ok(back)
1652}
1653
1654/// A record's history rows ([`history`]) as the items `<rx-history>` shows
1655/// (`time`, `title`, `body`, `kind`): the title is the transition and the
1656/// states it moved between, the body the reason, and the kind follows the
1657/// tone of the state entered (`danger` is `error`; `success` and `warning`
1658/// stay; anything else is `info`).
1659///
1660/// ```
1661/// # async fn demo(db: renox::db::Db) -> renox::Result {
1662/// let log = renox::state_machine::history(&db, "orders", 42).await?;
1663/// let items = renox::state_machine::timeline(&log, None);
1664/// // <rx-history :items="items"/>
1665/// # let _ = items; Ok(()) }
1666/// ```
1667///
1668/// Pass the model's [`MachineInfo`] (`info_of::<M>()`) to take the kind from
1669/// the states' tones and the title from the transitions' labels; without it
1670/// every item is `info` and titled with the transition's name.
1671pub fn timeline(rows: &[StateTransition], machine: Option<&MachineInfo>) -> Vec<Value> {
1672    rows.iter()
1673        .map(|row| {
1674            let label = machine
1675                .and_then(|m| m.transitions.iter().find(|t| t.name == row.transition))
1676                .map_or_else(|| row.transition.clone(), |t| t.label.clone());
1677            let kind = machine
1678                .and_then(|m| m.states.iter().find(|s| s.name == row.to_state))
1679                .and_then(|s| s.tone.as_deref())
1680                .map_or("info", |tone| match tone {
1681                    "danger" | "error" => "error",
1682                    "success" => "success",
1683                    "warning" => "warning",
1684                    _ => "info",
1685                });
1686            let title = match &row.from_state {
1687                Some(from) => format!("{label}: {from} \u{2192} {}", row.to_state),
1688                None => format!("{label}: {}", row.to_state),
1689            };
1690            serde_json::json!({
1691                "time": row.at.to_rfc3339(),
1692                "title": title,
1693                "body": row.reason,
1694                "kind": kind,
1695            })
1696        })
1697        .collect()
1698}