use std::collections::BTreeMap;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::sync::{Arc, PoisonError, RwLock};
use futures_util::future::BoxFuture;
use serde::Serialize;
use serde_json::Value;
use crate::auth::AuthUser;
use crate::auth::permissions::Scope;
use crate::db::{
Col, DateTime, Db, DbError, Executor, Json, Migration, Model, Row, Transaction, now, sql,
};
use crate::events::Event;
use crate::{AppState, Result};
pub(crate) const MIGRATION: Migration = crate::db::framework_migration!(
"state_machine",
"00010101000410_create_state_transitions_table"
);
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct StateTransition {
pub id: i64,
pub model: String,
pub record_key: String,
pub from_state: Option<String>,
pub to_state: String,
pub transition: String,
pub actor_id: Option<i64>,
pub reason: Option<String>,
pub metadata: Value,
pub at: DateTime,
}
impl StateTransition {
fn from_row(row: &Row) -> std::result::Result<Self, DbError> {
let metadata: Json<Value> = row.try_get("metadata")?;
Ok(StateTransition {
id: row.try_get("id")?,
model: row.try_get("model")?,
record_key: row.try_get("record_key")?,
from_state: row.try_get("from_state")?,
to_state: row.try_get("to_state")?,
transition: row.try_get("transition")?,
actor_id: row.try_get("actor_id")?,
reason: row.try_get("reason")?,
metadata: metadata.0,
at: row.try_get("at")?,
})
}
}
#[derive(Debug, Clone, PartialEq)]
#[must_use = "a transition record is only stored when you call `record`"]
pub struct TransitionRecord {
model: String,
record_key: String,
from_state: Option<String>,
to_state: String,
transition: String,
actor_id: Option<i64>,
reason: Option<String>,
metadata: Value,
}
impl TransitionRecord {
pub fn new(
model: impl Into<String>,
key: impl ToString,
to_state: impl Into<String>,
transition: impl Into<String>,
) -> Self {
TransitionRecord {
model: model.into(),
record_key: key.to_string(),
from_state: None,
to_state: to_state.into(),
transition: transition.into(),
actor_id: None,
reason: None,
metadata: Value::Null,
}
}
pub fn from(mut self, state: impl Into<String>) -> Self {
self.from_state = Some(state.into());
self
}
pub fn actor(mut self, user_id: i64) -> Self {
self.actor_id = Some(user_id);
self
}
pub fn reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
pub fn metadata(mut self, metadata: Value) -> Self {
self.metadata = metadata;
self
}
pub async fn record<'c>(self, db: impl Executor<'c>) -> Result<StateTransition> {
let at = now();
let id: i64 = sql("INSERT INTO state_transitions \
(model, record_key, from_state, to_state, transition, actor_id, reason, metadata, at) \
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
.bind(self.model.as_str())
.bind(self.record_key.as_str())
.bind(self.from_state.as_deref())
.bind(self.to_state.as_str())
.bind(self.transition.as_str())
.bind(self.actor_id)
.bind(self.reason.as_deref())
.bind(Json(self.metadata.clone()))
.bind(at)
.scalar(db)
.await?;
Ok(StateTransition {
id,
model: self.model,
record_key: self.record_key,
from_state: self.from_state,
to_state: self.to_state,
transition: self.transition,
actor_id: self.actor_id,
reason: self.reason,
metadata: self.metadata,
at,
})
}
}
pub async fn history<'c>(
db: impl Executor<'c>,
model: &str,
key: impl ToString,
) -> Result<Vec<StateTransition>> {
let rows = sql(
"SELECT id, model, record_key, from_state, to_state, transition, actor_id, reason, \
metadata, at FROM state_transitions WHERE model = ? AND record_key = ? ORDER BY id",
)
.bind(model)
.bind(key.to_string())
.fetch_all(db)
.await?;
rows.iter()
.map(StateTransition::from_row)
.collect::<std::result::Result<_, _>>()
.map_err(Into::into)
}
pub trait StateMachine: Model {
type State: Copy + PartialEq + fmt::Display + Send + Sync + 'static;
const COLUMN: Col<Self, Self::State>;
fn machine() -> Machine<Self>;
fn available<'a>(
&'a self,
user: &'a AuthUser,
db: &'a Db,
) -> impl Future<Output = Result<Vec<Available>>> + Send + 'a
where
Self: Sized,
{
available_for(self, user, db)
}
fn insert_in_state<'a>(
&'a mut self,
tx: &'a mut Transaction,
state: Self::State,
reason: &'a str,
) -> impl Future<Output = Result> + Send + 'a
where
Self: Sized,
{
insert_in_state_for(self, tx, state, reason)
}
fn transition(&self, name: &str) -> TransitionBuilder<'_, Self>
where
Self: Sized,
{
TransitionBuilder {
record: self,
name: name.to_owned(),
actor: Actor::Unset,
reason: None,
input: Ok(Value::Null),
meta: Value::Null,
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum TransitionError {
Unauthenticated,
Forbidden,
NotFrom(String),
Guard(String),
Conflict,
Unknown(String),
ReasonRequired,
Failed(crate::Error),
}
impl fmt::Display for TransitionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TransitionError::Unauthenticated => f.write_str("log in to do this"),
TransitionError::Forbidden => f.write_str("you may not do this"),
TransitionError::NotFrom(state) => {
write!(f, "this can't be done from the state `{state}`")
}
TransitionError::Guard(message) => f.write_str(message),
TransitionError::Conflict => {
f.write_str("the record was changed by someone else; reload and try again")
}
TransitionError::Unknown(name) => write!(f, "there is no transition `{name}`"),
TransitionError::ReasonRequired => f.write_str("a reason is required"),
TransitionError::Failed(error) => write!(f, "the transition failed: {error:?}"),
}
}
}
impl std::error::Error for TransitionError {}
impl From<crate::Error> for TransitionError {
fn from(error: crate::Error) -> Self {
TransitionError::Failed(error)
}
}
impl From<DbError> for TransitionError {
fn from(error: DbError) -> Self {
TransitionError::Failed(error.into())
}
}
#[derive(Clone, Default)]
pub struct TransitionCtx {
actor: Option<AuthUser>,
reason: Option<String>,
input: Value,
meta: Value,
}
impl TransitionCtx {
pub fn new(actor: Option<AuthUser>) -> Self {
TransitionCtx {
actor,
..Default::default()
}
}
pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
pub fn with_input(mut self, input: Value) -> Self {
self.input = input;
self
}
pub fn with_meta(mut self, meta: Value) -> Self {
self.meta = meta;
self
}
pub fn actor(&self) -> Option<&AuthUser> {
self.actor.as_ref()
}
pub fn reason(&self) -> Option<&str> {
self.reason.as_deref()
}
pub fn input(&self) -> &Value {
&self.input
}
pub fn input_as<T: serde::de::DeserializeOwned>(&self) -> std::result::Result<T, String> {
serde_json::from_value(self.input.clone()).map_err(|e| e.to_string())
}
pub fn meta(&self) -> &Value {
&self.meta
}
}
type GuardFn<M> = Arc<
dyn for<'a> Fn(&'a M, &'a TransitionCtx) -> BoxFuture<'a, std::result::Result<(), String>>
+ Send
+ Sync,
>;
type EffectFn<M> = Arc<
dyn for<'a> Fn(&'a M, &'a TransitionCtx, &'a mut Transaction) -> BoxFuture<'a, Result>
+ Send
+ Sync,
>;
type ScopeFn<M> = Arc<dyn Fn(&M) -> Scope + Send + Sync>;
enum Access<M> {
Authenticated,
Permission(String),
PermissionIn(String, ScopeFn<M>),
System,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct StateDef {
pub name: String,
pub tone: Option<String>,
pub terminal: bool,
}
pub struct Transition<M: StateMachine> {
name: String,
label: Option<String>,
tone: Option<String>,
from: Vec<String>,
to: Option<String>,
reason_required: bool,
access: Access<M>,
guards: Vec<(String, GuardFn<M>)>,
effects: Vec<EffectFn<M>>,
}
impl<M: StateMachine> Transition<M> {
pub fn new(name: impl Into<String>) -> Self {
Transition {
name: name.into(),
label: None,
tone: None,
from: Vec::new(),
to: None,
reason_required: false,
access: Access::Authenticated,
guards: Vec::new(),
effects: Vec::new(),
}
}
pub fn from<S: fmt::Display>(mut self, states: impl IntoIterator<Item = S>) -> Self {
self.from = states.into_iter().map(|s| s.to_string()).collect();
self
}
pub fn to(mut self, state: impl fmt::Display) -> Self {
self.to = Some(state.to_string());
self
}
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
pub fn tone(mut self, tone: impl Into<String>) -> Self {
self.tone = Some(tone.into());
self
}
pub fn reason_required(mut self) -> Self {
self.reason_required = true;
self
}
pub fn permission(mut self, permission: impl Into<String>) -> Self {
self.access = Access::Permission(permission.into());
self
}
pub fn permission_in(
mut self,
permission: impl Into<String>,
scope: impl Fn(&M) -> Scope + Send + Sync + 'static,
) -> Self {
self.access = Access::PermissionIn(permission.into(), Arc::new(scope));
self
}
pub fn system(mut self) -> Self {
self.access = Access::System;
self
}
pub fn guard<F>(mut self, name: impl Into<String>, guard: F) -> Self
where
F: for<'a> Fn(&'a M, &'a TransitionCtx) -> BoxFuture<'a, std::result::Result<(), String>>
+ Send
+ Sync
+ 'static,
{
self.guards.push((name.into(), Arc::new(guard)));
self
}
pub fn effect<F>(mut self, effect: F) -> Self
where
F: for<'a> Fn(&'a M, &'a TransitionCtx, &'a mut Transaction) -> BoxFuture<'a, Result>
+ Send
+ Sync
+ 'static,
{
self.effects.push(Arc::new(effect));
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn label_text(&self) -> String {
self.label.clone().unwrap_or_else(|| humanize(&self.name))
}
pub fn tone_name(&self) -> Option<&str> {
self.tone.as_deref()
}
pub fn from_states(&self) -> &[String] {
&self.from
}
pub fn to_state(&self) -> Option<&str> {
self.to.as_deref()
}
pub fn needs_reason(&self) -> bool {
self.reason_required
}
pub fn is_system(&self) -> bool {
matches!(self.access, Access::System)
}
pub fn guard_names(&self) -> Vec<&str> {
self.guards.iter().map(|(n, _)| n.as_str()).collect()
}
pub fn check_access(
&self,
record: &M,
actor: Option<&AuthUser>,
) -> std::result::Result<(), TransitionError> {
let Some(user) = actor else {
return if self.is_system() {
Ok(())
} else {
Err(TransitionError::Unauthenticated)
};
};
let allowed = match &self.access {
Access::Authenticated => true,
Access::Permission(p) => user.has_permission(p),
Access::PermissionIn(p, scope) => user.has_permission_in(p, &scope(record)),
Access::System => false,
};
if allowed {
Ok(())
} else {
Err(TransitionError::Forbidden)
}
}
pub fn check_from(
&self,
current: impl fmt::Display,
) -> std::result::Result<(), TransitionError> {
let current = current.to_string();
if self.from.contains(¤t) {
Ok(())
} else {
Err(TransitionError::NotFrom(current))
}
}
pub async fn check_guards(
&self,
record: &M,
ctx: &TransitionCtx,
) -> std::result::Result<(), TransitionError> {
for (_, guard) in &self.guards {
guard(record, ctx).await.map_err(TransitionError::Guard)?;
}
Ok(())
}
pub async fn run_effects(
&self,
record: &M,
ctx: &TransitionCtx,
tx: &mut Transaction,
) -> Result {
for effect in &self.effects {
effect(record, ctx, tx).await?;
}
Ok(())
}
}
fn humanize(name: &str) -> String {
let text = name.replace(['_', '-'], " ");
let mut chars = text.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
}
pub struct Machine<M: StateMachine> {
states: Vec<StateDef>,
initial: Vec<String>,
transitions: Vec<Transition<M>>,
last: Option<usize>,
}
impl<M: StateMachine> Default for Machine<M> {
fn default() -> Self {
Self::new()
}
}
impl<M: StateMachine> Machine<M> {
pub fn new() -> Self {
Machine {
states: Vec::new(),
initial: Vec::new(),
transitions: Vec::new(),
last: None,
}
}
fn index_of(&mut self, name: &str) -> usize {
if let Some(i) = self.states.iter().position(|s| s.name == name) {
return i;
}
self.states.push(StateDef {
name: name.to_owned(),
tone: None,
terminal: false,
});
self.states.len() - 1
}
pub fn state(mut self, state: impl fmt::Display) -> Self {
let i = self.index_of(&state.to_string());
self.last = Some(i);
self
}
pub fn tone(mut self, tone: impl Into<String>) -> Self {
let i = self.last.expect("`tone` follows `state`");
self.states[i].tone = Some(tone.into());
self
}
pub fn terminal(mut self) -> Self {
let i = self.last.expect("`terminal` follows `state`");
self.states[i].terminal = true;
self
}
pub fn initial<S: fmt::Display>(mut self, states: impl IntoIterator<Item = S>) -> Self {
let names: Vec<String> = states.into_iter().map(|s| s.to_string()).collect();
for name in &names {
self.index_of(name);
}
self.initial = names;
self
}
pub fn transition(mut self, transition: Transition<M>) -> Self {
let to = transition
.to
.clone()
.unwrap_or_else(|| panic!("transition `{}` has no `to` state", transition.name));
assert!(
!transition.from.is_empty(),
"transition `{}` has no `from` state",
transition.name
);
assert!(
self.transitions.iter().all(|t| t.name != transition.name),
"transition `{}` is defined twice",
transition.name
);
for name in transition.from.clone().iter().chain([&to]) {
self.index_of(name);
}
for from in &transition.from {
let terminal = self.states.iter().any(|s| &s.name == from && s.terminal);
assert!(
!terminal,
"transition `{}` leaves the terminal state `{from}`",
transition.name
);
}
self.last = None;
self.transitions.push(transition);
self
}
pub fn states(&self) -> &[StateDef] {
&self.states
}
pub fn initial_states(&self) -> &[String] {
&self.initial
}
pub fn transitions(&self) -> &[Transition<M>] {
&self.transitions
}
pub fn find(&self, name: &str) -> std::result::Result<&Transition<M>, TransitionError> {
self.transitions
.iter()
.find(|t| t.name == name)
.ok_or_else(|| TransitionError::Unknown(name.to_owned()))
}
pub fn from_state<'a>(
&'a self,
state: &'a str,
) -> impl Iterator<Item = &'a Transition<M>> + 'a {
self.transitions
.iter()
.filter(move |t| t.from.iter().any(|f| f == state))
}
pub fn mermaid(&self) -> String {
let mut out = String::from("stateDiagram-v2\n");
for name in &self.initial {
out.push_str(&format!(" [*] --> {}\n", mermaid_id(name)));
}
for t in &self.transitions {
let to = t.to.as_deref().unwrap_or_default();
for from in &t.from {
out.push_str(&format!(
" {} --> {}: {}\n",
mermaid_id(from),
mermaid_id(to),
t.name
));
}
}
for state in self.states.iter().filter(|s| s.terminal) {
out.push_str(&format!(" {} --> [*]\n", mermaid_id(&state.name)));
}
out
}
}
fn mermaid_id(name: &str) -> String {
name.chars()
.map(|c| if c.is_alphanumeric() { c } else { '_' })
.collect()
}
enum Actor {
Unset,
User(Box<AuthUser>),
System,
}
#[must_use = "a transition only runs when you call `run` or `run_in`"]
pub struct TransitionBuilder<'a, M: StateMachine> {
record: &'a M,
name: String,
actor: Actor,
reason: Option<String>,
input: std::result::Result<Value, String>,
meta: Value,
}
impl<M: StateMachine> TransitionBuilder<'_, M> {
pub fn by(mut self, user: &AuthUser) -> Self {
self.actor = Actor::User(Box::new(user.clone()));
self
}
pub fn by_system(mut self) -> Self {
self.actor = Actor::System;
self
}
pub fn reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
pub fn input<T: Serialize>(mut self, input: &T) -> Self {
self.input = serde_json::to_value(input).map_err(|e| e.to_string());
self
}
pub fn meta(mut self, meta: Value) -> Self {
self.meta = meta;
self
}
pub async fn run(self, state: &AppState) -> std::result::Result<Outcome<M>, TransitionError> {
let mut tx = state.db.begin().await?;
let outcome = self.run_in(&mut tx).await?;
tx.commit().await?;
if let Outcome::Done(done) = &outcome {
state.emit(done.clone()).await?;
}
Ok(outcome)
}
pub async fn run_in(
self,
tx: &mut Transaction,
) -> std::result::Result<Outcome<M>, TransitionError> {
let machine = M::machine();
let transition = machine.find(&self.name)?;
let record = self.record;
let actor = match &self.actor {
Actor::Unset => return Err(TransitionError::Unauthenticated),
Actor::User(user) => Some(user.as_ref()),
Actor::System => None,
};
transition.check_access(record, actor)?;
let current = current_state(record)?;
transition.check_from(¤t)?;
let input = self.input.map_err(|e| {
TransitionError::Failed(crate::Error::Internal(anyhow::anyhow!(
"the transition's input is not JSON: {e}"
)))
})?;
let mut ctx = TransitionCtx::new(actor.cloned())
.with_input(input)
.with_meta(self.meta.clone());
if let Some(reason) = &self.reason {
ctx = ctx.with_reason(reason.clone());
}
transition.check_guards(record, &ctx).await?;
if transition.needs_reason() && self.reason.as_deref().is_none_or(|r| r.trim().is_empty()) {
return Err(TransitionError::ReasonRequired);
}
let to = transition
.to_state()
.expect("a built machine has a `to` state")
.to_owned();
if let Some(interceptor) = interceptor() {
let request = TransitionRequest {
model: M::TABLE,
key: record.id().to_string(),
transition: transition.name().to_owned(),
from: current.clone(),
to: to.clone(),
actor: actor.cloned(),
reason: self.reason.clone(),
input: ctx.input().clone(),
meta: self.meta.clone(),
};
if let Decision::Defer(data) = interceptor.intercept(&request, &mut *tx).await? {
return Ok(Outcome::Pending(Pending {
key: record.id(),
from: current,
to,
transition: transition.name().to_owned(),
actor_id: actor.map(|u| u.id),
reason: self.reason,
meta: self.meta,
data,
}));
}
}
let column = M::COLUMN.name();
let moved = sql(format!(
"UPDATE {} SET {column} = ? WHERE id = ? AND {column} = ?",
M::TABLE
))
.bind(to.as_str())
.bind(record.id())
.bind(current.as_str())
.execute(&mut *tx)
.await?;
if moved == 0 {
return Err(TransitionError::Conflict);
}
let mut row = TransitionRecord::new(M::TABLE, record.id(), to.as_str(), transition.name())
.from(current.as_str())
.metadata(self.meta.clone());
if let Some(user) = actor {
row = row.actor(user.id);
}
if let Some(reason) = &self.reason {
row = row.reason(reason.clone());
}
row.record(&mut *tx).await?;
transition.run_effects(record, &ctx, tx).await?;
Ok(Outcome::Done(Transitioned {
key: record.id(),
from: current,
to,
transition: transition.name().to_owned(),
actor_id: actor.map(|u| u.id),
reason: self.reason,
meta: self.meta,
_model: PhantomData,
}))
}
}
tokio::task_local! {
static INSERT_ANY_STATE: ();
}
#[doc(hidden)]
pub fn check_insert<M: StateMachine>(record: &M) -> Result {
if INSERT_ANY_STATE.try_with(|_| ()).is_ok() {
return Ok(());
}
let machine = M::machine();
let initial = machine.initial_states();
if initial.is_empty() {
return Ok(());
}
let current = current_state(record).map_err(TransitionError::into_error)?;
if initial.contains(¤t) {
return Ok(());
}
Err(crate::Error::Status(
axum::http::StatusCode::UNPROCESSABLE_ENTITY,
format!(
"a new {} can't start in the state `{current}` (it starts in {}); \
use `insert_in_state` for an exception",
M::TABLE,
initial
.iter()
.map(|s| format!("`{s}`"))
.collect::<Vec<_>>()
.join(" or "),
),
))
}
async fn insert_in_state_for<M: StateMachine>(
record: &mut M,
tx: &mut Transaction,
state: M::State,
reason: &str,
) -> Result {
let current = current_state(record).map_err(TransitionError::into_error)?;
let wanted = state.to_string();
if current != wanted {
return Err(anyhow::anyhow!(
"insert_in_state: the record's status is `{current}`, not `{wanted}`; set it first"
)
.into());
}
INSERT_ANY_STATE.scope((), record.insert(&mut *tx)).await?;
TransitionRecord::new(M::TABLE, record.id(), wanted, "insert")
.reason(reason)
.record(&mut *tx)
.await?;
Ok(())
}
fn current_state<M: StateMachine>(record: &M) -> std::result::Result<String, TransitionError> {
let column = M::COLUMN.name();
let at = M::COLUMNS
.iter()
.filter(|c| **c != "id")
.position(|c| *c == column);
match at.and_then(|i| record.values().into_iter().nth(i)) {
Some(crate::db::DbValue::Text(state)) => Ok(state),
_ => Err(TransitionError::Failed(crate::Error::Internal(
anyhow::anyhow!("the status column `{column}` is not a text column of the model"),
))),
}
}
#[must_use = "emit it after the transaction commits"]
pub struct Transitioned<M: StateMachine> {
pub key: M::Key,
pub from: String,
pub to: String,
pub transition: String,
pub actor_id: Option<i64>,
pub reason: Option<String>,
pub meta: Value,
_model: PhantomData<fn() -> M>,
}
impl<M: StateMachine> Clone for Transitioned<M> {
fn clone(&self) -> Self {
Transitioned {
key: self.key.clone(),
from: self.from.clone(),
to: self.to.clone(),
transition: self.transition.clone(),
actor_id: self.actor_id,
reason: self.reason.clone(),
meta: self.meta.clone(),
_model: PhantomData,
}
}
}
impl<M: StateMachine> fmt::Debug for Transitioned<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Transitioned")
.field("model", &M::TABLE)
.field("key", &self.key)
.field("from", &self.from)
.field("to", &self.to)
.field("transition", &self.transition)
.finish()
}
}
impl<M: StateMachine> Event for Transitioned<M> {}
impl<M: StateMachine> Transitioned<M> {
pub async fn emit(self, state: &AppState) -> Result {
state.emit(self).await
}
}
#[must_use = "emit a `Done` outcome after the transaction commits"]
pub enum Outcome<M: StateMachine> {
Done(Transitioned<M>),
Pending(Pending<M>),
}
impl<M: StateMachine> Clone for Outcome<M> {
fn clone(&self) -> Self {
match self {
Outcome::Done(done) => Outcome::Done(done.clone()),
Outcome::Pending(pending) => Outcome::Pending(pending.clone()),
}
}
}
impl<M: StateMachine> Outcome<M> {
pub fn into_done(self) -> Option<Transitioned<M>> {
match self {
Outcome::Done(done) => Some(done),
Outcome::Pending(_) => None,
}
}
pub fn is_pending(&self) -> bool {
matches!(self, Outcome::Pending(_))
}
pub async fn emit(self, state: &AppState) -> Result {
match self {
Outcome::Done(done) => done.emit(state).await,
Outcome::Pending(_) => Ok(()),
}
}
}
#[non_exhaustive]
pub struct Pending<M: StateMachine> {
pub key: M::Key,
pub from: String,
pub to: String,
pub transition: String,
pub actor_id: Option<i64>,
pub reason: Option<String>,
pub meta: Value,
pub data: Value,
}
impl<M: StateMachine> Clone for Pending<M> {
fn clone(&self) -> Self {
Pending {
key: self.key.clone(),
from: self.from.clone(),
to: self.to.clone(),
transition: self.transition.clone(),
actor_id: self.actor_id,
reason: self.reason.clone(),
meta: self.meta.clone(),
data: self.data.clone(),
}
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct TransitionRequest {
pub model: &'static str,
pub key: String,
pub transition: String,
pub from: String,
pub to: String,
pub actor: Option<AuthUser>,
pub reason: Option<String>,
pub input: Value,
pub meta: Value,
}
impl TransitionRequest {
pub fn new(
model: &'static str,
key: impl ToString,
transition: impl Into<String>,
from: impl Into<String>,
to: impl Into<String>,
) -> Self {
TransitionRequest {
model,
key: key.to_string(),
transition: transition.into(),
from: from.into(),
to: to.into(),
actor: None,
reason: None,
input: Value::Null,
meta: Value::Null,
}
}
pub fn with_input(mut self, input: Value) -> Self {
self.input = input;
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Decision {
Proceed,
Defer(Value),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Preview {
Proceed,
RequiresApproval,
Pending,
}
pub trait TransitionInterceptor: Send + Sync + 'static {
fn intercept<'a>(
&'a self,
request: &'a TransitionRequest,
tx: &'a mut Transaction,
) -> BoxFuture<'a, Result<Decision>>;
fn preview<'a>(
&'a self,
request: &'a TransitionRequest,
db: &'a Db,
) -> BoxFuture<'a, Result<Preview>> {
let _ = (request, db);
Box::pin(async { Ok(Preview::Proceed) })
}
}
static INTERCEPTOR: RwLock<Option<Arc<dyn TransitionInterceptor>>> = RwLock::new(None);
pub fn set_interceptor(interceptor: impl TransitionInterceptor) {
*INTERCEPTOR.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(interceptor));
}
pub fn clear_interceptor() {
*INTERCEPTOR.write().unwrap_or_else(PoisonError::into_inner) = None;
}
fn interceptor() -> Option<Arc<dyn TransitionInterceptor>> {
INTERCEPTOR
.read()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
pub async fn preview(request: &TransitionRequest, db: &Db) -> Result<Preview> {
match interceptor() {
Some(interceptor) => interceptor.preview(request, db).await,
None => Ok(Preview::Proceed),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Available {
pub name: String,
pub label: String,
pub tone: Option<String>,
pub needs_reason: bool,
pub requires_approval: bool,
}
async fn available_for<M: StateMachine>(
record: &M,
user: &AuthUser,
db: &Db,
) -> Result<Vec<Available>> {
let machine = M::machine();
let current = current_state(record).map_err(TransitionError::into_error)?;
let ctx = TransitionCtx::new(Some(user.clone()));
let mut out = Vec::new();
for transition in machine.from_state(¤t) {
if transition.is_system()
|| transition.check_access(record, Some(user)).is_err()
|| transition.check_guards(record, &ctx).await.is_err()
{
continue;
}
let to = transition.to_state().unwrap_or_default().to_owned();
let mut request = TransitionRequest::new(
M::TABLE,
record.id(),
transition.name(),
current.as_str(),
to,
);
request.actor = Some(user.clone());
let requires_approval = preview(&request, db).await? != Preview::Proceed;
out.push(Available {
name: transition.name().to_owned(),
label: transition.label_text(),
tone: transition.tone_name().map(str::to_owned),
needs_reason: transition.needs_reason(),
requires_approval,
});
}
Ok(out)
}
impl TransitionError {
pub fn into_error(self) -> crate::Error {
match self {
TransitionError::Unauthenticated => crate::Error::Unauthorized,
TransitionError::Forbidden => crate::Error::Forbidden,
TransitionError::Unknown(_) => crate::Error::NotFound,
TransitionError::Failed(error) => error,
other => crate::Error::Status(
axum::http::StatusCode::UNPROCESSABLE_ENTITY,
other.to_string(),
),
}
}
}
impl axum::response::IntoResponse for TransitionError {
fn into_response(self) -> axum::response::Response {
axum::response::IntoResponse::into_response(self.into_error())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct TransitionInfo {
pub name: String,
pub label: String,
pub tone: Option<String>,
pub from: Vec<String>,
pub to: String,
pub needs_reason: bool,
pub system: bool,
pub guards: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct MachineInfo {
pub model: String,
pub table: String,
pub states: Vec<StateDef>,
pub initial: Vec<String>,
pub transitions: Vec<TransitionInfo>,
pub mermaid: String,
}
static REGISTRY: RwLock<BTreeMap<String, MachineInfo>> = RwLock::new(BTreeMap::new());
pub fn register<M: StateMachine>() {
let info = info_of::<M>();
REGISTRY
.write()
.unwrap_or_else(PoisonError::into_inner)
.insert(info.model.clone(), info);
}
pub fn info_of<M: StateMachine>() -> MachineInfo {
let machine = M::machine();
let model = std::any::type_name::<M>()
.rsplit("::")
.next()
.unwrap_or_default()
.to_owned();
MachineInfo {
model,
table: M::TABLE.to_owned(),
states: machine.states().to_vec(),
initial: machine.initial_states().to_vec(),
transitions: machine
.transitions()
.iter()
.map(|t| TransitionInfo {
name: t.name().to_owned(),
label: t.label_text(),
tone: t.tone_name().map(str::to_owned),
from: t.from_states().to_vec(),
to: t.to_state().unwrap_or_default().to_owned(),
needs_reason: t.needs_reason(),
system: t.is_system(),
guards: t.guard_names().into_iter().map(str::to_owned).collect(),
})
.collect(),
mermaid: machine.mermaid(),
}
}
pub fn machine_info(name: &str) -> Option<MachineInfo> {
let registry = REGISTRY.read().unwrap_or_else(PoisonError::into_inner);
registry
.values()
.find(|m| m.model.eq_ignore_ascii_case(name) || m.table.eq_ignore_ascii_case(name))
.cloned()
}
pub fn machine_names() -> Vec<String> {
REGISTRY
.read()
.unwrap_or_else(PoisonError::into_inner)
.keys()
.cloned()
.collect()
}
pub fn routes<M: StateMachine + Send + Sync + 'static>() -> crate::routing::Routes {
crate::routing::Routes::new().post("/{id}/transitions/{name}", run_transition::<M>)
}
#[derive(serde::Deserialize)]
struct ReasonForm {
reason: Option<String>,
}
async fn run_transition<M: StateMachine + Send + Sync + 'static>(
axum::extract::State(state): axum::extract::State<AppState>,
user: AuthUser,
axum::extract::Path((id, name)): axum::extract::Path<(String, String)>,
back: crate::Back,
axum::extract::Form(form): axum::extract::Form<ReasonForm>,
) -> Result<crate::Back> {
let key = id.parse::<M::Key>().map_err(|_| crate::Error::NotFound)?;
let record = M::find(&state.db, key)
.await?
.ok_or(crate::Error::NotFound)?;
let mut run = record.transition(&name).by(&user);
let reason = form.reason.unwrap_or_default();
let reason = reason.trim();
if !reason.is_empty() {
run = run.reason(reason);
}
let _outcome = run.run(&state).await.map_err(TransitionError::into_error)?;
Ok(back)
}
pub fn timeline(rows: &[StateTransition], machine: Option<&MachineInfo>) -> Vec<Value> {
rows.iter()
.map(|row| {
let label = machine
.and_then(|m| m.transitions.iter().find(|t| t.name == row.transition))
.map_or_else(|| row.transition.clone(), |t| t.label.clone());
let kind = machine
.and_then(|m| m.states.iter().find(|s| s.name == row.to_state))
.and_then(|s| s.tone.as_deref())
.map_or("info", |tone| match tone {
"danger" | "error" => "error",
"success" => "success",
"warning" => "warning",
_ => "info",
});
let title = match &row.from_state {
Some(from) => format!("{label}: {from} \u{2192} {}", row.to_state),
None => format!("{label}: {}", row.to_state),
};
serde_json::json!({
"time": row.at.to_rfc3339(),
"title": title,
"body": row.reason,
"kind": kind,
})
})
.collect()
}