approvals

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 9 Imported by: 0

README

go-approvals

tests Go Reference

Multi-step approvals and business workflows for SaaS applications: an expense approved by a manager and then by finance, a contract signed off by legal, an access request that expires if nobody answers. Workflows are plain Go values registered by key; requests snapshot their steps so code changes never break work in flight; decisions are serialized with row locks; and every transition runs your hooks inside the same transaction, so notifications are enqueued atomically with the state change.

Install

go get github.com/byteminus/go-approvals

Requires Go 1.26 or later. PostgreSQL 16 or later for pgxstore.

Quick start

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"

	approvals "github.com/byteminus/go-approvals"
	"github.com/byteminus/go-approvals/pgxstore"
)

func main() {
	ctx := context.Background()
	pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer pool.Close()

	store, err := pgxstore.New(pool)
	if err != nil {
		log.Fatal(err)
	}
	if err := store.CreateSchema(ctx); err != nil {
		log.Fatal(err)
	}

	// Role membership comes from your application.
	roles := approvals.ResolverFunc(func(ctx context.Context, actor, role, tenant string) (bool, error) {
		return role == "finance" && (actor == "fay" || actor == "finn"), nil
	})
	engine, err := approvals.New(store, approvals.Options{
		Resolver: roles,
		Hooks: []approvals.Hook{func(ctx context.Context, t approvals.Transition, r approvals.Request) error {
			// Runs in the transition's transaction: enqueue notifications here.
			log.Printf("%s: %s", r.ID, t.Kind)
			return nil
		}},
	})
	if err != nil {
		log.Fatal(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 {
		log.Fatal(err)
	}

	as := func(actor string) context.Context {
		return approvals.WithTenant(approvals.WithActor(ctx, 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 {
		log.Fatal(err)
	}
	for _, actor := range []string{"maria", "fay", "finn"} {
		if req, err = engine.Approve(as(actor), req.ID, approvals.DecideInput{Comment: "ok"}); err != nil {
			log.Fatal(err)
		}
	}
	fmt.Println(req.Status) // approved
}

Concepts

  • Workflow: a key and an ordered list of steps, defined in code and validated by Engine.Register. Each step has a unique name, approvers (explicit actor IDs, roles, or both) and a rule:
    • RuleAny: the first eligible approval completes the step.
    • RuleAll: every listed approver must approve. Cannot be combined with roles, because "everyone in a role" cannot be counted reliably.
    • RuleQuorum: Quorum distinct eligible approvals complete the step.
    • An optional Deadline per step: once it passes the request expires.
  • Separation of duties is on by default: the requester cannot decide on their own request unless the workflow sets AllowSelfApproval. Submit rejects with ErrUnsatisfiable a request that could never complete because of it (for example when the requester is a step's only approver).
  • Request: a UUID v7, the workflow key, a snapshot of the steps, the subject Ref, requester, JSON payload, tenant ID, status (pending, approved, rejected, cancelled, expired), the current step index, the current deadline and timestamps.
  • Decision: one approval or rejection per actor per step, with a comment. A second one fails with ErrAlreadyDecided. A rejection closes the request; an approval advances it once the rule is satisfied, and the last step approves it. DecideInput.Step optionally names the step the actor is looking at, so a stale click fails with ErrStaleStep instead of counting for the next step.
  • Eligibility: an actor listed on the step, or one for whom your ApproverResolver.HasRole(ctx, actor, role, tenantID) returns true. The tenant passed is the request's.
  • Transition: every state change (submitted, step_advanced, approved, rejected, cancelled, expired) is recorded and passed to the hooks in the same transaction. A hook error aborts the change.
  • Actor and tenant travel in the context: WithActor names who is acting; WithTenant stamps new requests and scopes every read and decision to that tenant (requests of other tenants are ErrNotFound).
  • Deadlines: ExpireDue expires overdue requests and is meant for a scheduler. A decision on an overdue request expires it on the spot and fails with ErrNotPending, so a late click never counts. Both paths take the same row lock, so a race between them has exactly one outcome.

PostgreSQL

pgxstore.New(db, opts...) takes a *pgxpool.Pool, *pgx.Conn or pgx.Tx. Tables are named with a prefix, approval_ by default; use pgxstore.WithTablePrefix("billing.approval_") for another prefix or a schema. store.CreateSchema(ctx) applies the DDL below (idempotent), and store.Schema() returns it for migration tools:

CREATE TABLE IF NOT EXISTS "approval_requests" (
	id                  uuid PRIMARY KEY,
	workflow            text NOT NULL CHECK (workflow <> ''),
	steps               jsonb NOT NULL CHECK (
		CASE WHEN jsonb_typeof(steps) = 'array' THEN jsonb_array_length(steps) > 0 ELSE false END),
	allow_self_approval boolean NOT NULL,
	subject_type        text NOT NULL CHECK (subject_type <> ''),
	subject_id          text NOT NULL CHECK (subject_id <> ''),
	requester           text NOT NULL CHECK (requester <> ''),
	payload             jsonb,
	tenant_id           text NOT NULL,
	status              text NOT NULL CHECK (status IN ('pending', 'approved', 'rejected', 'cancelled', 'expired')),
	current_step        integer NOT NULL,
	current_approvers   text[] NOT NULL,
	current_roles       text[] NOT NULL,
	due_at              timestamptz,
	created_at          timestamptz NOT NULL,
	updated_at          timestamptz NOT NULL,
	CHECK (current_step >= 0 AND current_step <
		CASE WHEN jsonb_typeof(steps) = 'array' THEN jsonb_array_length(steps) ELSE 0 END),
	CHECK (status = 'pending' OR due_at IS NULL)
);

CREATE INDEX IF NOT EXISTS "approval_requests_due_idx" ON "approval_requests" (due_at, id)
	WHERE status = 'pending' AND due_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS "approval_requests_approvers_idx" ON "approval_requests" USING gin (current_approvers)
	WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS "approval_requests_roles_idx" ON "approval_requests" USING gin (current_roles)
	WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS "approval_requests_tenant_idx" ON "approval_requests" (tenant_id, status, created_at);

CREATE TABLE IF NOT EXISTS "approval_decisions" (
	seq        bigint GENERATED ALWAYS AS IDENTITY,
	id         uuid PRIMARY KEY,
	request_id uuid NOT NULL REFERENCES "approval_requests" (id) ON DELETE CASCADE,
	step       integer NOT NULL CHECK (step >= 0),
	actor      text NOT NULL CHECK (actor <> ''),
	outcome    text NOT NULL CHECK (outcome IN ('approved', 'rejected')),
	comment    text NOT NULL,
	created_at timestamptz NOT NULL,
	CONSTRAINT "approval_decisions_actor_key" UNIQUE (request_id, step, actor)
);

CREATE TABLE IF NOT EXISTS "approval_transitions" (
	seq        bigint GENERATED ALWAYS AS IDENTITY,
	id         uuid PRIMARY KEY,
	request_id uuid NOT NULL REFERENCES "approval_requests" (id) ON DELETE CASCADE,
	kind       text NOT NULL CHECK (kind IN ('submitted', 'step_advanced', 'approved', 'rejected', 'cancelled', 'expired')),
	from_step  integer NOT NULL CHECK (from_step >= 0),
	to_step    integer NOT NULL CHECK (to_step >= 0),
	actor      text NOT NULL,
	comment    text NOT NULL,
	created_at timestamptz NOT NULL
);

CREATE INDEX IF NOT EXISTS "approval_transitions_request_idx" ON "approval_transitions" (request_id, seq);

current_approvers and current_roles mirror the current step of the snapshot so inboxes are served from GIN indexes; the store maintains them on every write.

Joining your transaction

Every engine call runs in a store transaction. With WithConn, that transaction begins on the connection your context carries, so it becomes a savepoint inside your own transaction and commits or rolls back with it:

type txKey struct{}

store, err := pgxstore.New(pool, pgxstore.WithConn(func(ctx context.Context) pgxstore.Querier {
	if tx, ok := ctx.Value(txKey{}).(pgx.Tx); ok {
		return tx
	}
	return nil // use the pool
}))

tx, err := pool.Begin(ctx)
// ... insert the expense row with tx ...
req, err := engine.Submit(context.WithValue(ctx, txKey{}, tx), input)
err = tx.Commit(ctx)

Inside a hook, store.TxFrom(ctx) returns the transaction of the transition, for writing outbox rows or enqueueing jobs atomically with it.

API overview

Call Purpose
approvals.New(store, Options{Resolver, CancelAuthorizer, Hooks, Now}) Create an engine.
Register(Workflow) Validate and register a workflow by key.
Submit(ctx, SubmitInput) Start a request for the actor in ctx.
Approve(ctx, id, DecideInput) / Reject(...) Record a decision on the current step.
Cancel(ctx, id, reason) Withdraw a request: the requester, or an actor your CancelAuthorizer allows.
Get(ctx, id) / History(ctx, id) Read a request, its decisions and its transitions.
PendingFor(ctx, actor) The actor's inbox across workflows, including role-based eligibility.
ExpireDue(ctx) Expire overdue requests; call it from a scheduler.
WithActor, ActorFrom, WithTenant, TenantFrom Context helpers.

Errors are sentinels for errors.Is: ErrInvalidWorkflow, ErrDuplicateWorkflow, ErrUnknownWorkflow, ErrInvalidInput, ErrNoActor, ErrUnsatisfiable, ErrNotFound, ErrNotPending, ErrNotEligible, ErrAlreadyDecided, ErrStaleStep, ErrNotAuthorized, and, from stores, ErrDuplicate and ErrInvalidRecord.

Stores: memstore (in memory; transactions are serialized and rolled back on error, but cannot join a database transaction) and pgxstore. Implement approvals.Store for anything else and run storetest.Run against it.

Testing

go test -race ./...
TEST_DATABASE_URL=postgres://postgres:postgres@localhost:5432/approvals?sslmode=disable go test -race ./...

Without TEST_DATABASE_URL the PostgreSQL tests are skipped (and fail when CI is set). The storetest conformance suite runs against both stores and includes the concurrency tests: concurrent approvals on a quorum step advance it exactly once with no duplicate decisions, and ExpireDue racing a decision always leaves one consistent outcome.

Roadmap

  • Pagination and filters for PendingFor (it returns the whole inbox).
  • Delegation and out-of-office substitutes.
  • Escalation or reminders before a deadline, instead of only expiry.
  • Hooks for individual decisions that do not change state.
  • Conditional steps (skip a step based on the payload).
  • Purging or archiving closed requests.

License

MIT, see LICENSE.

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

Examples

Constants

This section is empty.

Variables

View Source
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

func ActorFrom(ctx context.Context) (string, bool)

ActorFrom returns the actor stored by WithActor. The boolean is false when none is set or it is empty.

func TenantFrom

func TenantFrom(ctx context.Context) (string, bool)

TenantFrom returns the tenant stored by WithTenant and whether one is set. An empty tenant ID set explicitly is still a scope.

func WithActor

func WithActor(ctx context.Context, actor string) context.Context

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

func WithTenant(ctx context.Context, tenantID string) context.Context

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

type CancelAuthorizerFunc func(ctx context.Context, actor string, r Request) (bool, error)

CancelAuthorizerFunc adapts a function to CancelAuthorizer.

func (CancelAuthorizerFunc) CanCancel

func (f CancelAuthorizerFunc) CanCancel(ctx context.Context, actor string, r Request) (bool, error)

CanCancel calls f.

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

type Due struct {
	ID    uuid.UUID
	DueAt time.Time
}

Due identifies a request whose deadline has passed; it doubles as the keyset cursor for paging through ListDue.

type DueQuery

type DueQuery struct {
	Now   time.Time
	After *Due
	Limit int
}

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 New

func New(store Store, opts Options) (*Engine, error)

New returns an engine backed by store.

func (*Engine) Approve

func (e *Engine) Approve(ctx context.Context, id uuid.UUID, in DecideInput) (Request, error)

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

func (e *Engine) Cancel(ctx context.Context, id uuid.UUID, reason string) (Request, error)

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

func (e *Engine) ExpireDue(ctx context.Context) (int, error)

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

func (e *Engine) Get(ctx context.Context, id uuid.UUID) (Request, error)

Get returns a request. Requests of another tenant than the one in ctx are reported as ErrNotFound.

func (*Engine) History

func (e *Engine) History(ctx context.Context, id uuid.UUID) (History, error)

History returns a request's decisions and transitions, with the same tenant rule as Get.

func (*Engine) PendingFor

func (e *Engine) PendingFor(ctx context.Context, actor string) ([]Request, error)

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

func (e *Engine) Register(w Workflow) error

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.

func (*Engine) Reject

func (e *Engine) Reject(ctx context.Context, id uuid.UUID, in DecideInput) (Request, error)

Reject records a rejection by the actor in ctx, which closes the request. Deadlines are handled as for Approve.

func (*Engine) Submit

func (e *Engine) Submit(ctx context.Context, in SubmitInput) (Request, error)

Submit starts a request for the actor in ctx, stamped with the tenant in ctx (empty when none is set).

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 Outcome

type Outcome string

Outcome is what an actor decided.

const (
	// OutcomeApproved records an approval.
	OutcomeApproved Outcome = "approved"
	// OutcomeRejected records a rejection.
	OutcomeRejected Outcome = "rejected"
)

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

type Ref struct {
	Type string
	ID   string
}

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.

func (Request) Clone

func (r Request) Clone() Request

Clone returns a deep copy of r, so that the copy can be modified without affecting the original.

type ResolverFunc

type ResolverFunc func(ctx context.Context, actor, role, tenantID string) (bool, error)

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

func (ResolverFunc) HasRole

func (f ResolverFunc) HasRole(ctx context.Context, actor, role, tenantID string) (bool, error)

HasRole calls f.

type RoleQuery

type RoleQuery struct {
	Now        time.Time
	TenantID   string
	AllTenants bool
}

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"
)

func (Status) Valid

func (s Status) Valid() bool

Valid reports whether s is one of the defined statuses.

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

type TenantRole struct {
	TenantID string
	Role     string
}

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.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL