持久化状态机

属于 kxed 状态机组件(官网 | 源码)。

面向订单、支付、工单与审批流等业务实体的扁平持久化有限状态机插件。提供声明式转移表校验、同步/异步守卫(Guard)、后置异步回调(Hook)、乐观锁 CAS 并发控制、幂等重放、转移历史审计以及可插拔的存储适配器(Adapter 模式)。

快速接入#

在 Cargo.toml 开启主包 kxed 的 state-machine 特性(生产环境按需搭配 seaorm-* 或 state-machine-redis):

TOML
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["state-machine", "seaorm-sqlite"] }

在应用配置中选择存储适配器(默认 memory):

TOML
[state_machine]
backend = "database"
backend_timeout = "5s"
max_history_per_entity = 256

在业务代码中定义状态与事件,注册 StateMachinePlugin 并执行状态流转:

Rust
use kxed::plugins::state_machine::{
    EventKey, FireOptions, MachineDefinition, StateKey, StateMachinePlugin,
};
use kxed::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum OrderState {
    Draft,
    Paid,
}

impl StateKey for OrderState {
    fn as_str(&self) -> &str {
        match self {
            Self::Draft => "draft",
            Self::Paid => "paid",
        }
    }

    fn from_str(raw: &str) -> Option<Self> {
        match raw {
            "draft" => Some(Self::Draft),
            "paid" => Some(Self::Paid),
            _ => None,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum OrderEvent {
    Pay,
}

impl EventKey for OrderEvent {
    fn as_str(&self) -> &str {
        match self {
            Self::Pay => "pay",
        }
    }

    fn from_str(raw: &str) -> Option<Self> {
        match raw {
            "pay" => Some(Self::Pay),
            _ => None,
        }
    }
}

async fn pay_order(ctx: &AppCtx, order_id: &str) -> Result<String, AppErr> {
    let def = MachineDefinition::<OrderState, OrderEvent, ()>::builder("order", OrderState::Draft)
        .transition(OrderState::Draft, OrderEvent::Pay, OrderState::Paid)
        .build()?;
    let sm = ctx.state_machine()?.bind(def);
    let outcome = sm
        .fire(order_id, OrderEvent::Pay, FireOptions::new().with_key("pay-1"))
        .await?;
    Ok(outcome.to.as_str().to_owned())
}

存储适配器(Adapter 模式)#

核心运行时通过 StateMachineStore trait 与底层持久化解耦,内置三套适配器,同时支持调用 StateMachinePlugin::adapter(custom) 注入自定义适配器(例如直接读写业务表字段):

state_machine.backend存储实现所需特性与前置插件
memory(默认)MemoryStateMachineStorestate-machine(单实例内存,适合开发与测试)
databaseSqlStateMachineStorestate-machine 加任一 seaorm-*,注册 SeaOrmPlugin,支持 fire_in_tx 与业务表同事务提交
redisRedisStateMachineStorestate-machine-redis(或 cluster-backends),注册 RedisPlugin 并配置 redis.url

外部 SQL 事务协同#

使用 SqlStateMachineStore 时,可在业务 SeaORM 事务内调用 BoundMachine::fire_in_tx(&tx, ...),确保业务表更新与状态机状态及审计日志原子提交;返回的 PendingTxTransition 在 tx.commit().await? 成功后调用 .run_hooks().await? 触发异步后置回调,避免未提交事务产生脏副作用。

Config#

keydefaultcontract
state_machine.backendmemorymemory、database 或 redis(仅对 StateMachinePlugin::new() 生效)
state_machine.backend_timeout5s单次存储操作超时,范围 1ms..=5m
state_machine.max_history_per_entity256内存与 Redis 后端单实体最大历史条数,范围 1..=10000
state_machine.redis_key_prefixkxed:smRedis 键前缀,1..=128 字节且不含空白字符