Documentation
¶
Overview ¶
Package saga runs sagas that outlast a process: work that spans services, kept in a Store, so that a crash, a restart or a lost node is followed by the run going on from where it was.
A saga is an fsm machine and a protobuf message. Define gives states of the machine an effect, the function that runs when a run enters the state, and the effect fires the event that moves the run on:
orders := saga.Define[*ordersv1.Order]("order", machine).
Do(Reserving, reserve).
Do(Charging, charge)
eng, err := saga.Start(node, saga.Config{Store: saga.Memory()}, orders)
created, err := orders.Begin(ctx, eng, "order-123", &ordersv1.Order{Sku: "apple"})
snap, err := orders.Wait(ctx, eng, "order-123")
The run's state and data are saved before each effect and when the run waits, and nothing is replayed: after a crash, the code that runs is the effect of the state the record is in. So an effect runs at least once, and what it asks of others must be safe to ask twice: Run.Key is the same for every attempt, and travels in the metadata of what the effect sends with its ctx.
Sequence builds the saga of the textbooks, steps in order with what undoes each, as such a machine.
Index ¶
- Constants
- Variables
- func KeyOf(md grpcproc.Metadata) (key string, fence uint64, ok bool)
- func Permanent(err error) error
- type Config
- type Definition
- func (d *Definition[S, D]) Accept[P proto.Message](ev fsm.Event[P], apply func(data D, p P)) *Definition[S, D]
- func (d *Definition[S, D]) AcceptSignal(ev fsm.Event[fsm.Unit]) *Definition[S, D]
- func (d *Definition[S, D]) After(state S, after time.Duration, ev fsm.Event[fsm.Unit]) *Definition[S, D]
- func (d *Definition[S, D]) Begin(ctx context.Context, e *Engine, id string, data D) (bool, error)
- func (d *Definition[S, D]) Do(state S, effect Effect[S, D], opts ...StepOption) *Definition[S, D]
- func (d *Definition[S, D]) Get(ctx context.Context, e *Engine, id string) (Snapshot[S, D], error)
- func (d *Definition[S, D]) Notify(ctx context.Context, e *Engine, id string, ev fsm.Event[fsm.Unit]) error
- func (d *Definition[S, D]) Resume(ctx context.Context, e *Engine, id string) error
- func (d *Definition[S, D]) Signal[P proto.Message](ctx context.Context, e *Engine, id string, ev fsm.Event[P], p P) error
- func (d *Definition[S, D]) Version(v uint64) *Definition[S, D]
- func (d *Definition[S, D]) Wait(ctx context.Context, e *Engine, id string) (Snapshot[S, D], error)
- type Effect
- type Engine
- type Record
- type Run
- func (r *Run[S, D]) Attempt() int
- func (r *Run[S, D]) Fence() uint64
- func (r *Run[S, D]) Fire[A any](ctx context.Context, ev fsm.Event[A], arg A) error
- func (r *Run[S, D]) ID() string
- func (r *Run[S, D]) Key() string
- func (r *Run[S, D]) Process() *grpcproc.Process[proto.Message]
- func (r *Run[S, D]) State() S
- type Saga
- type Signal
- type Snapshot
- type Stage
- type Status
- type StepOption
- type StepSpec
- type Store
Examples ¶
Constants ¶
const ( MetadataKey = "grpcproc-saga-key" MetadataFence = "grpcproc-saga-fence" )
The metadata an effect's ctx carries, and so every send and call made with it: the run's key, the same for every attempt of one visit to a state, and its fence, which grows with each owner the run has.
const MaxInbox = 64
MaxInbox is how many signals a run holds before Store.Signal refuses more. A signal no state of the run takes is held until the run ends, so a sender that repeats itself can fill it.
Variables ¶
var ( // ErrLost is a write by an engine that no longer owns the run. ErrLost = errors.New("saga: the run has another owner") // ErrNoRun is a signal to, or a question about, a run that is not there. ErrNoRun = errors.New("saga: no such run") // ErrEnded is a signal to a run that is Done. ErrEnded = errors.New("saga: the run has ended") // ErrInboxFull is a signal to a run that holds MaxInbox already. ErrInboxFull = errors.New("saga: the run's inbox is full") // ErrFired is a second Fire from one effect. ErrFired = errors.New("saga: the effect has fired already") )
var ErrBusy = errors.New("saga: the engine is answering other questions; ask again")
ErrBusy answers a query or a control that comes while an engine answers as many as it does at once.
var ErrNoSaga = errors.New("saga: the engine runs no such saga")
ErrNoSaga answers a query or a control about a saga the engine does not run: the store it shares may keep another service's runs, which are not this engine's to show.
Functions ¶
Types ¶
type Config ¶
type Config struct {
// Store keeps the runs. Required. Engines that share one share the runs.
Store Store
// Name is the name the engine's process is registered under on its node.
// Default "saga".
Name string
// Poll is how often the engine asks the store for runs that are due, and
// how often Wait asks about a run. A run begun, signalled or resumed
// through this engine is claimed at once. Default 1s.
Poll time.Duration
// Lease is how long a claim holds a run without being renewed: how long
// a run whose engine died waits for another. The engine renews it a
// quarter of that after each claim or renewal, and tries one that failed
// again a sixteenth later; an effect whose engine could not renew it,
// with a quarter of it left, has its ctx ended. Default 30s; at least a
// millisecond.
Lease time.Duration
// Concurrency is how many runs the engine works on at once. Default 64.
Concurrency int
// InspectData lets the engine show, to a query through the Inspector,
// a run's data and its signals' payloads. Off, a query sees a run's
// state, status, timers, and its error and cause, which say why it is
// stuck, and not what the run carries, which is often a customer's: a
// read-only Inspector is not a private one. An effect whose error would
// tell a customer's data should not put it there.
InspectData bool
}
Config configures an Engine.
type Definition ¶
type Definition[S comparable, D proto.Message] struct { // contains filtered or unexported fields }
Definition is a saga: an fsm machine, the type of its runs' data, the effects of its states, their timers, and the events it takes from outside. Build it with Define and its methods, then give it to Start. Its other methods begin runs and ask about them, through an Engine.
func Define ¶
func Define[D proto.Message, S comparable](name string, m *fsm.Machine[S]) *Definition[S, D]
Define begins a saga named name, whose runs are states of m with a D beside them. m must have an Initial state, where a run begins, and its states must print differently, since a run's state is kept as fmt prints it. Mistakes here and in the methods are reported by Start.
func Sequence ¶
Sequence is a saga of steps done in order, named name. A step that fails for good, by a Permanent error or by running out of Attempts, up to the pivot, has the steps done so far undone, last first, itself included, since it may have happened; the run then ends in StageFailed, with why in its Cause. After the pivot there is no way back. A run whose steps are all done ends in StageDone.
It is a Definition over a machine built here, so a run is begun, asked about and drawn like any other.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"strings"
"time"
"google.golang.org/protobuf/types/known/wrapperspb"
"github.com/floatdrop/grpcproc"
"github.com/floatdrop/grpcproc/saga"
)
func main() {
ctx := context.Background()
node, err := grpcproc.NewNode(grpcproc.Config{Name: "shop", Resolver: grpcproc.StaticResolver{}, Admit: grpcproc.AdmitAll})
if err != nil {
panic(err)
}
if err := node.Start(ctx); err != nil {
panic(err)
}
defer func() { _ = node.Stop(ctx) }()
// A run's data is the card it is paid with.
declined := func(card string) bool { return strings.HasPrefix(card, "4000") }
type order = saga.Run[saga.Stage, *wrapperspb.StringValue]
note := func(what string) saga.Effect[saga.Stage, *wrapperspb.StringValue] {
return func(_ context.Context, r *order) error {
fmt.Println(r.ID(), what)
return nil
}
}
charge := func(_ context.Context, r *order) error {
if declined(r.Data.Value) {
return saga.Permanent(errors.New("card declined"))
}
fmt.Println(r.ID(), "charge")
return nil
}
refund := func(_ context.Context, r *order) error {
// A charge that failed is undone too, since it may have happened.
if declined(r.Data.Value) {
fmt.Println(r.ID(), "refund: nothing was charged")
return nil
}
fmt.Println(r.ID(), "refund")
return nil
}
orders, err := saga.Sequence("order",
saga.Step("reserve", note("reserve")).Undo(note("release")),
saga.Step("charge", charge).Undo(refund).Pivot(),
saga.Step("ship", note("ship")),
)
if err != nil {
panic(err)
}
eng, err := saga.Start(node, saga.Config{Store: saga.Memory(), Poll: 10 * time.Millisecond}, orders)
if err != nil {
panic(err)
}
place(ctx, orders, eng, "order-1", "4242 4242")
place(ctx, orders, eng, "order-2", "4000 0002")
}
// place begins a run of orders paid with card and waits for its end.
func place(ctx context.Context, orders *saga.Definition[saga.Stage, *wrapperspb.StringValue], eng *saga.Engine, id, card string) {
if _, err := orders.Begin(ctx, eng, id, wrapperspb.String(card)); err != nil {
panic(err)
}
s, err := orders.Wait(ctx, eng, id)
if err != nil {
panic(err)
}
if s.Cause != "" {
fmt.Printf("%s ended in %s: %s\n", id, s.State, s.Cause)
return
}
fmt.Printf("%s ended in %s\n", id, s.State)
}
Output: order-1 reserve order-1 charge order-1 ship order-1 ended in done order-2 reserve order-2 refund: nothing was charged order-2 release order-2 ended in failed: card declined
func (*Definition[S, D]) Accept ¶
func (d *Definition[S, D]) Accept[P proto.Message](ev fsm.Event[P], apply func(data D, p P)) *Definition[S, D]
Accept lets ev reach a run from outside, by Signal. apply, unless nil, writes the payload to the run's data when the machine takes the event. A state that takes it by an internal transition (fsm's Stay) keeps its visit: its effect is not run again, and its timer stands.
func (*Definition[S, D]) AcceptSignal ¶
func (d *Definition[S, D]) AcceptSignal(ev fsm.Event[fsm.Unit]) *Definition[S, D]
AcceptSignal is Accept for an event with no payload, sent by Notify.
func (*Definition[S, D]) After ¶
func (d *Definition[S, D]) After(state S, after time.Duration, ev fsm.Event[fsm.Unit]) *Definition[S, D]
After fires ev on a run that is still in the same visit to state once after has passed since it entered it. The time is kept in the run's record, so it outlasts the engine that set it.
func (*Definition[S, D]) Begin ¶
Begin starts a run with id and data, in the machine's Initial state, and reports whether it did: a saga has one run of an id, so beginning it again is no error and changes nothing. id is the run's idempotency key for whoever begins it.
func (*Definition[S, D]) Do ¶
func (d *Definition[S, D]) Do(state S, effect Effect[S, D], opts ...StepOption) *Definition[S, D]
Do gives state its effect: what runs when a run enters it. It runs before any signal or timer moves the run on from this visit.
func (*Definition[S, D]) Notify ¶
func (d *Definition[S, D]) Notify(ctx context.Context, e *Engine, id string, ev fsm.Event[fsm.Unit]) error
Notify sends ev, an event with no payload, to a run, as Signal does.
func (*Definition[S, D]) Signal ¶
func (d *Definition[S, D]) Signal[P proto.Message](ctx context.Context, e *Engine, id string, ev fsm.Event[P], p P) error
Signal sends ev with its payload to a run. It is kept with the run until its machine is in a state that accepts it; of the signals a state accepts, the earlier is taken first. ev must be one the saga Accepts.
func (*Definition[S, D]) Version ¶
func (d *Definition[S, D]) Version(v uint64) *Definition[S, D]
Version says which version of the saga this program has; 0 if it never says. A run keeps the highest version that began, signalled or worked on it, and an engine works only on runs its version reaches. So raise it when the machine gains a state, an event or a timer: in a rolling deploy, the old program then leaves alone the runs the new one has touched, which it could not read. Runs of an older version are taken up as they are.
type Effect ¶
Effect is what runs when a run enters a state. It fires the event that moves the run on, with Run.Fire, or returns nil without firing, and the run waits in the state for a signal or its timer. An error has it run again, after a backoff; what it wrote to Run.Data is then dropped.
It runs at least once per visit: after a crash, or a lost lease, the next owner runs it again, with the same Run.Key. ctx ends when the run's process is told to exit or its engine loses the run, and carries the key and the fence as metadata, so what the effect sends with ctx carries them too.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine runs sagas on a node: it claims runs that are due from the store and works on each in a process of its own.
type Record ¶
type Record struct {
Saga string // the Definition's name
ID string // the run's, unique within its saga
// SagaVersion is the highest Definition.Version that began, signalled or
// worked on the run. An engine claims a run only if its saga's version
// is at least that: an older program leaves a newer one's runs alone.
SagaVersion uint64
State string // the machine's state, as fmt prints it
Data []byte // the run's data, a protobuf encoding
// Visit counts the states the run has entered, the first included. It
// tells two visits to one state apart, in Run.Key and for a timer.
Visit uint64
// EffectDone is set once the state's effect is through for this visit:
// it returned nil without firing, or failed for good and its Otherwise
// kept the run in the state. The run waits, and the effect is not run
// again in this visit.
EffectDone bool
Attempts int // how many times the effect failed in this visit, while it is tried
Error string // why it failed last while it is tried, or why the run is Stuck
// Cause is the error an Otherwise last fired with: why the run left its
// way, kept for the rest of it.
Cause string
Status Status
// Wake is when the run is next due: the sooner of RetryAt and Deadline
// when its owner let it go. Zero is never. A signal its owner has not
// seen makes a run due whatever its Wake.
Wake time.Time
// RetryAt is when the effect, having failed, is next tried; zero if it
// is not waiting for that.
RetryAt time.Time
// Deadline is when the timer of this visit fires; zero if it has none.
Deadline time.Time
// Owner is the engine working on the run, "" for none, until
// LeaseUntil. Epoch counts the claims of the run: it is the fence a
// Save must present.
Owner string
LeaseUntil time.Time
Epoch uint64
// Inbox is the signals waiting, in the order they came. A Save removes
// those in Consumed, by Seq, and says in Seen the highest Seq its owner
// has looked at.
Inbox []Signal
Consumed []uint64
Seen uint64
Revision uint64 // counts the writes to the record
CreatedAt time.Time
UpdatedAt time.Time
}
Record is a run as a Store keeps it.
type Run ¶
type Run[S comparable, D proto.Message] struct { // Data is the run's data. What an effect writes to it is saved when the // effect returns nil, with the state it fired to. Data D // contains filtered or unexported fields }
Run is a run as its effect sees it.
func (*Run[S, D]) Fence ¶
Fence grows with each owner the run has. A participant that keeps the highest it has seen for a key can refuse an old owner's late request.
func (*Run[S, D]) Fire ¶
Fire moves the run on by ev, as the machine's Fire does. An effect fires once. An event the machine refuses in this state is a Permanent error: trying again will not change the machine. An internal transition (fsm's Stay) is taken without leaving the state: the run then waits in it, as if the effect had not fired.
func (*Run[S, D]) Key ¶
Key names this visit to this state, the same for every attempt: the idempotency key of what the effect asks of others.
type Saga ¶
type Saga interface {
// contains filtered or unexported methods
}
Saga is a Definition, of any state and data type, as Start takes it.
type Signal ¶
type Signal struct {
Seq uint64 // set by the Store, growing per run
Event string // the fsm event's name
Payload []byte // its payload, a protobuf encoding; nil for a signal with none
// Version is the Definition.Version of the program that sent it: the
// run's SagaVersion is raised to it.
Version uint64
}
Signal is an event sent to a run from outside it, kept until its machine is in a state that takes it.
type Snapshot ¶
type Snapshot[S comparable, D proto.Message] struct { ID string State S Data D Status Status Attempts int // failures of the state's effect in this visit Error string // the last, or why the run is Stuck Cause string // the error an Otherwise last fired with Updated time.Time }
Snapshot is a run as Get and Wait report it.
type Stage ¶
type Stage string
Stage is a state of a Sequence's machine: a step's name while the step is done, "undo " and its name while it is undone, StageDone or StageFailed.
type Status ¶
type Status uint8
Status is where a run stands with its engine.
const ( // Active is a run that goes on: at work, or waiting for a signal, a // timer or its next attempt. Active Status = iota // Done is a run whose machine reached a state with no way out. Done // Stuck is a run whose effect failed for good with no Otherwise to // fire. It is kept as it is until Resume. Stuck )
type StepOption ¶
type StepOption func(*step)
StepOption says how a state's effect is tried.
func Attempts ¶
func Attempts(n int) StepOption
Attempts bounds how many times an effect is run in one visit before it has failed for good. The default, 0, is no bound.
func Backoff ¶
func Backoff(lo, hi time.Duration) StepOption
Backoff is the wait before an effect that failed is run again: lo after the first failure, doubling to hi. The default is 100ms to a minute.
func Otherwise ¶
func Otherwise(ev fsm.Event[string]) StepOption
Otherwise fires ev, with the error's text, when the effect has failed for good: it returned a Permanent error, or ran out of Attempts. With none, or if the machine refuses ev, the run is Stuck. One the machine takes by an internal transition keeps the run in the state, waiting for a signal or its timer.
type StepSpec ¶
StepSpec is a step of a Sequence; see Step.
func Step ¶
Step is a step of a Sequence, named name: do does it. It is an Effect that does not fire: returning nil is the step done, and an error has it tried again, as opts say, like any effect.
func (*StepSpec[D]) Pivot ¶
Pivot marks the step after which the run only goes forward: the steps after it are not undone, nor is anything undone for them. One that fails for good leaves the run Stuck. Without a pivot, the last step is it.
func (*StepSpec[D]) Undo ¶
func (s *StepSpec[D]) Undo(undo Effect[Stage, D], opts ...StepOption) *StepSpec[D]
Undo gives the step what undoes it, run if a later step, or this one, fails for good before the pivot. The step may not have happened, or not wholly: undo must then do nothing, or the rest. An undo that fails for good leaves the run Stuck.
type Store ¶
type Store interface {
// Create adds r, unless its saga has a run with its ID: then it returns
// that run, and false.
Create(ctx context.Context, r Record) (Record, bool, error)
// Claim gives owner up to n runs that are due, each for ttl, of the sagas
// named in sagas, whose SagaVersion is no more than the version given
// there. A run is due if it is Active, has no owner or one whose lease
// ended, and its Wake has come or it holds a signal past its Seen. Claim
// raises each one's Epoch, and returns them oldest Wake first.
Claim(ctx context.Context, owner string, sagas map[string]uint64, ttl time.Duration, n int) ([]Record, error)
// Save writes the state of a run its caller owns: every field but its
// lease, Inbox, CreatedAt and Revision, and its SagaVersion only if
// r's is higher: a signal may have raised it since the caller read it. It removes the signals in
// r.Consumed. The lease stays as Claim and Renew left it, unless r.Owner
// is "": that lets the run go. Save returns the record as it is kept,
// its inbox as it is now; ErrLost if r.Epoch is not the run's.
Save(ctx context.Context, r Record) (Record, error)
// Renew extends the lease of a run to ttl from now; ErrLost if epoch is
// not the run's, or the run has no owner.
Renew(ctx context.Context, saga, id string, epoch uint64, ttl time.Duration) error
// Signal adds s to a run's inbox, with the next Seq, which makes an
// Active run due, and raises the run's SagaVersion to s.Version. ErrNoRun
// if there is none, ErrEnded if it is Done, ErrInboxFull if it holds
// MaxInbox.
Signal(ctx context.Context, saga, id string, s Signal) error
// Resume makes a Stuck run Active, due at once, its attempts counted
// from none and its RetryAt cleared. ErrNoRun if there is none; a run
// that is not Stuck is left as it is.
Resume(ctx context.Context, saga, id string) error
// Get returns a run, and whether there is one.
Get(ctx context.Context, saga, id string) (Record, bool, error)
// List returns the runs of a saga, by ID, as Go orders strings: byte by
// byte, whatever a database's collation.
List(ctx context.Context, saga string) ([]Record, error)
}
A Store keeps the runs. It is the one thing a saga needs that outlasts a process: everything else is the engine's, which has no state of its own. sagatest.Store checks an implementation.
One engine owns a run at a time, by a lease, and only the owner writes its state; anyone adds signals, which are kept beside it. Every claim raises the run's Epoch, and a Save or Renew with another is refused with ErrLost, so an engine that lost its lease cannot write over its successor.
Every method returns when its ctx ends: an engine gives up a lease it could not renew in time, and a Renew that outlasts its ctx would keep it from knowing.