Documentation
¶
Overview ¶
Package approvals runs multi-step approval workflows for SaaS applications, such as an expense approved by a manager and then by finance.
Workflows are defined in code and registered with an Engine by key. Each workflow is an ordered list of steps; a step names its approvers (explicit actor IDs, roles resolved by the application's ApproverResolver, or both) and a rule: RuleAny, RuleAll or RuleQuorum. A step may carry a deadline, after which the request expires. Separation of duties is on by default: requesters cannot decide on their own requests unless the workflow sets AllowSelfApproval.
Submit creates a Request that stores a snapshot of the workflow's steps, so later code changes never alter requests already in flight. Approve and Reject record one Decision per actor per step; a rejection closes the request, and an approval advances it once the step's rule is satisfied. Cancel withdraws a request, PendingFor lists an actor's inbox across workflows, History returns the audit trail, and ExpireDue closes requests whose deadline passed.
Every state change is recorded as a Transition and passed to the configured hooks inside the same store transaction, so applications can enqueue notifications atomically; a hook error aborts the change. Decisions on one request are serialized by a row lock in the store.
The actor performing a call and the tenant it is scoped to travel in the context (WithActor, WithTenant). Storage is pluggable through Store: see the memstore and pgxstore subpackages, and storetest for the conformance suite third-party stores can run.
Example ¶
An expense is approved by the employee's manager, then by two members of the finance team within 48 hours.
package main
import (
"context"
"fmt"
"slices"
"time"
approvals "github.com/byteminus/go-approvals"
"github.com/byteminus/go-approvals/memstore"
)
func main() {
finance := approvals.ResolverFunc(func(_ context.Context, actor, role, tenant string) (bool, error) {
return role == "finance" && tenant == "acme" && slices.Contains([]string{"fay", "finn"}, actor), nil
})
notify := func(_ context.Context, t approvals.Transition, r approvals.Request) error {
// In production, enqueue a notification job here; it commits or
// rolls back with the transition.
fmt.Printf("hook: %s (step %d -> %d)\n", t.Kind, t.FromStep, t.ToStep)
return nil
}
engine, err := approvals.New(memstore.New(), approvals.Options{
Resolver: finance,
Hooks: []approvals.Hook{notify},
})
if err != nil {
panic(err)
}
err = engine.Register(approvals.Workflow{
Key: "expense",
Steps: []approvals.Step{
{Name: "manager", Approvers: []string{"maria"}, Rule: approvals.RuleAny},
{Name: "finance", Roles: []string{"finance"}, Rule: approvals.RuleQuorum, Quorum: 2, Deadline: 48 * time.Hour},
},
})
if err != nil {
panic(err)
}
as := func(actor string) context.Context {
return approvals.WithTenant(approvals.WithActor(context.Background(), actor), "acme")
}
req, err := engine.Submit(as("eve"), approvals.SubmitInput{
Workflow: "expense",
Subject: approvals.Ref{Type: "expense", ID: "exp_42"},
Payload: []byte(`{"amount": 125, "currency": "EUR"}`),
})
if err != nil {
panic(err)
}
inbox, _ := engine.PendingFor(as("maria"), "maria")
fmt.Println("maria's inbox:", len(inbox))
for _, actor := range []string{"maria", "fay", "finn"} {
req, err = engine.Approve(as(actor), req.ID, approvals.DecideInput{Comment: "ok"})
if err != nil {
panic(err)
}
fmt.Printf("%s approved: status %s, step %d\n", actor, req.Status, req.CurrentStep)
}
_, err = engine.Approve(as("eve"), req.ID, approvals.DecideInput{})
fmt.Println(err)
}
Output: hook: submitted (step 0 -> 0) maria's inbox: 1 hook: step_advanced (step 0 -> 1) maria approved: status pending, step 1 fay approved: status pending, step 1 hook: approved (step 1 -> 1) finn approved: status approved, step 1 approvals: request is not pending: status is approved
Index ¶
- Variables
- func ActorFrom(ctx context.Context) (string, bool)
- func TenantFrom(ctx context.Context) (string, bool)
- func WithActor(ctx context.Context, actor string) context.Context
- func WithTenant(ctx context.Context, tenantID string) context.Context
- type ApproverResolver
- type CancelAuthorizer
- type CancelAuthorizerFunc
- type DecideInput
- type Decision
- type Due
- type DueQuery
- type Engine
- func (e *Engine) Approve(ctx context.Context, id uuid.UUID, in DecideInput) (Request, error)
- func (e *Engine) Cancel(ctx context.Context, id uuid.UUID, reason string) (Request, error)
- func (e *Engine) ExpireDue(ctx context.Context) (int, error)
- func (e *Engine) Get(ctx context.Context, id uuid.UUID) (Request, error)
- func (e *Engine) History(ctx context.Context, id uuid.UUID) (History, error)
- func (e *Engine) PendingFor(ctx context.Context, actor string) ([]Request, error)
- func (e *Engine) Register(w Workflow) error
- func (e *Engine) Reject(ctx context.Context, id uuid.UUID, in DecideInput) (Request, error)
- func (e *Engine) Submit(ctx context.Context, in SubmitInput) (Request, error)
- type History
- type Hook
- type Options
- type Outcome
- type PendingQuery
- type Ref
- type Request
- type ResolverFunc
- type RoleQuery
- type Rule
- type Status
- type Step
- type Store
- type SubmitInput
- type TenantRole
- type Transition
- type TransitionKind
- type Workflow
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidWorkflow reports a workflow definition rejected by Register. ErrInvalidWorkflow = errors.New("approvals: invalid workflow") // ErrDuplicateWorkflow reports a second Register call with the same key. ErrDuplicateWorkflow = errors.New("approvals: workflow already registered") // ErrUnknownWorkflow reports a Submit for a key that was never registered. ErrUnknownWorkflow = errors.New("approvals: unknown workflow") // ErrInvalidInput reports a malformed argument, such as a missing subject. ErrInvalidInput = errors.New("approvals: invalid input") // ErrNoActor reports a call that needs an actor (see WithActor) without one. ErrNoActor = errors.New("approvals: no actor") // ErrUnsatisfiable reports a submission whose workflow could never // complete, typically because separation of duties excludes the only // eligible approver. ErrUnsatisfiable = errors.New("approvals: workflow cannot be satisfied for this requester") // ErrNotFound reports a request (or a request a record refers to) that // does not exist or belongs to another tenant. ErrNotFound = errors.New("approvals: request not found") // ErrNotPending reports an action on a request that is already closed. ErrNotPending = errors.New("approvals: request is not pending") // ErrNotEligible reports a decision by an actor who may not decide on the // current step. ErrNotEligible = errors.New("approvals: actor is not eligible") // ErrAlreadyDecided reports a second decision by the same actor on the // same step. ErrAlreadyDecided = errors.New("approvals: actor already decided on this step") // ErrStaleStep reports a decision aimed at a step that is no longer the // current one. ErrStaleStep = errors.New("approvals: request is no longer at that step") // ErrNotAuthorized reports a cancellation by an actor who may not cancel. ErrNotAuthorized = errors.New("approvals: actor is not authorized") // ErrDuplicate is returned by stores when a record's ID already exists. ErrDuplicate = errors.New("approvals: duplicate record") // ErrInvalidRecord is returned by stores when a record violates the // storage constraints. ErrInvalidRecord = errors.New("approvals: invalid record") )
Functions ¶
func ActorFrom ¶
ActorFrom returns the actor stored by WithActor. The boolean is false when none is set or it is empty.
func TenantFrom ¶
TenantFrom returns the tenant stored by WithTenant and whether one is set. An empty tenant ID set explicitly is still a scope.
func WithActor ¶
WithActor returns a copy of ctx carrying the ID of the actor performing engine calls: the requester for Submit and Cancel, the approver for Approve and Reject.
func WithTenant ¶
WithTenant returns a copy of ctx scoped to a tenant. Submit stamps new requests with it, and every read or decision only sees that tenant's requests. Without a tenant in the context the engine is unscoped, which suits single-tenant applications and back-office jobs.
Types ¶
type ApproverResolver ¶
type ApproverResolver interface {
HasRole(ctx context.Context, actor, role, tenantID string) (bool, error)
}
ApproverResolver answers role membership questions for the application. HasRole reports whether actor holds role within tenantID; tenantID is the request's tenant and is empty for requests submitted without one, which implementations typically treat as "any tenant" or "global".
type CancelAuthorizer ¶
type CancelAuthorizer interface {
CanCancel(ctx context.Context, actor string, r Request) (bool, error)
}
CancelAuthorizer lets the application allow actors other than the requester, such as administrators, to cancel a request. The requester may always cancel their own pending request.
type CancelAuthorizerFunc ¶
CancelAuthorizerFunc adapts a function to CancelAuthorizer.
type DecideInput ¶
type DecideInput struct {
// Comment is stored with the decision.
Comment string
// Step, when set, must name the request's current step or the decision
// fails with ErrStaleStep. It protects actors who are eligible on
// several steps from having a click meant for one step count for the
// next after the request moved on.
Step string
}
DecideInput carries the details of an approval or rejection.
type Decision ¶
type Decision struct {
ID uuid.UUID
RequestID uuid.UUID
Step int
Actor string
Outcome Outcome
Comment string
At time.Time
}
Decision is one actor's approval or rejection on one step of a request. Each actor decides at most once per step.
type Due ¶
Due identifies a request whose deadline has passed; it doubles as the keyset cursor for paging through ListDue.
type DueQuery ¶
DueQuery pages through overdue requests. When After is set only requests ordered after it are returned. Limit must be positive.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine runs workflows against a Store. It is safe for concurrent use; decisions on the same request are serialized by the store's row lock.
func (*Engine) Approve ¶
Approve records an approval by the actor in ctx on the request's current step. Once the step's rule is satisfied the request advances, or is approved if it was the last step. A request whose deadline has passed is expired instead and ErrNotPending is returned.
Example (SeparationOfDuties) ¶
Separation of duties: the requester cannot approve their own request.
package main
import (
"context"
"fmt"
approvals "github.com/byteminus/go-approvals"
"github.com/byteminus/go-approvals/memstore"
)
func main() {
engine, _ := approvals.New(memstore.New(), approvals.Options{})
_ = engine.Register(approvals.Workflow{
Key: "refund",
Steps: []approvals.Step{{Name: "lead", Approvers: []string{"lee", "sam"}, Rule: approvals.RuleAny}},
})
ctx := approvals.WithActor(context.Background(), "sam")
req, _ := engine.Submit(ctx, approvals.SubmitInput{Workflow: "refund", Subject: approvals.Ref{Type: "refund", ID: "r1"}})
_, err := engine.Approve(ctx, req.ID, approvals.DecideInput{})
fmt.Println(err)
}
Output: approvals: actor is not eligible: requesters cannot decide on their own requests
func (*Engine) Cancel ¶
Cancel withdraws a pending request. The actor in ctx must be the requester or be allowed by the CancelAuthorizer; otherwise ErrNotAuthorized is returned. reason is recorded on the transition.
func (*Engine) ExpireDue ¶
ExpireDue expires every pending request whose deadline has passed and returns how many it expired. It is meant to be called periodically by a scheduler and works across all tenants regardless of ctx; hooks see a context carrying the request's tenant. Each request expires in its own transaction, so a failing hook only holds back that request; the errors are joined and returned after the remaining requests are processed.
Example ¶
ExpireDue is meant for a periodic job; requests past their step deadline are expired and their hooks run.
package main
import (
"context"
"fmt"
"time"
approvals "github.com/byteminus/go-approvals"
"github.com/byteminus/go-approvals/memstore"
)
func main() {
now := time.Date(2026, 10, 23, 9, 0, 0, 0, time.UTC)
engine, _ := approvals.New(memstore.New(), approvals.Options{Now: func() time.Time { return now }})
_ = engine.Register(approvals.Workflow{
Key: "access",
Steps: []approvals.Step{{Name: "owner", Approvers: []string{"olga"}, Rule: approvals.RuleAny, Deadline: 24 * time.Hour}},
})
req, _ := engine.Submit(approvals.WithActor(context.Background(), "ivan"),
approvals.SubmitInput{Workflow: "access", Subject: approvals.Ref{Type: "repo", ID: "billing"}})
now = now.Add(25 * time.Hour)
n, err := engine.ExpireDue(context.Background())
fmt.Println(n, err)
req, _ = engine.Get(context.Background(), req.ID)
fmt.Println(req.Status)
}
Output: 1 <nil> expired
func (*Engine) Get ¶
Get returns a request. Requests of another tenant than the one in ctx are reported as ErrNotFound.
func (*Engine) History ¶
History returns a request's decisions and transitions, with the same tenant rule as Get.
func (*Engine) PendingFor ¶
PendingFor returns the requests, across all workflows, that actor can decide on right now: those whose current step lists the actor or one of the actor's roles, excluding requests the actor already decided on at this step, their own requests unless self-approval is allowed, and requests past their deadline. It is scoped to the tenant in ctx when one is set.
Role eligibility is resolved by asking the ApproverResolver about each distinct (tenant, role) pair that open requests are waiting on, so the cost grows with the number of such pairs rather than with the number of requests.
func (*Engine) Register ¶
Register validates w and makes it available to Submit. It returns an error wrapping ErrInvalidWorkflow for a malformed definition and ErrDuplicateWorkflow when the key is taken. The engine keeps its own copy of w.
type History ¶
type History struct {
Decisions []Decision
Transitions []Transition
}
History is the audit trail of a request, each list in the order it was recorded.
type Hook ¶
type Hook func(ctx context.Context, t Transition, r Request) error
Hook observes a transition. Hooks run inside the transaction that records the transition, after it is written, so they can enqueue notifications or update application rows atomically with it; r is the request as it stands after the transition. Returning an error aborts the whole transition.
type Options ¶
type Options struct {
// Resolver answers role membership. Workflows that use roles cannot be
// registered without one.
Resolver ApproverResolver
// CancelAuthorizer, when set, is consulted for cancellations by actors
// other than the requester.
CancelAuthorizer CancelAuthorizer
// Hooks run, in order, on every transition.
Hooks []Hook
// Now returns the current time; it defaults to time.Now.
Now func() time.Time
}
Options configures an Engine. The zero value is usable for workflows that only name explicit approvers.
type PendingQuery ¶
type PendingQuery struct {
Actor string
Grants []TenantRole
Now time.Time
TenantID string
AllTenants bool
}
PendingQuery selects an actor's inbox. A request matches when it is pending, its DueAt is zero or after Now, it belongs to TenantID (or AllTenants is set), the actor has not decided on its current step, the actor is not its requester unless it allows self-approval, and the actor is listed on the current step or Grants contains a pair of the request's tenant and one of the current step's roles.
type Ref ¶
Ref identifies the business object a request is about, for example Ref{Type: "expense", ID: "exp_42"}. Both fields are required.
type Request ¶
type Request struct {
ID uuid.UUID
Workflow string
Steps []Step
AllowSelfApproval bool
Subject Ref
Requester string
// Payload is optional application data, stored as JSON. Stores may
// normalize its formatting (PostgreSQL jsonb does).
Payload json.RawMessage
TenantID string
Status Status
// CurrentStep indexes Steps. Once the request is closed it keeps the
// index of the step that was open when it closed.
CurrentStep int
// DueAt is when the current step's deadline passes; zero means no
// deadline. It is always zero once the request is closed.
DueAt time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
Request is one run of a workflow. Steps and AllowSelfApproval are a snapshot taken at submission, so changing or removing a workflow in code never alters requests already in flight.
type ResolverFunc ¶
ResolverFunc adapts a function to ApproverResolver.
Example ¶
package main
import (
"context"
"fmt"
approvals "github.com/byteminus/go-approvals"
)
func main() {
admins := approvals.ResolverFunc(func(_ context.Context, actor, role, _ string) (bool, error) {
return role == "admin" && actor == "root", nil
})
ok, _ := admins.HasRole(context.Background(), "root", "admin", "")
fmt.Println(ok)
}
Output: true
type RoleQuery ¶
RoleQuery scopes ListPendingRoles. The zero value of AllTenants restricts the result to TenantID.
type Rule ¶
type Rule string
Rule decides when a step has collected enough approvals.
const ( // RuleAny completes the step on the first eligible approval. RuleAny Rule = "any" // RuleAll completes the step once every explicit approver has approved. // Steps using it may not list roles, because role membership is open // ended and "everyone in a role" cannot be counted reliably. RuleAll Rule = "all" // RuleQuorum completes the step once Step.Quorum distinct eligible // actors have approved. RuleQuorum Rule = "quorum" )
type Status ¶
type Status string
Status is the lifecycle state of a request.
const ( // StatusPending means the request is waiting for decisions. StatusPending Status = "pending" // StatusApproved means every step was satisfied. StatusApproved Status = "approved" // StatusRejected means an eligible actor rejected the request. StatusRejected Status = "rejected" // StatusCancelled means the requester or an authorized actor withdrew it. StatusCancelled Status = "cancelled" // StatusExpired means the current step's deadline passed. StatusExpired Status = "expired" )
type Step ¶
type Step struct {
// Name identifies the step within its workflow; names are unique per
// workflow and let callers guard decisions against a step that has
// already moved on (see DecideInput.Step).
Name string
// Approvers lists actor IDs that may decide on this step.
Approvers []string
// Roles lists roles whose members may decide on this step.
Roles []string
// Rule decides when the step is satisfied.
Rule Rule
// Quorum is the number of approvals RuleQuorum requires. It must be zero
// for the other rules.
Quorum int
// Deadline, when positive, is how long the step may stay open. Once it
// passes the request expires.
Deadline time.Duration
}
Step is one stage of a workflow. An actor is eligible to decide on the step when it is listed in Approvers or holds one of Roles, as reported by the engine's ApproverResolver.
type Store ¶
type Store interface {
// InTx runs fn in a transaction. The context passed to fn carries the
// transaction: store calls made with it join the transaction, and so do
// hooks. If fn returns an error the transaction's writes are discarded.
// A nested InTx joins the outer transaction and, when it fails, discards
// only its own writes.
InTx(ctx context.Context, fn func(ctx context.Context) error) error
// CreateRequest inserts r. It returns ErrDuplicate when r.ID exists and
// ErrInvalidRecord when r is malformed: empty workflow, subject or
// requester; no steps; an unknown status; CurrentStep out of range; or a
// closed request with a DueAt.
CreateRequest(ctx context.Context, r Request) error
// GetRequest returns the request or ErrNotFound.
GetRequest(ctx context.Context, id uuid.UUID) (Request, error)
// LockRequest returns the request like GetRequest and locks it until the
// surrounding InTx ends, so that concurrent writers on the same request
// are serialized.
LockRequest(ctx context.Context, id uuid.UUID) (Request, error)
// UpdateRequest saves the mutable fields of r: Status, CurrentStep, DueAt
// and UpdatedAt. Only pending requests may change: it returns ErrNotFound
// when r.ID does not exist, ErrNotPending when the stored request is
// closed, and ErrInvalidRecord when the new state is malformed.
UpdateRequest(ctx context.Context, r Request) error
// CreateDecision inserts d. It returns ErrAlreadyDecided when the actor
// already decided on that step of that request, ErrDuplicate when d.ID
// exists, ErrNotFound when the request does not exist, and
// ErrInvalidRecord when d is malformed.
CreateDecision(ctx context.Context, d Decision) error
// ListDecisions returns a request's decisions in insertion order.
ListDecisions(ctx context.Context, requestID uuid.UUID) ([]Decision, error)
// CreateTransition inserts t, with the same error rules as
// CreateDecision apart from ErrAlreadyDecided.
CreateTransition(ctx context.Context, t Transition) error
// ListTransitions returns a request's transitions in insertion order.
ListTransitions(ctx context.Context, requestID uuid.UUID) ([]Transition, error)
// ListPending returns the pending, not yet overdue requests on whose
// current step q.Actor may decide, ordered by creation time then ID. See
// PendingQuery for the matching rules.
ListPending(ctx context.Context, q PendingQuery) ([]Request, error)
// ListPendingRoles returns the distinct (tenant, role) pairs named by the
// current steps of pending, not yet overdue requests, ordered by tenant
// then role.
ListPendingRoles(ctx context.Context, q RoleQuery) ([]TenantRole, error)
// ListDue returns pending requests whose DueAt is set and not after
// q.Now, ordered by DueAt then ID.
ListDue(ctx context.Context, q DueQuery) ([]Due, error)
}
Store persists requests, decisions and transitions. Implementations must be safe for concurrent use and must enforce the constraints documented on each method, so that every store behaves the same; the storetest package verifies this.
type SubmitInput ¶
type SubmitInput struct {
// Workflow is the key of a registered workflow.
Workflow string
// Subject identifies the business object being approved.
Subject Ref
// Payload is optional JSON the application wants kept with the request.
Payload json.RawMessage
}
SubmitInput describes a new request.
type TenantRole ¶
TenantRole is a role within a tenant. An empty TenantID is the tenant of requests submitted without one.
type Transition ¶
type Transition struct {
ID uuid.UUID
RequestID uuid.UUID
Kind TransitionKind
FromStep int
ToStep int
Actor string
Comment string
At time.Time
}
Transition is an entry in a request's history describing a state change. FromStep and ToStep are the step indexes before and after the change; they differ only for TransitionStepAdvanced. Actor is empty for transitions the engine makes on its own, such as expiry.
type TransitionKind ¶
type TransitionKind string
TransitionKind names a change in a request's state.
const ( // TransitionSubmitted records the creation of a request. TransitionSubmitted TransitionKind = "submitted" // TransitionStepAdvanced records a satisfied step that was not the last. TransitionStepAdvanced TransitionKind = "step_advanced" // TransitionApproved records the last step being satisfied. TransitionApproved TransitionKind = "approved" // TransitionRejected records a rejection that closed the request. TransitionRejected TransitionKind = "rejected" // TransitionCancelled records a cancellation. TransitionCancelled TransitionKind = "cancelled" // TransitionExpired records a missed deadline. TransitionExpired TransitionKind = "expired" )
func (TransitionKind) Valid ¶
func (k TransitionKind) Valid() bool
Valid reports whether k is one of the defined transition kinds.
type Workflow ¶
type Workflow struct {
// Key identifies the workflow, for example "expense".
Key string
// Steps run in order; the request is approved when the last one is.
Steps []Step
// AllowSelfApproval lets the requester decide on their own request. It is
// off by default to enforce separation of duties.
AllowSelfApproval bool
}
Workflow is a named, ordered list of steps defined in application code and registered with an Engine.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package memstore is an in-memory approvals.Store for tests, examples and prototypes.
|
Package memstore is an in-memory approvals.Store for tests, examples and prototypes. |
|
Package pgxstore is the PostgreSQL implementation of approvals.Store, built on github.com/jackc/pgx/v5.
|
Package pgxstore is the PostgreSQL implementation of approvals.Store, built on github.com/jackc/pgx/v5. |
|
Package storetest is a conformance suite for approvals.Store implementations.
|
Package storetest is a conformance suite for approvals.Store implementations. |