Documentation
¶
Overview ¶
Package workflow is a generic workflow/BPM engine: it owns case state, transitions, assignment, and history for any process a consumer chooses to model as a Definition.
The defining constraint is that the engine stores ZERO domain data. A Case carries only a reference — Domain and ExternalID, e.g. ("compras", "solicitud-123") — never the purchase order, the teacher record, or any other business payload. There is no form builder, no key/value "tracked data" table, and no JSON blob of user fields attached to a case. A consumer that needs to show "what is this case about" looks the referenced object up in its own domain store using (Domain, ExternalID); this package has no opinion on, and no access to, that data.
Assignment is by organizational position and unit (see Eligibility), never by a person ID baked into the Definition. Resolving "who currently holds that position" — including deputy/subrogación handling — is deliberately left to a separate org-context service the caller owns: EligibilityFor returns the Eligibility for a case's current node, and the caller resolves it to actual people using whatever authority source it already has. This package never needs to know that resolution happened, or how.
Scope ¶
An operation belongs in the engine only when it must stay consistent with a case's tokens and its chained event trace. Authorization, audit_log writes, resolving people, domain data and periodic jobs stay in the consumer: for example, the engine exposes Overdue and Expire, and the consumer schedules the job that calls them.
Every new operation that moves tokens must join the random walk in random_walk_test.go, which checks the engine's invariants and its replay from events over generated definitions.
Index ¶
- Constants
- Variables
- func JoinRejected(_ context.Context, _ pgxtx.DBTX, c Case) (bool, error)
- func LastActorOf(history []Event, node string) string
- type Actor
- type ActorKind
- type AssignInput
- type AssigneeResolver
- type AssignmentDetail
- type BranchResult
- type CancelDetail
- type CancelInput
- type CancelTokenInput
- type Case
- type ChainBrokenError
- type ClaimInput
- type CommentPolicy
- type Config
- type DeadlineDetail
- type DeadlineResolver
- type Definition
- func (d Definition) AssignRules() []string
- func (d Definition) DeadlineRules() []string
- func (d Definition) EffectNames() []string
- func (d Definition) GuardNames() []string
- func (d Definition) Key() string
- func (d Definition) Node(id string) (Node, bool)
- func (d Definition) StartNode() (Node, bool)
- func (d Definition) TransitionsFrom(nodeID string) []Transition
- func (d Definition) Validate() error
- type DueInput
- type EffectSink
- type Eligibility
- type Engine
- func (e *Engine) Available(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]Transition, error)
- func (e *Engine) AvailableFor(ctx context.Context, db pgxtx.DBTX, caseID, tokenID uuid.UUID) ([]Transition, error)
- func (e *Engine) Cancel(ctx context.Context, db pgxtx.DBTX, in CancelInput) (*Case, error)
- func (e *Engine) CancelToken(ctx context.Context, db pgxtx.DBTX, in CancelTokenInput) (*MoveResult, error)
- func (e *Engine) Claim(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID, actorID string) (*Case, error)
- func (e *Engine) ClaimWith(ctx context.Context, db pgxtx.DBTX, in ClaimInput) (*Case, error)
- func (e *Engine) Definitions() []Definition
- func (e *Engine) EligibilityFor(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) (Eligibility, error)
- func (e *Engine) EligibilityForToken(ctx context.Context, db pgxtx.DBTX, caseID, tokenID uuid.UUID) (Eligibility, error)
- func (e *Engine) Expire(ctx context.Context, db pgxtx.DBTX, in ExpireInput) (*MoveResult, error)
- func (e *Engine) History(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]Event, error)
- func (e *Engine) Inbox(ctx context.Context, db pgxtx.DBTX, f InboxFilter) ([]WorkItem, error)
- func (e *Engine) JoinResults(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]JoinResult, error)
- func (e *Engine) Move(ctx context.Context, db pgxtx.DBTX, in MoveInput) (*Case, error)
- func (e *Engine) MoveDetailed(ctx context.Context, db pgxtx.DBTX, in MoveInput) (*MoveResult, error)
- func (e *Engine) Open(ctx context.Context, db pgxtx.DBTX, in OpenInput) (*Case, error)
- func (e *Engine) OpenDetailed(ctx context.Context, db pgxtx.DBTX, in OpenInput) (*MoveResult, error)
- func (e *Engine) Overdue(ctx context.Context, db pgxtx.DBTX, f OverdueFilter) ([]WorkItem, error)
- func (e *Engine) Participated(ctx context.Context, db pgxtx.DBTX, f ParticipationFilter) ([]Case, error)
- func (e *Engine) Reassign(ctx context.Context, db pgxtx.DBTX, in ReassignInput) (*Case, error)
- func (e *Engine) RecordFailure(ctx context.Context, db pgxtx.DBTX, in FailureInput) (Event, error)
- func (e *Engine) RefreshEligibility(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) (bool, error)
- func (e *Engine) Register(d Definition) error
- func (e *Engine) RegisterGuard(name string, fn GuardFunc) error
- func (e *Engine) Release(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID, actorID string) (*Case, error)
- func (e *Engine) ReleaseWith(ctx context.Context, db pgxtx.DBTX, in ReleaseInput) (*Case, error)
- func (e *Engine) SetDeadline(ctx context.Context, db pgxtx.DBTX, in SetDeadlineInput) (*Case, error)
- func (e *Engine) Tokens(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]Token, error)
- func (e *Engine) VerifyChain(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) error
- type Event
- type EventDigest
- type EventKind
- type ExpireInput
- type ExpiryDetail
- type FailureDetail
- type FailureInput
- type FailureKind
- type GuardFunc
- type InboxFilter
- type JoinBranch
- type JoinDetail
- type JoinPolicy
- type JoinRecord
- type JoinResult
- type MoveInput
- type MoveResult
- type Node
- type NodeKind
- type OpenInput
- type Option
- type Outcome
- type OverdueCursor
- type OverdueFilter
- type ParticipationFilter
- type ReassignInput
- type ReleaseInput
- type Repository
- type Scope
- type ScopeStatus
- type SetDeadlineInput
- type SplitDetail
- type Status
- type StepDetail
- type StepRecord
- type Token
- type TokenStatus
- type Transition
- type WaitingDetail
- type WorkItem
Constants ¶
const ( DefaultListLimit = 20 MaxListLimit = 1000 MaxListOffset = 100_000 )
List paging bounds. A repository list query applies them through InboxFilter.Page: DefaultListLimit replaces a non-positive Limit, a Limit above MaxListLimit is clamped to it, and an Offset outside [0, MaxListOffset] is rejected with ErrOffsetOutOfRange. Offset is rejected rather than clamped because a clamped offset would silently return a different page than the one asked for; the cap exists because Postgres reads and discards every skipped row, so an unbounded offset lets one request force a scan of the whole table. Callers that page deeper than MaxListOffset rows should filter (for example by time range) instead.
Twin: audit.Filters.Page and the audit paging constants (audit/audit.go) apply the same rules with the same values. The packages do not import each other, so the code is duplicated; change both together.
const CurrentEventSchema = 5
CurrentEventSchema is the Event.SchemaVersion the engine writes. Version 1 is every event stored before schema_version existed: no Detail. Version 2 adds Detail and LastSeq-assigned Seq. Version 3 adds TokenID and ScopeID; an older event reads as the case's root token in its root scope. Version 4 adds DeadlineAt; an older event reads with none. Version 5 adds the join policy details: the outcome in WaitingDetail, and the policy, verdict and branches in JoinDetail; an older event reads with none.
Variables ¶
var ( // ErrNotOverdue reports an Expire of a token whose deadline has not // passed (it must be strictly before now, as in Overdue), or that has // none. ErrNotOverdue = errors.New("workflow: token is not overdue") // ErrAlreadyExpired reports an Expire of a token whose current deadline // was already recorded as expired; a scheduler retry gets it instead of // a second EventExpired. ErrAlreadyExpired = errors.New("workflow: token deadline already expired") )
Sentinel errors of the deadline operations.
var ( ErrTokenRequired = errors.New("workflow: case has several active tokens; name one") ErrTokenNotFound = errors.New("workflow: token is not active in this case") ErrLastBranch = errors.New("workflow: cancelling this token would leave its scope without a live branch") ErrJoinRejected = errors.New("workflow: join rejected by the consumer's join check") ErrReasonRequired = errors.New("workflow: a reason is required") // ErrCaseWithoutTokens reports an open case stored without any token // row. Every binary since v0.19.0 writes a case's root token with the // case, so only a bug or a manual insert leaves one behind. ErrCaseWithoutTokens = errors.New("workflow: open case has no tokens") )
Sentinel errors of the token model.
var ( ErrDefinitionNotRegistered = errors.New("workflow: definition not registered") ErrGuardNotRegistered = errors.New("workflow: guard not registered") ErrCaseNotFound = errors.New("workflow: case not found") ErrCaseExists = errors.New("workflow: case already exists for that external reference") ErrCaseClosed = errors.New("workflow: case is closed") ErrInvalidTransition = errors.New("workflow: no such transition from current state") ErrGuardRejected = errors.New("workflow: guard rejected the transition") ErrNotAssigned = errors.New("workflow: case is not assigned") ErrAlreadyAssigned = errors.New("workflow: case is already assigned") ErrInvalidDefinition = errors.New("workflow: invalid definition") ErrCommentRequired = errors.New("workflow: comment is required for this transition") ErrCommentNotAllowed = errors.New("workflow: comment is not allowed for this transition") ErrNoRoute = errors.New("workflow: no route matched at decision node") // ErrTooManyDecisionHops reports a call that passed through more // decision nodes, or more splits and joins, than the engine allows. A // validated Definition never gets there (Validate rejects gateway-only // cycles). ErrTooManyDecisionHops = errors.New("workflow: exceeded maximum decision node hops") ErrReturnNotVisited = errors.New("workflow: case never occupied the return transition's target node") // ErrUnknownEffect reports that a Definition names an effect the Engine's // EffectSink does not know, or names any effect while no sink is set. ErrUnknownEffect = errors.New("workflow: effect not known to the effect sink") // ErrConflict reports that the case changed between the engine's read // and its write: its Revision no longer matches the stored row because a // concurrent writer committed first. The failing call persisted nothing // (no case update, no event); the caller should roll back its // transaction and may retry the whole operation from a fresh read. ErrConflict = errors.New("workflow: case was modified concurrently") // ErrUnsupportedEventSchema reports an event whose SchemaVersion is newer // than CurrentEventSchema: it was written by a newer binary, and reading // it here would silently drop the fields this one does not know. ErrUnsupportedEventSchema = errors.New("workflow: event schema version not supported by this binary") // ErrInvalidActor reports an input Actor the engine cannot record: an // unknown (or unspecified) kind, ActorSystem without an ID, or an Actor.ID // that differs from the deprecated ActorID set alongside it. ErrInvalidActor = errors.New("workflow: invalid actor") // ErrInvalidFailure reports a FailureInput the engine cannot record: an // unknown FailureKind, or a Detail that is not a JSON object. ErrInvalidFailure = errors.New("workflow: invalid failure record") // ErrChainBroken reports a case whose stored events no longer match // their hash chain (see Engine.VerifyChain); the error is a // *ChainBrokenError carrying the first bad Seq. ErrChainBroken = errors.New("workflow: event hash chain broken") )
Sentinel errors callers can branch on via errors.Is.
var ErrInvalidOutcome = errors.New("workflow: token waits at a policy join without a valid outcome")
ErrInvalidOutcome reports a token waiting at a join with a policy whose stored outcome is neither approved nor rejected: migration 011 was rolled back and applied again while it waited, it arrived before a registered definition gained the policy without a new version, or a custom Repository does not persist Token.Outcome. The call fails and persists nothing, rather than counting a vote it cannot read. The answer is still in the token's EventWaiting.
var ErrOffsetOutOfRange = errors.New("workflow: list offset out of range")
ErrOffsetOutOfRange is returned (wrapped) by a list query whose Offset is negative or above MaxListOffset. HTTP adapters map it to 400.
var ErrUnknownAssignRule = errors.New("workflow: assign rule not known to the assignee resolver")
ErrUnknownAssignRule reports a Definition declaring a Node.AssignRule while the Engine has no Config.Assignees.
var ErrUnknownDeadlineRule = errors.New("workflow: deadline rule not known to the deadline resolver")
ErrUnknownDeadlineRule reports a Definition declaring a Node.DeadlineRule while the Engine has no Config.Deadlines, or (from a resolver such as calendar.Rules) a rule name the resolver does not know.
Functions ¶
func JoinRejected ¶ added in v0.23.0
JoinRejected is a GuardFunc for the decision node after a join with a verdict policy: it passes when the round that just closed was rejected, so the decision's guarded route is the way back and its unguarded default the way forward. Register it under any name. It reads Case.JoinResult, so where no round closed in the current call it reports false.
func LastActorOf ¶ added in v0.23.0
LastActorOf returns the actor of the latest EventMoved leaving node with a non-system actor, or empty. It searches the whole history, not one scope, because each round of a parallel block opens a new scope. Rules that keep the person of an earlier step build on it (see AssigneeResolver).
Types ¶
type Actor ¶ added in v0.18.0
type Actor struct {
Kind ActorKind
// ID identifies the actor in the caller's identity source: a person id,
// a client id, or the name of a system component.
ID string
// ActingAs is the authority the actor used, e.g. "position@unit" and
// whether they act as holder, subrogante or delegate. The caller resolves
// it when the event happens: an org-context service answers for the
// present and cannot prove past authority.
ActingAs string
// OnBehalfOf is the person the actor acted for, when not themselves.
OnBehalfOf string
// Via is the client or channel the action came through.
Via string
}
Actor is who performed the action an Event records, resolved by the caller at event time.
type ActorKind ¶ added in v0.18.0
type ActorKind string
ActorKind classifies who performed the action an Event records.
const ( // ActorHuman is a person acting through the consumer's UI. It is the // kind of the deprecated ActorID alias. ActorHuman ActorKind = "human" // ActorOperator is a person acting with an administrative or support // authority over the case rather than as its assignee. ActorOperator ActorKind = "operator" // ActorSystem is the consumer's own automation (a scheduler, a worker). // It must carry an ID naming the component. ActorSystem ActorKind = "system" // ActorAPIClient is an external system calling the consumer's API. ActorAPIClient ActorKind = "api_client" // ActorAnonymous is an unauthenticated caller. ActorAnonymous ActorKind = "anonymous" // ActorUnspecified is the kind of an event written before actors had a // kind. The engine only reads it; an input carrying it is invalid. ActorUnspecified ActorKind = "unspecified" )
type AssignInput ¶ added in v0.23.0
AssignInput is what an AssigneeResolver receives: the rule a node declares, the case and token as they are being written, the node being entered, and the case's whole history, including the events this same call has planned so far. Case.State and Case.AssignedTo still hold their values from before the call, because they are projected from the tokens when the call persists: read Node and Token for where the token is going.
type AssigneeResolver ¶ added in v0.23.0
type AssigneeResolver interface {
Assignee(ctx context.Context, db pgxtx.DBTX, in AssignInput) (string, error)
}
AssigneeResolver turns a Node.AssignRule into the person a token entering that node goes to (see Config.Assignees). vogel never interprets the rule. An empty answer leaves the token in the node's pool. A returned error fails the call that entered the node, with nothing persisted.
Like a GuardFunc it runs inside the caller's open transaction: it must not call the network, so a consumer answers from local data.
type AssignmentDetail ¶ added in v0.18.0
type AssignmentDetail struct {
From string `json:"from"`
To string `json:"to"`
Reason string `json:"reason,omitempty"`
}
AssignmentDetail is the Event.Detail of EventAssigned (written by Claim, From empty) and EventUnassigned (written by Release, To empty). From and To are person ids; Reason is the caller's free-text reason for a release.
type BranchResult ¶ added in v0.23.0
type BranchResult struct {
Token uuid.UUID `json:"token"`
Outcome Outcome `json:"outcome"`
Seq int64 `json:"seq"`
}
BranchResult is one branch of a round in JoinDetail: its token, what it answered (OutcomeUnanswered when it was cancelled first) and the Seq of the event to read about it: the move into the join, holding the actor and the comment, or the EventTokenCancelled. A branch that was running a nested block when the round closed reports the first token cancelled inside that block.
type CancelDetail ¶ added in v0.19.0
type CancelDetail struct {
Reason string `json:"reason"`
}
CancelDetail is the Event.Detail of EventTokenCancelled and EventCancelled: the caller's reason, or join_policy:<policy> for a branch a join policy cancelled when it closed the round. It carries no node: each EventTokenCancelled records its branch's node in FromState, and Engine.Cancel emits one per live token right before its EventCancelled.
type CancelInput ¶ added in v0.19.0
type CancelInput struct {
CaseID uuid.UUID
Actor Actor
// Reason is required: Cancel fails with ErrReasonRequired when it is
// empty after trimming.
Reason string
// ExpectedRevision works like MoveInput.ExpectedRevision.
ExpectedRevision *int64
}
CancelInput describes the cancellation of a whole case.
type CancelTokenInput ¶ added in v0.19.0
type CancelTokenInput struct {
CaseID uuid.UUID
TokenID uuid.UUID
Actor Actor
// Reason is required (see CancelInput.Reason).
Reason string
}
CancelTokenInput describes the cancellation of one branch.
type Case ¶
type Case struct {
ID uuid.UUID
Definition string // definition name
Version int
// Tenant scopes the case; empty for a single-tenant consumer. A case is
// unique per (Tenant, Domain, ExternalID).
Tenant string
Domain string // e.g. "compras"
ExternalID string // e.g. "solicitud-123"
Unit string // organizational unit the case belongs to
// State is the node of the case's only active token: empty while the
// case has several active tokens (inside a parallel block), the terminal
// node once closed.
State string
Status Status
// AssignedTo is the person id holding the only active token; empty when
// it is unclaimed or the case has several active tokens.
AssignedTo string
OpenedAt time.Time
ClosedAt *time.Time
// DeadlineAt is the earliest deadline among the active tokens.
DeadlineAt *time.Time
// Revision is the row's optimistic-concurrency token. It is unrelated
// to Version, which is the Definition version the case runs on. Create
// always persists 0; every successful Repository.Update compares it
// against the stored value and advances both by one, so a write based on
// a stale read fails with ErrConflict instead of silently overwriting a
// concurrent change (a lost update).
Revision int64
// LastSeq is the Seq of the newest event appended to the case, 0 before
// any. The engine assigns the next events' Seq from it and persists the
// advanced value through the same Repository.Update compare-and-swap
// (Create for Open), so assigning a Seq never reads the history. A
// consumer can stamp it on its own rows to record which point of the
// case history they saw.
LastSeq int64
// JoinResult is the round a join with a policy just closed. It is set only
// on the snapshot guards receive while routing the call that fired that
// join (see workflow.JoinRejected), and nil everywhere else: a repository
// never reads or writes it. Engine.JoinResults reads rounds afterwards.
JoinResult *JoinResult
}
Case is a single running (or completed) instance of a Definition. It carries only a reference to the domain object it concerns — Domain and ExternalID — never the object's own data.
type ChainBrokenError ¶ added in v0.18.0
type ChainBrokenError struct {
CaseID uuid.UUID
// Seq is the first event that fails verification.
Seq int64
// Reason says which check failed.
Reason string
}
ChainBrokenError reports the first event of a case whose hash chain link does not hold. It matches ErrChainBroken with errors.Is.
func (*ChainBrokenError) Error ¶ added in v0.18.0
func (e *ChainBrokenError) Error() string
func (*ChainBrokenError) Is ¶ added in v0.18.0
func (e *ChainBrokenError) Is(target error) bool
Is reports whether target is ErrChainBroken.
type ClaimInput ¶ added in v0.18.0
type ClaimInput struct {
CaseID uuid.UUID
TokenID uuid.UUID
Actor Actor
// ExpectedRevision works like MoveInput.ExpectedRevision.
ExpectedRevision *int64
}
ClaimInput describes a claim: Actor becomes the token's assignee (its ID is stored as Token.AssignedTo), so Actor.ID is required whatever the kind. An empty Actor.Kind means ActorHuman. TokenID names the token; zero means the case's only active token (see MoveInput.TokenID).
type CommentPolicy ¶ added in v0.6.0
type CommentPolicy string
CommentPolicy controls whether a comment is required, optional, or disallowed when a Transition is taken. It is process history, not domain data: the engine stores the comment text on the Event it appends, but never interprets it.
const ( // CommentNone is the default: MoveInput.Comment must be empty (after // trimming) or Move fails with ErrCommentNotAllowed. Both the zero // value "" and the explicit literal "none" mean CommentNone, so a // Definition can spell out "no comment" without relying on the zero // value — see CommentPolicy.Canonical for how the alias is collapsed // back to this constant before any comparison. CommentNone CommentPolicy = "" // CommentOptional allows, but does not require, a comment. CommentOptional CommentPolicy = "optional" // CommentRequired fails Move with ErrCommentRequired when // MoveInput.Comment is empty after trimming. CommentRequired CommentPolicy = "required" )
func (CommentPolicy) Canonical ¶ added in v0.6.0
func (p CommentPolicy) Canonical() CommentPolicy
Canonical collapses the "none" alias into the CommentNone zero value, so every comparison site sees the same value regardless of which spelling a Definition used. Definition.Validate cannot normalize transitions in place for the caller — it has a value receiver, so any mutation would be discarded when it returns — so canonicalization happens here instead, at every comparison point (currently just checkComment). Comparing a raw, non-canonicalized CommentPolicy against the CommentNone constant with == silently disagrees for an alias-spelled value; call Canonical() first.
func (CommentPolicy) Valid ¶ added in v0.6.0
func (p CommentPolicy) Valid() bool
Valid reports whether p is one of the known CommentPolicy values.
type Config ¶
type Config struct {
// Now returns the current time. Nil uses time.Now — inject a fixed clock
// in tests.
Now func() time.Time
// TraceIDs, if set, returns the trace and span IDs of the span carried by
// a context, or empty strings when there is none; every appended event
// records them as Event.TraceID and Event.SpanID. Nil leaves both empty.
// It has the shape of postgres.Config.TraceIDs, so otel.SampledTraceIDs
// fits it without this package depending on any tracing library.
TraceIDs func(ctx context.Context) (traceID, spanID string)
// JoinCheck, if set, runs inside the transaction of every call that fires
// a join, before anything is written, with the scope as joined and the
// tokens it consumed. A non-nil error aborts the call with ErrJoinRejected
// wrapping it, and nothing is persisted. Consumers use it to enforce how
// branch-scoped data merges (reject a conflict, namespace or collect the
// branches' values) without the engine reading domain data. Like a
// GuardFunc it runs inside the caller's transaction and must not call the
// network.
JoinCheck func(ctx context.Context, db pgxtx.DBTX, j JoinRecord) error
// Deadlines resolves Node.DeadlineRule when a token enters a node that
// declares one. Nil means no definition may declare a deadline rule
// (Engine.Register fails with ErrUnknownDeadlineRule).
Deadlines DeadlineResolver
// Assignees resolves Node.AssignRule when a token comes to rest on a node
// that declares one. Nil means no definition may declare an assign rule
// (Engine.Register fails with ErrUnknownAssignRule).
Assignees AssigneeResolver
}
Config configures optional Engine behaviour.
type DeadlineDetail ¶ added in v0.20.0
type DeadlineDetail struct {
From *time.Time `json:"from"`
To *time.Time `json:"to"`
Reason string `json:"reason"`
}
DeadlineDetail is the Event.Detail of EventDeadlineChanged: the token's deadline before and after the change (nil when there was, or now is, none) and the caller's reason.
type DeadlineResolver ¶ added in v0.20.0
DeadlineResolver turns a Node.DeadlineRule into the deadline of a token entering that node (see Config.Deadlines and package workflow/calendar). A returned error fails the Open or Move that entered the node, with nothing persisted.
Like a GuardFunc it runs inside the caller's open transaction: it must not call the network. Load holiday calendars and similar data before, or keep them in memory.
type Definition ¶
type Definition struct {
Name string
Version int
Nodes []Node
Transitions []Transition
}
Definition describes one version of a workflow: its nodes, and the transitions permitted between them.
func (Definition) AssignRules ¶ added in v0.23.0
func (d Definition) AssignRules() []string
AssignRules returns the sorted, deduplicated set of assign rule names the Engine may resolve for this definition.
func (Definition) DeadlineRules ¶ added in v0.20.0
func (d Definition) DeadlineRules() []string
DeadlineRules returns the sorted, deduplicated set of deadline rule names the Engine may resolve for this definition: those of its non-terminal nodes. A terminal node closes the case on entry and never gets a deadline, so its rule is ignored and needs no resolver.
func (Definition) EffectNames ¶ added in v0.14.0
func (d Definition) EffectNames() []string
EffectNames returns the sorted, deduplicated set of effect names referenced by this definition's nodes and transitions.
func (Definition) GuardNames ¶
func (d Definition) GuardNames() []string
GuardNames returns the sorted, deduplicated set of guard names referenced by this definition's transitions.
func (Definition) Key ¶
func (d Definition) Key() string
Key returns the unique key this definition is registered under: "Name@Version".
func (Definition) Node ¶
func (d Definition) Node(id string) (Node, bool)
Node returns the node with the given ID, if any.
func (Definition) StartNode ¶
func (d Definition) StartNode() (Node, bool)
StartNode returns the definition's single start node, if any.
func (Definition) TransitionsFrom ¶
func (d Definition) TransitionsFrom(nodeID string) []Transition
TransitionsFrom returns every transition originating at nodeID.
func (Definition) Validate ¶
func (d Definition) Validate() error
Validate checks d for structural problems and returns a single error listing every violation found, wrapping ErrInvalidDefinition. It returns nil when d is well-formed.
type DueInput ¶ added in v0.20.0
DueInput is what a DeadlineResolver receives: the rule a node declares, the time the token entered the node, and the case and token as they are being written.
type EffectSink ¶ added in v0.14.0
type EffectSink interface {
// HasEffect reports whether name is an effect this sink can dispatch.
HasEffect(name string) bool
// CheckDB reports whether Dispatch could run on db. Open and Move call
// it before writing anything, whenever the case's definition declares
// at least one effect, so a db the sink cannot dispatch on (for example
// a pool where a transaction is required) fails the call with nothing
// persisted, instead of committing a transition whose effects are then
// lost.
CheckDB(db pgxtx.DBTX) error
// Dispatch is called by Open, Move, CancelToken and Expire (when it takes
// the node's OnExpire transition) exactly once, after all their
// persistence succeeded, with the definition the case runs on,
// the final case, and exactly the events that call appended, in Seq order
// (Open: the EventOpened; Move: the EventStepSubmitted when MoveInput.Step
// is set, the human-driven EventMoved, then every automatic event that
// followed it: decision-node hops, splits and the branch tokens' hops,
// waits, joins, and the EventClosed if the case closed). Each event names
// its Event.TokenID. db is the exact value the caller passed to that
// call, so whatever Dispatch writes commits or rolls back with the
// caller's transaction. A returned error fails the call (wrapped); the caller
// must then roll back. Like a GuardFunc, Dispatch runs inside that open
// transaction and must not call the network.
Dispatch(ctx context.Context, db pgxtx.DBTX, d Definition, c Case, events []Event) error
}
EffectSink turns the declarative effects a Definition names (Node.Effects, Transition.Effects) into work that runs outside the request advancing the case — typically by enqueuing jobs in the same transaction. The engine itself never runs an effect and never enqueues anything: it only asks the sink, at Register time, whether each name is known, and hands it the events each Open, Move, CancelToken or Expire appended.
type Eligibility ¶
Eligibility declares who may act on a node, by organizational position. An empty Unit means "the unit the case belongs to" — see ResolveUnit.
Eligibility never names a person. Turning a position+unit pair into the people who currently hold it (including deputy/subrogación resolution) is the caller's org-context service's job, not this package's.
func ByPosition ¶
func ByPosition(position string) Eligibility
ByPosition builds an Eligibility scoped to the case's own unit.
func ByPositionInUnit ¶
func ByPositionInUnit(position, unit string) Eligibility
ByPositionInUnit builds an Eligibility pinned to an explicit unit, overriding the case's own unit.
func (Eligibility) IsZero ¶
func (e Eligibility) IsZero() bool
IsZero reports whether e declares no position at all.
func (Eligibility) ResolveUnit ¶
func (e Eligibility) ResolveUnit(caseUnit string) string
ResolveUnit returns e.Unit when explicitly set, or caseUnit otherwise.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine runs a set of registered Definitions against a Repository: it opens cases, evaluates and applies transitions, tracks assignment, and records history.
func New ¶
New creates an Engine backed by repo. logger is required by the surrounding convention (libraries take a stdlib *slog.Logger); a nil logger falls back to slog.Default().
func (*Engine) Available ¶
func (e *Engine) Available(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]Transition, error)
Available returns the transitions leaving the current node of the case's only active token whose guard (if any) currently evaluates true; it is AvailableFor with a zero token ID, so a case with several active tokens fails with ErrTokenRequired. A closed or cancelled case offers none.
func (*Engine) AvailableFor ¶ added in v0.19.0
func (e *Engine) AvailableFor(ctx context.Context, db pgxtx.DBTX, caseID, tokenID uuid.UUID) ([]Transition, error)
AvailableFor returns the transitions leaving tokenID's current node whose guard (if any) currently evaluates true; a zero tokenID names the case's only active token (ErrTokenRequired with several, ErrTokenNotFound when the token is not active in the case). A return transition (Transition.Return) is filtered out unless the token's scope previously occupied its To node (see occupiedStates) — checked before the guard, exactly like Engine.Move orders the same two checks. A guard returning an error aborts the whole call. The case's event history is read at most once, and only when at least one candidate transition is a return.
func (*Engine) Cancel ¶ added in v0.19.0
Cancel ends an open case without reaching a terminal node: it cancels every active and waiting token (one EventTokenCancelled each, in token order), sets every open scope to ScopeCancelled, sets the case to StatusCancelled with ClosedAt, and appends one EventCancelled. Both kinds carry the reason in a CancelDetail. A case that is not open fails with ErrCaseClosed. Cancel never calls the EffectSink.
func (*Engine) CancelToken ¶ added in v0.19.0
func (e *Engine) CancelToken(ctx context.Context, db pgxtx.DBTX, in CancelTokenInput) (*MoveResult, error)
CancelToken cancels one active token (EventTokenCancelled with a CancelDetail) and counts it toward its scope's join: when every other token of the scope already waits, the join fires and routing continues in this same call, exactly like Move (effects dispatched, MoveResult.Joined reported). It fails with ErrLastBranch when the token is its scope's only live branch (a sibling running inside a nested block that has not joined counts as live), root scope included — an open case must never be left without a live token; use Cancel to end the whole case — with ErrTokenNotFound when the token is not active in the case, and with ErrCaseClosed when the case is not open.
func (*Engine) Claim ¶
func (e *Engine) Claim(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID, actorID string) (*Case, error)
Claim assigns the case to actorID, a person: it is ClaimWith with Actor{Kind: ActorHuman, ID: actorID}, so an empty actorID fails with ErrInvalidActor.
func (*Engine) ClaimWith ¶ added in v0.18.0
ClaimWith assigns the token to in.Actor.ID. Re-claiming by the same actor ID is a no-op success; claiming a token already assigned to someone else fails with ErrAlreadyAssigned. Claims are per token: two branches of one case can be held by different people. An invalid Actor, or one without an ID (a claim must name its assignee), fails with ErrInvalidActor before anything is read. ClaimWith never calls the EffectSink: no effect can be declared on a claim. Like Move, the case update is a revision compare-and-swap performed before the event is appended: a concurrent change fails with ErrConflict and persists nothing, so two racing claimers can never both win.
func (*Engine) Definitions ¶
func (e *Engine) Definitions() []Definition
Definitions returns every registered definition, sorted by Name then Version, for introspection.
func (*Engine) EligibilityFor ¶
func (e *Engine) EligibilityFor(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) (Eligibility, error)
EligibilityFor returns the eligibility of the node the case's only active token rests on, with ResolveUnit already applied against the case's own unit; it is EligibilityForToken with a zero token ID. This is what a caller hands to its org-context service to resolve actual people. A closed or cancelled case answers for the node it ended on.
func (*Engine) EligibilityForToken ¶ added in v0.19.0
func (e *Engine) EligibilityForToken(ctx context.Context, db pgxtx.DBTX, caseID, tokenID uuid.UUID) (Eligibility, error)
EligibilityForToken returns the eligibility of the node tokenID rests on, with ResolveUnit applied. A zero tokenID names the case's only active token (ErrTokenRequired with several, ErrTokenNotFound when the token is not active in the case).
func (*Engine) Expire ¶ added in v0.20.0
func (e *Engine) Expire(ctx context.Context, db pgxtx.DBTX, in ExpireInput) (*MoveResult, error)
Expire records that the token's deadline passed: it appends an EventExpired (ExpiryDetail) once per deadline and marks the token expired. When the token's node declares Node.OnExpire, Expire then moves the token through that transition in the same call and transaction, exactly like Move with in.Actor (decision nodes, splits, joins and closing included, effects dispatched once with every appended event); that EventMoved's Detail is {"cause":"expired"}. The transition's CommentPolicy does not apply (the system has nothing to comment), but its Guard does: a rejection fails Expire with ErrGuardRejected and persists nothing. Without OnExpire the token stays where it is, visibly overdue, and nothing is dispatched.
An Actor that is not a valid ActorSystem fails with ErrInvalidActor before anything is read. A token without a deadline, or whose deadline is after Config.Now, fails with ErrNotOverdue; one whose current deadline already expired fails with ErrAlreadyExpired, so a scheduler retry is idempotent. SetDeadline clears the mark. A case that is not open fails with ErrCaseClosed, and a concurrent change with ErrConflict.
func (*Engine) History ¶
History returns every event recorded for caseID, ordered by Seq ascending — see Event.Seq for why Seq, rather than OccurredAt, is the ordering key.
func (*Engine) Inbox ¶
Inbox returns one WorkItem per active token of an open case matching f, oldest case first, as before tokens existed, then the case's tokens in the order they entered their node, paged by f.Page. States, Eligibility, AssignedTo, Unassigned and Overdue apply to the token.
func (*Engine) JoinResults ¶ added in v0.23.0
func (e *Engine) JoinResults(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]JoinResult, error)
JoinResults returns one JoinResult per fired join with a policy of caseID, oldest first, with each branch's actor, comment and cause read from its event. Each round opens its own scope, so rounds stay apart: an earlier round's approvals never count in a later one. A case with no such join returns none, and an unknown case fails with ErrCaseNotFound.
func (*Engine) Move ¶
Move applies the transition matching (token's node, Action) to the token MoveInput.TokenID names (the case's only active token when zero), then — if that lands on a decision node, a split or a join — keeps routing automatically, within this same call and the same db transaction, until every token it touched comes to rest on a task node, waits at a join, or closes the case on a terminal node. A token is never persisted resting on a decision node, a split or a join.
A split consumes the arriving token, opens a Scope expecting one token per route taken (every route of a NodeParallel; every passing route of a NodeInclusive, or its default when none passes) and routes each new token in turn. A token arriving at its scope's join waits; once waiting plus cancelled tokens reach Scope.Expected, the join consumes the waiting ones, asks Config.JoinCheck, and one new token continues in the parent scope (which may cascade into an outer join). A Node.JoinPolicy can close the round earlier, cancelling the branches still pending in this same call; a later Move on one of them fails with ErrTokenNotFound. Every token and scope change is written after the case's revision compare-and-swap, so two moves of one case never commit concurrently: the slower fails with ErrConflict and its retry sees the other's tokens. Assignment is always cleared on a move, since a new node means a new claim, unless the node a token comes to rest on declares a Node.AssignRule and Config.Assignees names a person.
The human-driven transition is checked in a fixed order before anything is mutated: first its CommentPolicy (see checkComment), then — only if it is a return transition (Transition.Return) — whether the case previously occupied its To node (see occupiedStates), then its Guard, if any. A return whose target the case never occupied fails with ErrReturnNotVisited before the guard ever runs, exactly like a rejected comment fails before the guard runs; either failure leaves the case and its history completely untouched. A return transition that passes all three checks is applied exactly like any other move: Deadline and eligibility are recomputed for the node the case comes to rest on, and assignment is cleared, same as always — Move has no separate "undo" semantics for a return, it is just an ordinary transition whose destination happens to be an earlier node in the case's own history.
Each hop along the way — the initial human-driven move and every automatic decision-node hop after it — appends its own EventMoved, with Action set to that hop's transition (or route) label and ActorID set to the original MoveInput actor (see resolveActor) throughout. Only the first hop ever carries in.Comment; every automatic hop records an empty Comment, since the comment belongs to the human action that started the move, not to the domain-data routing that followed it. Deadline and eligibility only ever apply to the node the case actually comes to rest on.
If routing cannot find a matching route — a route's guard errors, or, defensively, a Definition that reached the engine without going through Validate somehow lacks an unguarded default — Move fails (with the guard's own error, or ErrNoRoute) and leaves the case and its history completely untouched: every hop, split and join is planned in memory before anything is written. A Config.JoinCheck rejection fails the same way, with ErrJoinRejected.
When the hop chain ends on a terminal node, the automatic EventClosed Move appends takes its Action from the LAST hop in the chain: the final automatic decision-node route's label when the human-driven transition landed on a decision node and routing continued from there, or the human-driven transition's own Action (in.Action) when it landed on the terminal node directly with no further hops. EventClosed.Action never repeats in.Action once a route hop followed it — it describes how the case actually reached the terminal node, not what the human asked for.
Effects: once the case update and every event are persisted, Move calls the EffectSink's Dispatch (when one is set) exactly once, with the final case and exactly the events this call appended, in Seq order. A Dispatch error fails Move after its writes went through the caller's db, so the caller must roll back its transaction. A Move that fails earlier never dispatches.
Concurrency: the case is written through Repository.Update, a compare-and-swap on Case.Revision, BEFORE any event is appended. If another writer changed the case after Move read it, Move fails with ErrConflict and appends no event; the caller must roll back its transaction (a guard may already have written to it) and may retry from a fresh read. The check only sees writers that advance Case.Revision: during a rolling deploy, a process still running a vogel release from before the revision column overwrites cases without advancing it, so its writes can be lost undetected until every such process is replaced (see workflow/postgres Repository.Update for the deploy order). The compare-and-swap also checks the LastSeq Move read, so a RecordFailure committed in between (it advances LastSeq, not Revision) fails Move with ErrConflict the same way, before anything is written.
func (*Engine) MoveDetailed ¶ added in v0.18.0
func (e *Engine) MoveDetailed(ctx context.Context, db pgxtx.DBTX, in MoveInput) (*MoveResult, error)
MoveDetailed is Move, also returning exactly the events it appended, in Seq order (the same slice the EffectSink receives): a consumer can stamp the Seq of the event that triggered its own write on that row.
func (*Engine) Open ¶
Open creates a case at the definition's start node and appends an EventOpened event as Seq 1. It is callable inside the caller's own transaction via db (see pgxtx.DBTX). When an EffectSink is set, Open then calls its Dispatch once with that event; a Dispatch error fails Open and the caller must roll back its transaction, discarding the new case.
func (*Engine) OpenDetailed ¶ added in v0.18.0
func (e *Engine) OpenDetailed(ctx context.Context, db pgxtx.DBTX, in OpenInput) (*MoveResult, error)
OpenDetailed is Open, also returning the EventOpened it appended (see MoveResult).
func (*Engine) Overdue ¶ added in v0.20.0
Overdue returns one WorkItem per active token of an open case whose deadline is before f.Before and not yet recorded as expired (see Expire), oldest deadline first, then token ID, at most f.Page() of them, starting after f.After when it is set. The periodic job that calls Overdue and then Expire for each item belongs to the consumer. A token Expire keeps failing for (an OnExpire guard that rejects, a route that fails) stays in the list, so the job pages with f.After set to the last item's OverdueCursor rather than calling Overdue again from the start, or such tokens would fill every page and starve the newer ones.
func (*Engine) Participated ¶ added in v0.18.0
func (e *Engine) Participated(ctx context.Context, db pgxtx.DBTX, f ParticipationFilter) ([]Case, error)
Participated returns the distinct cases in which f.ActorID appears as the actor of any event (opened, moved, claimed, released, a step submission or a recorded failure), open or closed, assigned to them or not, ordered by the actor's newest event in each case, newest first. It pages like Inbox (see ParticipationFilter.Page) and fails with ErrInvalidActor for an empty ActorID.
func (*Engine) Reassign ¶ added in v0.20.0
Reassign assigns the token to in.To whoever holds it now (nobody included), appending an EventAssigned whose AssignmentDetail records the previous assignee, the new one and the reason. An empty Reason fails with ErrReasonRequired, and an empty To or an invalid Actor with ErrInvalidActor, before anything is read. Whether To holds the node's eligibility is the caller's check, as with ClaimWith: the engine never resolves people. Like ClaimWith it never calls the EffectSink, so a node's entry effects do not run again, and a concurrent change to the case fails with ErrConflict and persists nothing.
func (*Engine) RecordFailure ¶ added in v0.18.0
RecordFailure appends a record of a rejected move to the case: an EventNoRoute for FailureNoRoute, an EventFailed for every other kind, with a FailureDetail carrying in.Kind and in.Detail. It never changes the case's state, assignment or Revision; it only takes the next Seq, through Repository.AdvanceLastSeq, which locks the case row, so it serializes with every other writer of the case.
The move that failed ran in a transaction the caller must roll back first: RecordFailure runs in the caller's next transaction (db), so the record survives the rollback. FailureKindOf maps the engine's sentinel errors to a FailureKind. An unknown kind, a Detail that is not a JSON object or an invalid Actor fails with ErrInvalidFailure or ErrInvalidActor, and a TokenID the case does not have with ErrTokenNotFound, before anything is written.
A failure recorded while another call holds a stale read of the same case advances LastSeq but not Revision; that call's Repository.Update compares the LastSeq it read too, so it fails with ErrConflict before writing anything, and it retries from a fresh read like any other concurrent change.
func (*Engine) RefreshEligibility ¶ added in v0.19.0
func (e *Engine) RefreshEligibility(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) (bool, error)
RefreshEligibility writes the resolved eligibility of every active token of caseID that is stored without one, and reports whether it wrote anything. Tokens migration 008 materialized have none (a node's eligibility lives in the Definition), so they do not match InboxFilter.Eligibility until their case is written again; calling RefreshEligibility once per open case after the migration closes that gap. It appends no event, and like every write it is a compare-and-swap on the case revision (ErrConflict on a concurrent change).
func (*Engine) Register ¶
func (e *Engine) Register(d Definition) error
Register validates d and stores it under d.Key(). It also registers d under its bare Name, pointing at the highest version registered so far, so callers can open a case without pinning a version. A definition naming an effect fails with ErrUnknownEffect when no EffectSink is set, or when the sink's HasEffect reports false for that name. A definition declaring a Node.DeadlineRule fails with ErrUnknownDeadlineRule when Config.Deadlines is nil, and one declaring a Node.AssignRule with ErrUnknownAssignRule when Config.Assignees is nil.
func (*Engine) RegisterGuard ¶
RegisterGuard registers fn under name. Overwriting an existing name is allowed but logged at Warn.
func (*Engine) Release ¶
func (e *Engine) Release(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID, actorID string) (*Case, error)
Release clears the case's assignment on behalf of actorID, a person: it is ReleaseWith with Actor{Kind: ActorHuman, ID: actorID} and no Reason, so it only releases actorID's own claim (ErrReasonRequired otherwise).
func (*Engine) ReleaseWith ¶ added in v0.18.0
ReleaseWith clears the token's assignment, recording the previous assignee and in.Reason in the event's AssignmentDetail. An invalid Actor fails with ErrInvalidActor before anything is read, a token nobody holds (or a case that is no longer open) with ErrNotAssigned, and a release of a token held by someone other than in.Actor.ID without a Reason with ErrReasonRequired. A concurrent change to the case fails with ErrConflict and persists nothing (see ClaimWith). Like ClaimWith, it never calls the EffectSink.
func (*Engine) SetDeadline ¶ added in v0.20.0
func (e *Engine) SetDeadline(ctx context.Context, db pgxtx.DBTX, in SetDeadlineInput) (*Case, error)
SetDeadline replaces the token's deadline with in.DeadlineAt (nil removes it) and appends an EventDeadlineChanged whose DeadlineDetail records the old and new deadline and the reason. It also clears the token's expired mark, so a token whose deadline was extended can expire again. An empty Reason fails with ErrReasonRequired and an invalid Actor with ErrInvalidActor, before anything is read; a case that is not open fails with ErrCaseClosed. It never calls the EffectSink, and a concurrent change to the case fails with ErrConflict and persists nothing.
func (*Engine) Tokens ¶ added in v0.19.0
Tokens returns every token of caseID — active, waiting, consumed and cancelled — ordered by EnteredSeq (oldest first), then ID.
func (*Engine) VerifyChain ¶ added in v0.18.0
VerifyChain checks caseID's hash chain: every chained event's digest must match its current content, and its PrevDigest must be the Digest of the event before it (nil after an unchained event, or for the first event). Unchained events before the first chained one, those stored before the repository chained events, are accepted as they are; an unchained event after it is not. It returns nil for an intact chain, a *ChainBrokenError (matching ErrChainBroken) for the first event that fails, and ErrCaseNotFound for an unknown case.
The chain detects a stored event that was changed, removed or reordered without recomputing every digest after it. It cannot detect a rewrite that recomputes them, events removed from the end of the case, nor a rewrite that clears prev_digest and digest on every event of the case: VerifyChain cannot tell that from a case whose events all predate the chain, and accepts it. Comparing a Digest kept outside the database (an export, a signed log) is what detects them.
type Event ¶
type Event struct {
ID uuid.UUID
CaseID uuid.UUID
// Seq is the case-scoped, gap-free, strictly increasing sequence number
// that orders a case's events — the sole ordering key. Every event
// appended by one Engine.Move call (the human-driven hop, each
// automatic decision-node hop after it, and any automatic EventClosed)
// shares the exact same OccurredAt timestamp (see Engine.appendEvent),
// so a caller must never sort by OccurredAt to recover hop order within
// one Move; Seq, assigned in append order from Case.LastSeq, is what
// makes that order recoverable. workflow/postgres.ListEvents orders its
// query by `seq ASC` for exactly this reason (see repository.go).
Seq int64
Kind EventKind
// TokenID and ScopeID name the token the event concerns and that token's
// scope (see EventSplit and EventJoined for the two kinds that differ).
// Events stored before tokens existed read as the case ID for both: the
// root token in the root scope.
TokenID uuid.UUID
ScopeID uuid.UUID
FromState string
ToState string
Action string
// DeadlineAt is the deadline the token got on coming to rest at ToState
// (Node.Deadline or Node.DeadlineRule), so replaying the events rebuilds
// it. Only an EventOpened or EventMoved that leaves the token at a task
// node carries one, and only when that node declares a deadline; every
// other event, and events written before schema 4, have nil.
DeadlineAt *time.Time
// Actor is who performed the action. Events written before actors had
// a kind read as Actor{Kind: ActorUnspecified, ID: ActorID}.
Actor Actor
// ActorID mirrors Actor.ID.
//
// Deprecated: use Actor.ID.
ActorID string
// Tenant is the case's Tenant, copied on every append so an export or a
// row-level security policy never needs a join.
Tenant string
// Comment is the (already trimmed) comment or observation recorded
// alongside this event, when the taken transition's CommentPolicy
// allowed one. It is always empty on the automatic EventClosed event
// Move appends when entering a terminal node — the comment belongs to
// the EventMoved record for that same transition, not to its close
// side effect, so it is never duplicated there.
Comment string
OccurredAt time.Time
// SchemaVersion is the shape the event was written with. The engine
// writes CurrentEventSchema; rows stored before the column existed read
// as 1 (a repository that does not store it returns 0, read as 1 too).
// Engine reads fill the defaults of older versions and fail with
// ErrUnsupportedEventSchema for a version newer than this binary knows.
SchemaVersion int
// Detail is the kind-specific detail as a JSON object, `{}` for kinds
// that carry none. Each kind that uses it has its own Go type
// (AssignmentDetail). Like the rest of the event it holds references and
// digests only, never domain data.
Detail json.RawMessage
// RequestID is the request/correlation ID of the call that appended the
// event (reqctx.RequestIDFromContext), empty when there was none.
RequestID string
// TraceID and SpanID identify the span active when the event was
// appended, as returned by Config.TraceIDs; empty without that port or
// without a span.
TraceID string
SpanID string
// PrevDigest and Digest are the event's link in its case's hash chain,
// set by the repository on append: Digest is SHA-256 over PrevDigest
// and every stored field of the event, and PrevDigest is the Digest of
// the event at Seq-1. PrevDigest is nil for the first chained event of
// a case; both are nil for events stored before the repository chained
// them (migration 007 in workflow/postgres; migration 010 makes the
// digest v2, which also covers TokenID, ScopeID and DeadlineAt). See
// Engine.VerifyChain.
PrevDigest []byte
Digest []byte
}
Event is a single append-only history record for a Case.
type EventDigest ¶ added in v0.18.0
EventDigest is one link of a case's hash chain as the repository holds it: the stored PrevDigest and Digest of the event at Seq, and Recomputed, the digest the repository computes again from the row's current content and its stored PrevDigest (nil when Digest is nil). Engine.VerifyChain walks them.
type EventKind ¶
type EventKind string
EventKind identifies the kind of change an Event records.
const ( EventOpened EventKind = "opened" EventMoved EventKind = "moved" EventAssigned EventKind = "assigned" EventUnassigned EventKind = "unassigned" EventClosed EventKind = "closed" // EventStepSubmitted records the form submission a Move carried // (MoveInput.Step), immediately before that Move's human EventMoved. Its // Detail is a StepDetail. EventStepSubmitted EventKind = "step_submitted" // EventNoRoute and EventFailed record a rejected move (see // Engine.RecordFailure): EventNoRoute when no decision route matched, // EventFailed for every other FailureKind. Neither changes the case. The // Detail is a FailureDetail. EventNoRoute EventKind = "no_route" EventFailed EventKind = "failed" // EventSplit records a split consuming the arriving token (TokenID, in // its ScopeID) and opening a scope; the Detail is a SplitDetail. The // emitted tokens' EventMoved hops follow it. EventSplit EventKind = "split" // EventWaiting records a token arriving at its scope's join. EventWaiting EventKind = "waiting" // EventJoined records a join consuming its scope's waiting tokens. Its // ScopeID is the scope that joined and its TokenID the token the join // creates in the parent scope; the Detail is a JoinDetail. EventJoined EventKind = "joined" // EventTokenCancelled records one token cancelled by Engine.Cancel, // Engine.CancelToken or a join policy closing its round early; the Detail // is a CancelDetail. EventTokenCancelled EventKind = "token_cancelled" // EventCancelled records Engine.Cancel ending the case; the Detail is a // CancelDetail. It follows one EventTokenCancelled per live token, whose // FromState is the node that branch was at: while the case ran in // parallel its own FromState/ToState are empty (Case.State), so the // branches' positions are read from those events. EventCancelled EventKind = "cancelled" // EventDeadlineChanged records Engine.SetDeadline replacing a token's // deadline; the Detail is a DeadlineDetail. EventDeadlineChanged EventKind = "deadline_changed" // EventExpired records Engine.Expire marking a token's deadline as // passed; the Detail is an ExpiryDetail. EventExpired EventKind = "expired" )
type ExpireInput ¶ added in v0.20.0
ExpireInput describes the expiry of one overdue token. TokenID works like ClaimInput.TokenID. Actor must be an ActorSystem: expiry is the consumer's scheduler's job, never a person's.
type ExpiryDetail ¶ added in v0.20.0
ExpiryDetail is the Event.Detail of EventExpired: the deadline that expired.
type FailureDetail ¶ added in v0.18.0
type FailureDetail struct {
Kind FailureKind `json:"kind"`
Detail json.RawMessage `json:"detail,omitempty"`
}
FailureDetail is the Event.Detail of EventNoRoute and EventFailed: the FailureKind and the caller's own detail object (FailureInput.Detail), omitted when empty. Like every detail it holds references, never domain data.
type FailureInput ¶ added in v0.18.0
type FailureInput struct {
CaseID uuid.UUID
// TokenID names the token whose move failed, so the record lands in its
// branch; zero records it at the case level (the root token).
TokenID uuid.UUID
Actor Actor
Action string
Kind FailureKind
Detail json.RawMessage
}
FailureInput describes a rejected move to record (see RecordFailure).
type FailureKind ¶ added in v0.18.0
type FailureKind string
FailureKind classifies a rejected move recorded with Engine.RecordFailure.
const ( FailureNoRoute FailureKind = "no_route" FailureGuardRejected FailureKind = "guard_rejected" FailureConflict FailureKind = "conflict" FailureValidationFailed FailureKind = "validation_failed" FailureCommentRejected FailureKind = "comment_rejected" FailureReturnNotVisited FailureKind = "return_not_visited" FailureTransitionNotFound FailureKind = "transition_not_found" )
func FailureKindOf ¶ added in v0.18.0
func FailureKindOf(err error) (FailureKind, bool)
FailureKindOf reports the FailureKind for err when it wraps one of the engine's rejected-move sentinels (ErrNoRoute, ErrGuardRejected, ErrConflict, ErrInvalidActor, ErrCommentRequired, ErrCommentNotAllowed, ErrReturnNotVisited, ErrInvalidTransition), and false for any other error, such as ErrCaseClosed or a database failure, which RecordFailure is not meant to record.
func (FailureKind) Valid ¶ added in v0.18.0
func (k FailureKind) Valid() bool
Valid reports whether k is one of the known FailureKind values.
type GuardFunc ¶
GuardFunc evaluates whether a transition may be taken for the given case. An error aborts the caller's operation rather than being treated as false.
db is the exact value the caller passed to Engine.Available or Engine.Move — never a different connection, and never nil unless the caller itself passed nil. A guard that reads domain data (e.g. "does this purchase have an item with subsidy SEP?") must see writes made earlier in the caller's own transaction — for example a row the caller inserted just before calling Move — so the engine hands the guard the same db rather than opening a separate connection or using its own pool.
Because db is shared with the caller's own transaction, a guard MUST return (never swallow) any database error it encounters, and MUST fully close any pgx.Rows it opens — via Rows.Close, not merely draining Next to false — before returning. A failed statement that is not reported leaves the transaction poisoned (PostgreSQL SQLSTATE 25P02, "current transaction is aborted"), and rows left open hold the underlying connection busy; either failure then breaks the engine's own writes later in the same call to Move.
A guard also runs while that transaction, and its pool connection, are open: it must not call the network (an HTTP API, Cerbos, object storage, email). A slow or hanging remote call would hold the connection and the transaction's row locks for as long as it takes. Decide anything that needs a remote call before opening the transaction and pass the result in through the Case or the context.
type InboxFilter ¶
type InboxFilter struct {
Tenant string // empty = any
Domain string
States []string
Eligibility []Eligibility
AssignedTo string // empty = any
Unassigned bool // true = only unclaimed
Overdue bool // true = only past Token.DeadlineAt
Limit int // <= 0 means DefaultListLimit; clamped to MaxListLimit
Offset int // must be within [0, MaxListOffset]
}
InboxFilter selects the active tokens of open cases (see Engine.Inbox). States is the set of node IDs a caller considers itself eligible for, and Eligibility the set of (position, unit) pairs it holds: a token matches when its node is in States (when set) and its resolved Token.Eligible equals one of the pairs (when set). AssignedTo, Unassigned and Overdue apply to the token, not the case.
func (InboxFilter) Page ¶ added in v0.9.0
func (f InboxFilter) Page() (limit, offset int, err error)
Page returns the LIMIT and OFFSET a repository list query must use for f: see DefaultListLimit, MaxListLimit and MaxListOffset.
type JoinBranch ¶ added in v0.23.0
type JoinBranch struct {
BranchResult
Actor Actor
Comment string
Cause string
}
JoinBranch is one branch of a JoinResult: its BranchResult plus who acted, read from the event at Seq. On an unanswered branch the actor is whoever's call cancelled it. Cause says why the event happened on its own: "expired" for a move Engine.Expire took, the CancelDetail reason for an unanswered branch, and empty for an ordinary answer.
type JoinDetail ¶ added in v0.19.0
type JoinDetail struct {
Scope uuid.UUID `json:"scope"`
JoinNode string `json:"join_node"`
Tokens []uuid.UUID `json:"tokens"`
Policy JoinPolicy `json:"policy,omitempty"`
Verdict Outcome `json:"verdict,omitempty"`
Branches []BranchResult `json:"branches,omitempty"`
}
JoinDetail is the Event.Detail of EventJoined: the scope that joined, its join node and the tokens the join consumed. A join with a policy adds the policy, the round's verdict (empty under JoinCollect) and every branch. No comment is copied here: it stays in its move event (see BranchResult.Seq).
type JoinPolicy ¶ added in v0.23.0
type JoinPolicy string
JoinPolicy declares how the branches of a parallel block decide at its join (Node.JoinPolicy). The zero value is no policy: the join waits for every branch and records no outcome, tally or verdict.
const ( // JoinAllApprove closes the round on the first rejection, with verdict // OutcomeRejected, or when every branch approved, with OutcomeApproved. A // rejection cancels the branches still pending. JoinAllApprove JoinPolicy = "all_approve" // JoinAnyApprove closes the round on the first approval, with verdict // OutcomeApproved, cancelling the branches still pending, or when every // branch rejected, with OutcomeRejected. JoinAnyApprove JoinPolicy = "any_approve" // JoinCollect closes the round when every branch answered, with no // verdict: a person reads the tally on the task after the join and decides. JoinCollect JoinPolicy = "collect" )
func (JoinPolicy) Valid ¶ added in v0.23.0
func (p JoinPolicy) Valid() bool
Valid reports whether p is empty or one of the known policies.
type JoinRecord ¶ added in v0.19.0
type JoinRecord struct {
Scope Scope
Tokens []Token
Verdict Outcome
Branches []BranchResult
}
JoinRecord describes one join a call fired: the scope as joined and the tokens it consumed (see Config.JoinCheck and MoveResult.Joined). Under a policy it also carries the round's verdict (empty under JoinCollect) and every branch, so a JoinCheck can skip merging the data of a rejected round.
type JoinResult ¶ added in v0.23.0
type JoinResult struct {
Scope uuid.UUID
JoinNode string
Policy JoinPolicy
Verdict Outcome
Seq int64
Branches []JoinBranch
}
JoinResult is one closed round of a join with a policy: which join, under what policy, its verdict (empty under JoinCollect), the Seq of its EventJoined and every branch, oldest answer first.
Engine.JoinResults returns it with each branch's actor, comment and cause. The Case.JoinResult a guard receives while routing carries only the BranchResult of each branch, because the votes of earlier calls live in events that call has not read.
func (JoinResult) Count ¶ added in v0.23.0
func (r JoinResult) Count(outcome Outcome) int
Count returns how many branches of the round reported outcome.
type MoveInput ¶
type MoveInput struct {
CaseID uuid.UUID
// TokenID names the token to move. The zero value means the case's only
// active token: with several active tokens Move fails with
// ErrTokenRequired, and a token not active in the case fails with
// ErrTokenNotFound.
TokenID uuid.UUID
Action string
// Actor is who performs the move. Every event the move appends records
// it.
Actor Actor
// ActorID is the deprecated alias of Actor (see OpenInput.ActorID).
//
// Deprecated: use Actor.
ActorID string
// Comment is the step comment (on approval) or observation (on
// rejection) attached to this move. It is trimmed with strings.
// TrimSpace, then validated against the taken transition's
// CommentPolicy before any state change: empty after trimming on a
// CommentRequired transition fails with ErrCommentRequired, and
// non-empty on a CommentNone transition fails with
// ErrCommentNotAllowed. It is stored as-is (trimmed) on the resulting
// EventMoved record.
Comment string
// Step, when set, is the form submission this move carries: Move appends
// an EventStepSubmitted with it as detail immediately before the human
// EventMoved, in the same seq block. Nil appends no step event.
Step *StepRecord
// ExpectedRevision, when set, is the Case.Revision the caller's view of
// the case was read at. The call fails with ErrConflict when the stored
// revision differs, checked right after the case is read and before any
// check of its state or any write, so an offline or long-form client
// detects a stale view without reading the case again. Nil skips the
// check (the compare-and-swap on write still applies).
ExpectedRevision *int64
}
MoveInput describes a transition to apply to a case.
type MoveResult ¶ added in v0.18.0
type MoveResult struct {
Case *Case
Events []Event
Joined []JoinRecord
}
MoveResult is what OpenDetailed, MoveDetailed and CancelToken return: the case as persisted, exactly the events the call appended, in Seq order, and every join the call fired, in the order they fired.
type Node ¶
type Node struct {
ID string
Start bool
Terminal bool
Eligible Eligibility
// Deadline is the duration after entering this node before it is
// considered overdue. Zero means no deadline.
Deadline time.Duration
// DeadlineRule names a rule the Engine's Config.Deadlines resolves to the
// deadline of a token entering this node, for deadlines a fixed duration
// cannot express (business days, a holiday calendar). It excludes
// Deadline (Definition.Validate rejects both set), and Engine.Register
// rejects it when no resolver is configured (ErrUnknownDeadlineRule).
// On a terminal node it is ignored, like Deadline.
DeadlineRule string
// Kind distinguishes an ordinary task node from a decision node. The
// zero value is NodeTask. See the NodeKind doc comment.
Kind NodeKind
// Effects names the declarative effects to run when a case enters this
// node (EventOpened or EventMoved with ToState == ID). The engine never
// executes an effect: it only hands the events it appended to the
// Engine's EffectSink, which decides what each name means and runs it
// asynchronously, outside the request that advanced the case. Every name
// must be known to that sink (see Engine.Register and ErrUnknownEffect).
// Definition.Validate rejects an empty or duplicate name within one
// node, and any effect on a decision node, split or join: a case never
// rests there.
Effects []string
// Join names the NodeJoin where the branches of this split meet. Only a
// NodeParallel or NodeInclusive node may set it, and each join is named by
// exactly one split: together they bound a block (see Definition.Validate).
Join string
// OnExpire names the Action of one of this node's outgoing transitions:
// Engine.Expire moves an overdue token through it, as the system actor.
// Empty leaves an expired token where it is. Definition.Validate rejects
// a name that is not an outgoing transition, a return transition, and
// OnExpire on a decision node, split or join.
OnExpire string
// JoinPolicy declares how the branches of this join decide. Only a NodeJoin
// named by a NodeParallel may set it. Empty keeps the plain join: it waits
// for every branch and records no outcome.
JoinPolicy JoinPolicy
// AssignRule names a rule the Engine's Config.Assignees resolves to the
// person a token coming to rest on this node goes to, on every path into it
// (Move, splits, joins, return transitions, Expire) except Engine.Open.
// vogel never interprets the name, so no person ID enters the Definition.
// Empty keeps the default: the token goes to the node's pool. Definition.
// Validate rejects it on a decision node, split, join or terminal node, where
// no token ever rests, and Engine.Register rejects it when no resolver is
// configured (ErrUnknownAssignRule).
AssignRule string
}
Node is one state a Case can occupy within a Definition.
type NodeKind ¶ added in v0.6.0
type NodeKind string
NodeKind distinguishes a Node that rests on human action (NodeTask, the default) from one that routes automatically on domain data evaluated by its outgoing transitions' guards (NodeDecision) — a BPMN-style exclusive gateway. A Case is never persisted resting on a NodeDecision: Engine.Move keeps routing through it, within the same call, until it reaches a NodeTask or terminal node.
const ( // NodeTask is the default: a node a Case can rest on between human // actions, exactly like every Node before decision nodes existed. Both // the zero value "" and the explicit literal "task" mean NodeTask, so a // Definition can spell out "this is an ordinary node" without relying on // the zero value. NodeTask NodeKind = "" // NodeDecision marks a decision node: see the NodeKind doc comment. NodeDecision NodeKind = "decision" // NodeParallel is an AND split: a token arriving at it is consumed and one // new token leaves through every outgoing transition, none of which may // have a guard. Node.Join names the NodeJoin where the branches meet. NodeParallel NodeKind = "parallel" // NodeInclusive is an OR split: one new token leaves through every // outgoing route whose guard passes. Exactly one unguarded default route, // declared last, is taken only when no guarded route passes. Node.Join // names the NodeJoin where the branches meet. NodeInclusive NodeKind = "inclusive" // NodeJoin is where the branches of the split naming it meet: it waits // until every token that split emitted arrived (or was cancelled), or until // its Node.JoinPolicy closes the round, then one token continues through // its single, unguarded outgoing transition. NodeJoin NodeKind = "join" )
func (NodeKind) IsAutomatic ¶ added in v0.19.0
IsAutomatic reports whether a case never rests on a node of kind k: a decision node, a split or a join. Engine.Move routes through them within the same call.
type OpenInput ¶
type OpenInput struct {
Definition string
Version int // 0 = latest registered version
Domain string
ExternalID string
Unit string
// Tenant scopes the case (see Case.Tenant).
Tenant string
// Actor is who opens the case.
Actor Actor
// ActorID is the deprecated alias of Actor: with Actor.ID empty it means
// Actor{Kind: ActorHuman, ID: ActorID}; set to a different ID than
// Actor.ID it fails the call with ErrInvalidActor.
//
// Deprecated: use Actor.
ActorID string
}
OpenInput describes a new case to open.
type Option ¶
type Option func(*Engine)
Option configures optional Engine behaviour at construction time.
func WithDefinitions ¶
func WithDefinitions(defs ...Definition) Option
WithDefinitions registers defs at construction time, after every other option has been applied. It is a convenience over calling Register after New; a definition that fails validation (or names an unknown effect) is logged and skipped rather than aborting construction, since Option has no error return.
func WithEffectSink ¶ added in v0.14.0
func WithEffectSink(s EffectSink) Option
WithEffectSink sets the EffectSink that validates effect names at Register time and receives the events Open and Move append. Without one, Register rejects any definition that declares an effect, and nothing is dispatched. It may appear before or after WithDefinitions.
type Outcome ¶ added in v0.23.0
type Outcome string
Outcome is what one branch of a policy join decided (Transition.Outcome, Token.Outcome), and the verdict of a round.
const ( // OutcomeApproved is an approval. OutcomeApproved Outcome = "approved" // OutcomeRejected is a rejection. OutcomeRejected Outcome = "rejected" // OutcomeUnanswered is a branch cancelled before it answered. Only a tally // reports it (BranchResult): a Transition cannot declare it. OutcomeUnanswered Outcome = "unanswered" )
type OverdueCursor ¶ added in v0.21.0
OverdueCursor marks a position in Overdue's order: a token's deadline and its ID. Build it with WorkItem.OverdueCursor from an item Overdue listed: a database may store deadlines with less precision than time.Time (Postgres keeps microseconds), so a hand-built cursor can land between stored values.
type OverdueFilter ¶ added in v0.20.0
type OverdueFilter struct {
Tenant string // empty = any
// Limit is the page size: <= 0 means DefaultListLimit; clamped to
// MaxListLimit.
Limit int
// Before lists tokens whose deadline is strictly before it; the zero
// value means Config.Now at call time.
Before time.Time
// After, when set, lists only the tokens that come after it in Overdue's
// order (deadline, then token ID): pass the OverdueCursor of the last
// item of the previous page. nil starts from the oldest deadline.
After *OverdueCursor
}
OverdueFilter selects the overdue tokens Engine.Overdue lists.
func (OverdueFilter) Page ¶ added in v0.20.0
func (f OverdueFilter) Page() int
Page returns the LIMIT a repository query must use for f (see InboxFilter.Page); Overdue pages with After, not with an offset.
type ParticipationFilter ¶ added in v0.18.0
type ParticipationFilter struct {
Tenant string // empty = any
ActorID string
Limit int // <= 0 means DefaultListLimit; clamped to MaxListLimit
Offset int // must be within [0, MaxListOffset]
}
ParticipationFilter selects the cases an actor took part in (see Engine.Participated). ActorID is required; Tenant, when set, restricts the result to that tenant's cases. Like InboxFilter.Tenant, an empty Tenant means every tenant, so a multi-tenant consumer must always set it.
func (ParticipationFilter) Page ¶ added in v0.18.0
func (f ParticipationFilter) Page() (limit, offset int, err error)
Page returns the LIMIT and OFFSET for f, with the same rules as InboxFilter.Page.
type ReassignInput ¶ added in v0.20.0
type ReassignInput struct {
CaseID uuid.UUID
TokenID uuid.UUID
// To is the new assignee's person id; it is required.
To string
Actor Actor
// Reason is required: Reassign fails with ErrReasonRequired when it is
// empty after trimming. It is recorded trimmed.
Reason string
// ExpectedRevision works like MoveInput.ExpectedRevision.
ExpectedRevision *int64
}
ReassignInput describes an administrative reassignment: Actor moves the token to To, a person id, for Reason. TokenID works like ClaimInput.TokenID.
type ReleaseInput ¶ added in v0.18.0
type ReleaseInput struct {
CaseID uuid.UUID
TokenID uuid.UUID
Actor Actor
// Reason is the caller's free-text reason, recorded in the event's
// AssignmentDetail. It is required (ErrReasonRequired when empty after
// trimming) when Actor.ID is not the token's assignee, and optional for a
// self-release.
Reason string
// ExpectedRevision works like MoveInput.ExpectedRevision.
ExpectedRevision *int64
}
ReleaseInput describes a release: Actor clears the token's assignment, for Reason. An empty Actor.Kind means ActorHuman. TokenID works like ClaimInput.TokenID.
type Repository ¶
type Repository interface {
Create(ctx context.Context, db pgxtx.DBTX, c *Case) error
GetByID(ctx context.Context, db pgxtx.DBTX, id uuid.UUID) (*Case, error)
GetByExternalID(ctx context.Context, db pgxtx.DBTX, tenant, domain, externalID string) (*Case, error)
Update(ctx context.Context, db pgxtx.DBTX, c *Case, expectedLastSeq int64) error
AppendEvent(ctx context.Context, db pgxtx.DBTX, e *Event) error
ListEvents(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]Event, error)
ListWorkItems(ctx context.Context, db pgxtx.DBTX, f InboxFilter) ([]WorkItem, error)
ListOverdue(ctx context.Context, db pgxtx.DBTX, f OverdueFilter) ([]WorkItem, error)
AdvanceLastSeq(ctx context.Context, db pgxtx.DBTX, id uuid.UUID) (*Case, error)
ListParticipated(ctx context.Context, db pgxtx.DBTX, f ParticipationFilter) ([]Case, error)
ListEventDigests(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]EventDigest, error)
CreateScope(ctx context.Context, db pgxtx.DBTX, s *Scope) error
UpdateScope(ctx context.Context, db pgxtx.DBTX, s *Scope) error
ListScopes(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]Scope, error)
CreateToken(ctx context.Context, db pgxtx.DBTX, t *Token) error
UpdateToken(ctx context.Context, db pgxtx.DBTX, t *Token) error
ListTokens(ctx context.Context, db pgxtx.DBTX, caseID uuid.UUID) ([]Token, error)
}
Repository defines persistence operations for cases and their event history. See workflow/postgres for the PostgreSQL-backed implementation.
Create must persist Revision as 0 and leave c.Revision at 0. Update is a compare-and-swap on Revision and on LastSeq: it writes only when the stored revision equals c.Revision and the stored LastSeq equals expectedLastSeq (the value the caller read, before it advanced c.LastSeq for the events it is about to append), and on success advances both the stored row and c.Revision by one. It returns ErrCaseNotFound when no case has c.ID, and ErrConflict when the case exists but its revision or its LastSeq moved on (a concurrent write, or a RecordFailure, won); in both cases nothing is written. Create and Update persist c.LastSeq as given.
AppendEvent stores e exactly as given, Seq included: the engine assigns Seq from Case.LastSeq, and a Seq already taken for the case must fail rather than be moved. An empty Detail is stored and read back as `{}`. ListEvents returns SchemaVersion as stored; the engine upcasts it. A taken Seq fails with ErrConflict.
AdvanceLastSeq increments the case's LastSeq alone, leaving Revision and every other field as they are, and returns the updated case; it must lock the case row (serialize with Update) and fail with ErrCaseNotFound for a missing case. RecordFailure takes its Seq with it.
AppendEvent also chains the event: it sets e.PrevDigest to the Digest of the case's event at e.Seq-1 (nil when there is none, or when that event is unchained) and e.Digest to the digest of e over PrevDigest, so the caller gets the event as stored. ListEvents returns both as stored. ListEventDigests returns the case's chain links in Seq order, each with the digest recomputed from the row as it is now.
Tokens and scopes are mutable state of a case. The engine writes them only after Update's compare-and-swap succeeded in the same transaction, so the case revision serializes them and they need no revision of their own. CreateScope and CreateToken insert a new row; UpdateScope and UpdateToken write every mutable field of an existing one (ErrConflict when it does not exist). ListScopes and ListTokens return every row of the case, tokens ordered by EnteredSeq, then ID. Event.TokenID and Event.ScopeID are stored as given; a repository that stores no value for them (uuid.Nil) reads them back as uuid.Nil, which the engine reads as the case ID.
ListWorkItems returns one WorkItem per active token of an open case that matches f, oldest case first (OpenedAt, then case ID), then the case's tokens by EnteredSeq, then token ID, paged by f.Page.
ListOverdue returns one WorkItem per active token of an open case (of f.Tenant when set) whose DeadlineAt is before f.Before and whose ExpiredDeadline is not that same deadline, ordered by DeadlineAt, then token ID, after f.After when it is set (strictly greater (DeadlineAt, ID)), at most f.Page() of them. UpdateToken and CreateToken persist Token.ExpiredDeadline like every other field.
type Scope ¶ added in v0.19.0
type Scope struct {
ID uuid.UUID
CaseID uuid.UUID
ParentID *uuid.UUID
// SplitNode and JoinNode are the block's split and join; empty for the
// root scope.
SplitNode string
JoinNode string
// Expected is how many tokens the split emitted: the join fires when
// waiting plus cancelled tokens reach it, or earlier when its join policy
// closes the round.
Expected int
Status ScopeStatus
OpenedSeq int64
// ClosedSeq is the Seq of the event that joined, cancelled or closed the
// scope; 0 while it is open.
ClosedSeq int64
}
Scope groups the tokens one split emitted until its join consumes them. Every case has a root scope whose ID equals the case ID (ParentID nil, no split or join node, Expected 1); each split opens a child scope of the arriving token's scope.
type ScopeStatus ¶ added in v0.19.0
type ScopeStatus string
ScopeStatus is the lifecycle state of a Scope.
const ( ScopeOpen ScopeStatus = "open" ScopeJoined ScopeStatus = "joined" ScopeCancelled ScopeStatus = "cancelled" // ScopeClosed is the status of a case's root scope once the case closed. ScopeClosed ScopeStatus = "closed" )
type SetDeadlineInput ¶ added in v0.20.0
type SetDeadlineInput struct {
CaseID uuid.UUID
TokenID uuid.UUID
// DeadlineAt is the new deadline; nil removes it.
DeadlineAt *time.Time
Actor Actor
// Reason is required: SetDeadline fails with ErrReasonRequired when it is
// empty after trimming. It is recorded trimmed.
Reason string
// ExpectedRevision works like MoveInput.ExpectedRevision.
ExpectedRevision *int64
}
SetDeadlineInput describes a deadline change on one token. TokenID works like ClaimInput.TokenID.
type SplitDetail ¶ added in v0.19.0
type SplitDetail struct {
Scope uuid.UUID `json:"scope"`
SplitNode string `json:"split_node"`
Tokens []uuid.UUID `json:"tokens"`
}
SplitDetail is the Event.Detail of EventSplit: the scope the split opened, the split node and the tokens it emitted, in branch order.
type StepDetail ¶ added in v0.18.0
type StepDetail = StepRecord
StepDetail is the Event.Detail of EventStepSubmitted: the StepRecord the Move carried.
type StepRecord ¶ added in v0.18.0
type StepRecord struct {
StepID string `json:"step_id"`
FormVersion int `json:"form_version"`
PayloadDigest string `json:"payload_digest"`
}
StepRecord references the form submission a Move carries: which step (StepID) and form version the caller collected, and a digest of the submitted payload. The engine never sees the payload itself, only this reference, so the "zero domain data" rule holds.
type Token ¶ added in v0.19.0
type Token struct {
ID uuid.UUID
CaseID uuid.UUID
ScopeID uuid.UUID
// Node is the node the token rests on (TokenActive), waits at (a join,
// TokenWaiting), or last occupied (TokenConsumed, TokenCancelled).
Node string
Status TokenStatus
// Eligible is Node's eligibility with ResolveUnit already applied
// against the case's unit, stored so an inbox can filter by it.
Eligible Eligibility
AssignedTo string
// DeadlineAt is Node.Deadline applied when the token entered Node, or the
// deadline Engine.SetDeadline set since.
DeadlineAt *time.Time
// ExpiredDeadline is the deadline Engine.Expire recorded as expired. The
// token counts as expired while it equals DeadlineAt; entering a node and
// Engine.SetDeadline clear it.
ExpiredDeadline *time.Time
// EnteredSeq and EnteredAt are the Seq and time of the event that moved
// the token onto Node.
EnteredSeq int64
EnteredAt time.Time
// EndedSeq and EndedAt are set when the token stops being live
// (consumed or cancelled); EndedSeq is 0 and EndedAt nil before.
EndedSeq int64
EndedAt *time.Time
// Outcome is what the token answered on entering a join with a policy (the
// taken Transition.Outcome); empty on any other token.
Outcome Outcome
}
Token is one thread of execution inside a case: the unit a person claims, works on and submits (a work item). A case that never split has exactly one token, whose ID equals the case ID; a split consumes the arriving token and emits one token per taken branch, and a join consumes the branches' tokens and emits one token in the enclosing scope. A token keeps its ID while it moves from node to node inside its scope.
Tokens are mutable state, like Case: the history of how they got there is the case's events, each of which names its Event.TokenID and Event.ScopeID.
type TokenStatus ¶ added in v0.19.0
type TokenStatus string
TokenStatus is the lifecycle state of a Token.
const ( // TokenActive rests on a task node, waiting for a human action. TokenActive TokenStatus = "active" // TokenWaiting arrived at its scope's join and waits for its siblings. TokenWaiting TokenStatus = "waiting" // TokenConsumed left the case: a split or a join consumed it, or it // reached a terminal node. TokenConsumed TokenStatus = "consumed" // TokenCancelled was cancelled (Engine.Cancel, Engine.CancelToken, or a // join policy closing its round early). TokenCancelled TokenStatus = "cancelled" )
func (TokenStatus) Live ¶ added in v0.19.0
func (s TokenStatus) Live() bool
Live reports whether a token in status s still counts as a branch of its scope: TokenActive or TokenWaiting.
type Transition ¶
type Transition struct {
From string
To string
Action string
// Guard names a GuardFunc registered on the Engine. Empty means the
// transition (or, from a decision node, the route) is always permitted —
// for a decision node's routes, this is what marks the default.
Guard string
// Comment declares this transition's CommentPolicy: whether MoveInput.
// Comment is required, optional, or disallowed when this transition is
// taken. The zero value is CommentNone. Definition.Validate rejects an
// unrecognized value, and rejects any non-CommentNone value on a
// transition leaving a decision node, a split or a join — the engine
// takes those on its own, not as a human action, so there is nothing to
// comment on.
Comment CommentPolicy
// Return marks this transition as a return to an earlier task node the
// case already occupied (a bureaucratic sign-off sending a case back to
// a stage it already passed through, for example). Engine.Available
// offers it, and Engine.Move accepts it, ONLY if the case previously
// occupied To — determined from the case's own event history, never
// merely because To is reachable in the Definition's graph — so a
// return is never offered (and never accepted) for a node the case
// happened to skip. A return whose To the case never occupied fails
// Move with ErrReturnNotVisited, without mutating the case or
// appending any event. Return combines with Guard (both must pass) and
// with Comment (a return will typically be CommentRequired, so the
// rejection's reason is recorded) exactly like any ordinary
// transition; see Engine.Move's doc comment for the exact check
// ordering. Definition.Validate rejects a return transition that
// originates from a decision node (a route routes automatically on
// domain data; a return is a human action), that targets a terminal
// node, or that targets a decision node: a case never rests on a
// decision node, so a return into one would silently resume automatic
// routing and could push the case forward instead of back.
Return bool
// Effects names the declarative effects to run when this transition —
// or, from a decision node, this route — is taken. Like Node.Effects,
// the engine never executes them; it only passes the EventMoved it
// appended to the Engine's EffectSink. Definition.Validate rejects an
// empty or duplicate name within one transition.
Effects []string
// Outcome is the decision this transition records when it enters a join
// with a policy: OutcomeApproved or OutcomeRejected. Definition.Validate
// requires it on every transition entering such a join, which must leave a
// task node, and rejects it on any other transition. Under JoinAllApprove
// and JoinAnyApprove a rejected transition must have Comment: CommentRequired.
Outcome Outcome
}
Transition is a named move from one node to another, optionally gated by a registered guard. When From is a decision node, a Transition is instead called a route: routes are evaluated in declaration order by Engine.Move, and Definition.Validate requires exactly one unguarded route (the default), declared last.
type WaitingDetail ¶ added in v0.23.0
type WaitingDetail struct {
Outcome Outcome `json:"outcome,omitempty"`
}
WaitingDetail is the Event.Detail of the EventWaiting of a token entering a join with a policy: what it answered. Any other EventWaiting carries `{}`.
type WorkItem ¶ added in v0.19.0
WorkItem is one Inbox row: an active token and the case it belongs to.
func (*WorkItem) OverdueCursor ¶ added in v0.21.0
func (w *WorkItem) OverdueCursor() *OverdueCursor
OverdueCursor returns the cursor that resumes Overdue right after w, or nil when w is nil or its token has no deadline.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package calendar computes business-calendar deadlines for vogel/workflow: "N business days" counted in an explicit time zone, skipping weekends and the holidays a consumer supplies.
|
Package calendar computes business-calendar deadlines for vogel/workflow: "N business days" counted in an explicit time zone, skipping weekends and the holidays a consumer supplies. |
|
Package migrations embeds the SQL migration(s) that create the workflow_case and workflow_event tables this library owns.
|
Package migrations embeds the SQL migration(s) that create the workflow_case and workflow_event tables this library owns. |
|
Package postgres provides the PostgreSQL-backed implementation of the workflow.Repository port, built on native pgx.
|
Package postgres provides the PostgreSQL-backed implementation of the workflow.Repository port, built on native pgx. |
|
Package workflowhttp maps the errors of vogel/workflow to HTTP status codes and the error codes of vogel/httpx/response.
|
Package workflowhttp maps the errors of vogel/workflow to HTTP status codes and the error codes of vogel/httpx/response. |