1use 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#[derive(Debug, Clone, PartialEq, Serialize)]
97#[non_exhaustive]
98pub struct StateTransition {
99 pub id: i64,
101 pub model: String,
103 pub record_key: String,
105 pub from_state: Option<String>,
107 pub to_state: String,
109 pub transition: String,
111 pub actor_id: Option<i64>,
113 pub reason: Option<String>,
115 pub metadata: Value,
117 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#[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 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 pub fn from(mut self, state: impl Into<String>) -> Self {
177 self.from_state = Some(state.into());
178 self
179 }
180
181 pub fn actor(mut self, user_id: i64) -> Self {
183 self.actor_id = Some(user_id);
184 self
185 }
186
187 pub fn reason(mut self, reason: impl Into<String>) -> Self {
189 self.reason = Some(reason.into());
190 self
191 }
192
193 pub fn metadata(mut self, metadata: Value) -> Self {
195 self.metadata = metadata;
196 self
197 }
198
199 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
231pub 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
251pub trait StateMachine: Model {
256 type State: Copy + PartialEq + fmt::Display + Send + Sync + 'static;
258
259 const COLUMN: Col<Self, Self::State>;
261
262 fn machine() -> Machine<Self>;
265
266 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 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 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#[derive(Debug)]
324#[non_exhaustive]
325pub enum TransitionError {
326 Unauthenticated,
328 Forbidden,
331 NotFrom(String),
334 Guard(String),
336 Conflict,
338 Unknown(String),
340 ReasonRequired,
342 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#[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 pub fn new(actor: Option<AuthUser>) -> Self {
393 TransitionCtx {
394 actor,
395 ..Default::default()
396 }
397 }
398
399 pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
401 self.reason = Some(reason.into());
402 self
403 }
404
405 pub fn with_input(mut self, input: Value) -> Self {
407 self.input = input;
408 self
409 }
410
411 pub fn with_meta(mut self, meta: Value) -> Self {
413 self.meta = meta;
414 self
415 }
416
417 pub fn actor(&self) -> Option<&AuthUser> {
419 self.actor.as_ref()
420 }
421
422 pub fn reason(&self) -> Option<&str> {
424 self.reason.as_deref()
425 }
426
427 pub fn input(&self) -> &Value {
429 &self.input
430 }
431
432 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 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
455enum Access<M> {
457 Authenticated,
459 Permission(String),
461 PermissionIn(String, ScopeFn<M>),
463 System,
465}
466
467#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
469#[non_exhaustive]
470pub struct StateDef {
471 pub name: String,
473 pub tone: Option<String>,
475 pub terminal: bool,
477}
478
479pub 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 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 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 pub fn to(mut self, state: impl fmt::Display) -> Self {
517 self.to = Some(state.to_string());
518 self
519 }
520
521 pub fn label(mut self, label: impl Into<String>) -> Self {
523 self.label = Some(label.into());
524 self
525 }
526
527 pub fn tone(mut self, tone: impl Into<String>) -> Self {
529 self.tone = Some(tone.into());
530 self
531 }
532
533 pub fn reason_required(mut self) -> Self {
535 self.reason_required = true;
536 self
537 }
538
539 pub fn permission(mut self, permission: impl Into<String>) -> Self {
541 self.access = Access::Permission(permission.into());
542 self
543 }
544
545 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 pub fn system(mut self) -> Self {
558 self.access = Access::System;
559 self
560 }
561
562 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 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 pub fn name(&self) -> &str {
595 &self.name
596 }
597
598 pub fn label_text(&self) -> String {
600 self.label.clone().unwrap_or_else(|| humanize(&self.name))
601 }
602
603 pub fn tone_name(&self) -> Option<&str> {
605 self.tone.as_deref()
606 }
607
608 pub fn from_states(&self) -> &[String] {
610 &self.from
611 }
612
613 pub fn to_state(&self) -> Option<&str> {
615 self.to.as_deref()
616 }
617
618 pub fn needs_reason(&self) -> bool {
620 self.reason_required
621 }
622
623 pub fn is_system(&self) -> bool {
625 matches!(self.access, Access::System)
626 }
627
628 pub fn guard_names(&self) -> Vec<&str> {
630 self.guards.iter().map(|(n, _)| n.as_str()).collect()
631 }
632
633 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 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(¤t) {
668 Ok(())
669 } else {
670 Err(TransitionError::NotFrom(current))
671 }
672 }
673
674 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 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
700fn 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
710pub struct Machine<M: StateMachine> {
712 states: Vec<StateDef>,
713 initial: Vec<String>,
714 transitions: Vec<Transition<M>>,
715 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 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 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 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 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 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 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 pub fn states(&self) -> &[StateDef] {
829 &self.states
830 }
831
832 pub fn initial_states(&self) -> &[String] {
834 &self.initial
835 }
836
837 pub fn transitions(&self) -> &[Transition<M>] {
839 &self.transitions
840 }
841
842 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 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 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
886fn mermaid_id(name: &str) -> String {
888 name.chars()
889 .map(|c| if c.is_alphanumeric() { c } else { '_' })
890 .collect()
891}
892
893enum Actor {
895 Unset,
897 User(Box<AuthUser>),
898 System,
899}
900
901#[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 pub fn by(mut self, user: &AuthUser) -> Self {
915 self.actor = Actor::User(Box::new(user.clone()));
916 self
917 }
918
919 pub fn by_system(mut self) -> Self {
922 self.actor = Actor::System;
923 self
924 }
925
926 pub fn reason(mut self, reason: impl Into<String>) -> Self {
928 self.reason = Some(reason.into());
929 self
930 }
931
932 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 pub fn meta(mut self, meta: Value) -> Self {
942 self.meta = meta;
943 self
944 }
945
946 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 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(¤t)?;
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 static INSERT_ANY_STATE: ();
1075}
1076
1077#[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(¤t) {
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
1131fn 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#[must_use = "emit it after the transaction commits"]
1150pub struct Transitioned<M: StateMachine> {
1151 pub key: M::Key,
1153 pub from: String,
1155 pub to: String,
1157 pub transition: String,
1159 pub actor_id: Option<i64>,
1161 pub reason: Option<String>,
1163 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 pub async fn emit(self, state: &AppState) -> Result {
1200 state.emit(self).await
1201 }
1202}
1203
1204#[must_use = "emit a `Done` outcome after the transaction commits"]
1206pub enum Outcome<M: StateMachine> {
1207 Done(Transitioned<M>),
1209 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 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 pub fn is_pending(&self) -> bool {
1233 matches!(self, Outcome::Pending(_))
1234 }
1235
1236 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#[non_exhaustive]
1249pub struct Pending<M: StateMachine> {
1250 pub key: M::Key,
1252 pub from: String,
1254 pub to: String,
1256 pub transition: String,
1258 pub actor_id: Option<i64>,
1260 pub reason: Option<String>,
1262 pub meta: Value,
1264 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#[derive(Clone)]
1287#[non_exhaustive]
1288pub struct TransitionRequest {
1289 pub model: &'static str,
1291 pub key: String,
1293 pub transition: String,
1295 pub from: String,
1297 pub to: String,
1299 pub actor: Option<AuthUser>,
1301 pub reason: Option<String>,
1303 pub input: Value,
1305 pub meta: Value,
1307}
1308
1309impl TransitionRequest {
1310 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 pub fn with_input(mut self, input: Value) -> Self {
1335 self.input = input;
1336 self
1337 }
1338}
1339
1340#[derive(Debug, Clone, PartialEq)]
1342pub enum Decision {
1343 Proceed,
1345 Defer(Value),
1347}
1348
1349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1352pub enum Preview {
1353 Proceed,
1355 RequiresApproval,
1357 Pending,
1359}
1360
1361pub trait TransitionInterceptor: Send + Sync + 'static {
1367 fn intercept<'a>(
1370 &'a self,
1371 request: &'a TransitionRequest,
1372 tx: &'a mut Transaction,
1373 ) -> BoxFuture<'a, Result<Decision>>;
1374
1375 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
1390pub fn set_interceptor(interceptor: impl TransitionInterceptor) {
1393 *INTERCEPTOR.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(interceptor));
1394}
1395
1396pub 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
1408pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1419#[non_exhaustive]
1420pub struct Available {
1421 pub name: String,
1423 pub label: String,
1425 pub tone: Option<String>,
1427 pub needs_reason: bool,
1429 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(¤t) {
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 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 fn into_response(self) -> axum::response::Response {
1495 axum::response::IntoResponse::into_response(self.into_error())
1496 }
1497}
1498
1499#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1501#[non_exhaustive]
1502pub struct TransitionInfo {
1503 pub name: String,
1505 pub label: String,
1507 pub tone: Option<String>,
1509 pub from: Vec<String>,
1511 pub to: String,
1513 pub needs_reason: bool,
1515 pub system: bool,
1517 pub guards: Vec<String>,
1519}
1520
1521#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1524#[non_exhaustive]
1525pub struct MachineInfo {
1526 pub model: String,
1528 pub table: String,
1530 pub states: Vec<StateDef>,
1532 pub initial: Vec<String>,
1534 pub transitions: Vec<TransitionInfo>,
1536 pub mermaid: String,
1538}
1539
1540static REGISTRY: RwLock<BTreeMap<String, MachineInfo>> = RwLock::new(BTreeMap::new());
1541
1542pub 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
1552pub 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
1583pub 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
1593pub fn machine_names() -> Vec<String> {
1595 REGISTRY
1596 .read()
1597 .unwrap_or_else(PoisonError::into_inner)
1598 .keys()
1599 .cloned()
1600 .collect()
1601}
1602
1603pub 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 let _outcome = run.run(&state).await.map_err(TransitionError::into_error)?;
1651 Ok(back)
1652}
1653
1654pub 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}