Laravel Rust✓ Human-reviewed

One explicit state graph in Laravel Rust

Replace one state workflow with an enum and authorized transition operation, retaining stored aliases, custom guards, atomic writes and deliberate event timing.

Approved 2026-12-04T14:14:44.304135Z · Submission 85

One explicit state graph in Laravel Rust

Scope

Replace one model's package-backed state field with an app-owned enum, explicit persisted-value mapping and one authorized transition operation. Keep existing database state values. Exclude runtime class discovery, generic transition containers, reflection attributes and unrelated workflows. Custom transitions with external side effects need their own durable delivery plan; they are not replaced by assigning an enum. Preserve the upstream MIT notice when adapting source.

At the time of writing, the Package Port catalog listed a community Rust port. Offer a compatible maintained port before choosing app-owned logic and check get-recipe's current port catalog. This guidance has not been exercised in your app; verify it with the checks below.

Source behaviour

The inspected src/StateCaster.php persists state morph names, not enum ordinals. src/State.php::getMorphClass uses a configured name or a class name. Renaming a PHP state class is therefore not automatically a safe storage migration. src/HasStates.php supplies configured defaults and query scopes; inventory these callers as well as transitions.

State::transitionTo checks configured edges and resolves a transition. transition checks canTransition, calls its handler through the container and dispatches StateChanged afterward. Direct transition($transition) does not perform transitionTo's configured-edge lookup. DefaultTransition::handle assigns/saves the model; these methods do not themselves supply a database transaction or stale-write lock. Custom handlers, model observers and enclosing app code can add behaviour. StateConfig::ignoreSameState permits a self-edge; don't assume that suppresses handler/event execution.

Implementation

  1. Inventory persisted aliases/class names, nulls/defaults, every configured edge, direct/custom transition calls, guards, query scopes, events and serialization. Select one finite graph. Map every observed stored value explicitly; unknown/null values are errors unless the existing contract deliberately supports them. Never default an unknown value to an initial state or rewrite all rows just to use prettier enum names.
  2. Define an enum and a fixed allowed-edge match beside the selected use case. Preserve custom handler work as explicit code, not a dynamic class name from request input. This recipe deliberately routes every entry point through the same edge/guard checks, including paths that previously used direct transitions; record any resulting restriction.
  3. Authenticate/authorize the operation with trusted actor/tenant identity. Parse the desired state through an allowlist, not Rust deserialization defaults. In the existing connection's transaction callback, lock/reload the model, check the caller's expected current state or existing version, recheck ownership/business guards and then validate the edge. A UI's list of allowed buttons is not enforcement. All writers must use the protocol; SQLite needs driver-specific write serialization.
  4. Use the callback's tx for all related database work and propagate errors. Save the state and any related audit/domain writes atomically. If using a conditional update instead of a lock, check its affected-row count and include every concurrency precondition; comparing state alone cannot detect a leave-and-return cycle in a graph that permits one. Do not introduce a version column as an unreviewed schema change.
  5. Publish app-owned success notifications/cache invalidation only after commit, or use the app's existing outbox for durable effects. This deliberately changes immediate source-event timing; preserve required listener behaviour explicitly. In the inspected Rust API an after-commit error can mean the database committed: do not retry the whole transition blindly. Keep external effects idempotent under job retries and don't treat queue uniqueness as exactly-once execution.
  6. Preserve API strings, null/error mapping and query filters using the explicit storage mapping. Decide same-state handling: this example rejects it, deliberately unlike configurations permitting self-transitions. Scope caches by tenant and invalidate only affected workflow projections.

Complete pure edge predicate for an illustrative task workflow; these are example enum names, not a storage migration. It deliberately rejects self-edges and transitions out of terminal states. Authorization, persisted mappings, guards and transactions remain outside it:

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TaskState { Queued, Running, Completed, Cancelled }

fn allows(from: TaskState, to: TaskState) -> bool {
    use TaskState::*;
    matches!((from, to), (Queued, Running | Cancelled) | (Running, Completed | Cancelled))
}

Acceptance checklist

  • For the illustrated graph, accept only queued-to-running/cancelled and running-to-completed/cancelled. Reject queued-to-completed, completed-to-running and every self-edge. Existing app graphs need their own independently enumerated expectations, including custom guard failures.
  • Round-trip every existing alias, legacy class-name value and supported null/default case without rewriting storage. Unknown states fail visibly. The HTTP/queue/CLI paths cannot bypass authorization or configured edges.
  • Two independent workers try queued-to-running and queued-to-cancelled with the same expected state: exactly one commits, the other conflicts, and no partial audit write or duplicate success event escapes. Use the actual production driver, not one shared test transaction.
  • Force a failure after the state write but before commit and verify the old state from a fresh connection. Then simulate post-commit dispatch failure and verify the caller does not repeat an already committed operation.
  • Replayed jobs follow the declared idempotency/conflict policy. Cross-tenant calls and stale permissions change nothing. Compare required model observers/custom handlers and event payload/timing with source-backed callers.

Run formatting, strict Clippy and the application's transition/authorization/queue integration tests. Record versions, concurrency results and deliberate differences with the change. Remove the package only after all state casts, transitions, scopes and listeners have replacements.

Sources

  • MIT reference source: src/State.php, StateConfig.php, StateCaster.php, HasStates.php, Transition.php, DefaultTransition.php, and tests/TransitionTest.php. Preserve LICENSE.md for adapted source.
  • Framework source checked: crates/database/src/db/connection.rs and db/neutral/transaction.rs; reconcile the metadata with installed transaction/after-commit semantics.
  • Port options: check get-recipe's current port catalog (sourced from Package Port) at implementation time.