One explicit state graph in Laravel Go
Scope
Extract one model's state workflow into a typed value, explicit persisted mapping and authorized transition function. Preserve existing storage strings and custom business work. Exclude reflection-based class discovery, generic workflow registries and unrelated state fields. A state enum alone does not replace handlers with external effects. Keep the upstream MIT notice when adapting code.
At the time of writing, the Package Port catalog listed a community Go port. Offer a compatible maintained port before app-owned extraction 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 stores state morph values; State::getMorphClass chooses a configured name or PHP class name. src/HasStates.php supplies defaults and state query scopes. Storage values and response strings are therefore a compatibility contract, not enum positions to renumber.
src/State.php::transitionTo checks configured edges, resolves a handler and delegates to transition, which checks its guard, invokes handle and dispatches StateChanged. A direct transition($transition) skips transitionTo's configured-edge lookup. DefaultTransition::handle assigns and saves; those methods do not themselves add a transaction or stale-write lock, though app code/custom transitions can. StateConfig::ignoreSameState allows self-edges without guaranteeing handlers/events are suppressed.
Implementation
- Inventory actual aliases/class names in storage, defaults/nulls, transition classes, direct calls, guards, scopes, serializers and model/event hooks. Select one graph. Parse persisted values explicitly and reject unknowns; never let a Go zero value silently become the initial state. Keep legacy mappings while their values still exist.
- Put a fixed graph and use case in the app's existing action/service location. Accept
context.Context, trusted actor/tenant identity and typed input with expected state or an existing revision. Client input cannot select a handler/function/class name. Preserve custom handlers as explicit business code. Requiring the configured graph on every entry point is a deliberate restriction compared with direct package transitions; document affected callers. - Authorize the operation, then in
db.Transaction(ctx, func(txctx context.Context) error { ... })lock/reload the current row usingtxctx, recheck mutable ownership/guards and compare the expected state/version. Validate the edge only against that fresh state. All writers need the same locking protocol; SQLite requires a compatible write-serialization strategy, not an assumption that row locks exist. - Save the new state and associated audit/domain changes through the same transaction context. Return errors for rollback; a goroutine or outer-context query can escape this boundary. If using a conditional update, verify affected-row count and all relevant preconditions. A state-only comparison misses a leave-and-return cycle in cyclic graphs; use the app's existing monotonic revision where needed rather than silently adding schema.
- Send app-owned success notifications/cache invalidation after commit, using the existing outbox where durable delivery is required. This deliberately changes the package's immediate event timing, so retain necessary listener semantics explicitly.
db.AfterCommitcallback errors do not roll back committed data. External side effects need durable idempotency on retries; a unique queued job does not imply exactly-once execution. - Keep transport output outside the use case. Map states to existing API/storage strings, preserve query filtering and choose an explicit self-edge policy. The example rejects all self-edges; that deliberately differs from an upstream configuration permitting them. Avoid mutable global workflow/tenant state and use scoped cache keys.
Complete pure edge predicate for an illustrative task graph. Its string constants are example app-owned values, not an instruction to convert existing rows. It does not authorize, load, persist or run custom guards:
type TaskState string
const (
Queued TaskState = "queued"
Running TaskState = "running"
Completed TaskState = "completed"
Cancelled TaskState = "cancelled"
)
func allows(from, to TaskState) bool {
switch from {
case Queued:
return to == Running || to == Cancelled
case Running:
return to == Completed || to == Cancelled
default:
return false
}
}
Go permits conversion from arbitrary strings to TaskState; parsing and graph validation remain mandatory.
Acceptance checklist
- Accept only queued-to-running/cancelled and running-to-completed/cancelled for the example; reject queued-to-completed, completed-to-running, self-edges and unknown input. Derive expectations from the actual app's graph, not by calling the predicate to generate expected values.
- Round-trip every existing storage alias/class name, supported null/default and public response. Direct/HTTP/queue/CLI calls enforce the same required guards and authorization.
- Two independent connections concurrently attempt queued-to-running and queued-to-cancelled from the same expected state: exactly one succeeds; the loser conflicts without a partial audit write or success event.
- Inject failure after state write, read the original state from another connection, then exercise post-commit dispatch failure without repeating the committed operation. Replayed jobs follow an explicit idempotency/conflict policy.
- Test cross-tenant requests, revoked job-time authorization, custom transition work, required event/observer compatibility and worker isolation. Include concurrent calls under race instrumentation, but test database conflicts on the production driver too.
Run gofmt, go vet ./..., go test ./..., go test -race ./..., and real transaction/queue integration tests. Record versions/results and deliberate differences with the change. Remove the package only when all used casts, scopes, transitions and listeners have replacements.
Sources
- MIT reference source:
src/State.php,StateConfig.php,StateCaster.php,HasStates.php,Transition.php,DefaultTransition.php, andtests/TransitionTest.php. PreserveLICENSE.mdfor adapted source. - Framework source checked:
db/tx.go; check installed context, cancellation and after-commit behaviour against the metadata. - Port options: check
get-recipe's current port catalog (sourced from Package Port) at implementation time.