saga

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 15 Imported by: 3 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

grpcproc/saga

Sagas for grpcproc: work that spans services and outlasts a process. Reserve, charge, ship, and undo what was done when a later step cannot be. Each run is kept in a store, so with a store that outlasts the program, a crash, a restart or a lost node is followed by the run going on from where it was. The stores are in memory, which the nodes of one program can share, so a run outlasts a node of that program but not the program's restart, and in PostgreSQL, in grpcproc/saga/postgres (see Stores). A package of grpcproc's, built on its public API and fsm.

go get github.com/floatdrop/grpcproc # saga is a package of the core module
var order = fsm.MustNew("order",
    fsm.Initial(Reserving),
    fsm.From(Reserving).On(reserved).To(Charging),
    fsm.From(Reserving).On(refused).To(Refused),
    fsm.From(Charging).On(charged).To(Done),
    fsm.From(Charging).On(declined).To(Releasing),
    fsm.From(Releasing).On(released).To(Refused),
)

orders := saga.Define[*ordersv1.Order]("order", order).
    Do(Reserving, func(ctx context.Context, r *saga.Run[State, *ordersv1.Order]) error {
        res, err := stock.Reserve(ctx, r.Process(), &inventoryv1.Reserve{Order: r.ID(), Sku: r.Data.Sku})
        if err != nil {
            return err // tried again, with the same key
        }
        if res.Refused != "" {
            return r.Fire(ctx, refused, res.Refused)
        }
        return r.Fire(ctx, reserved, fsm.Unit{})
    }).
    Do(Charging, charge).
    Do(Releasing, release)

eng, err := saga.Start(node, saga.Config{Store: store}, orders)
created, err := orders.Begin(ctx, eng, "order-123", &ordersv1.Order{Sku: "apple"})
snap, err := orders.Wait(ctx, eng, "order-123") // once it is Done or Stuck

A saga that is a list of steps, each with what undoes it, needs no machine of its own: see Sequence.

A run is a state and its data

A saga is an fsm machine and a protobuf message. A run is one state of the machine and one value of the message, kept together as one record. Begin starts a run in the machine's Initial state; its id is unique within the saga, so beginning it again is no error and changes nothing, and the id is the idempotency key of whoever begins it.

Do gives a state its effect, the function that runs when a run enters the state. The effect does its work and fires the event that moves the run on, with Run.Fire; what it wrote to Run.Data is saved with the new state. An effect that returns nil without firing has done its part, and the run waits in the state, for a signal or its timer. A state with no effect waits from the start. A state with no way out ends the run: it is Done.

Nothing is replayed. After a crash, the code that runs is the effect of the state the record is in, so an effect is ordinary Go, goroutines and select included, and a new version of the program takes a run up where the record says it is. That is the difference from Temporal, which replays a history through the workflow's code and forbids both, and from DBOS, which runs the function again and asks for the same steps in the same order.

Run
Data the run's data; saved when the effect returns nil, dropped when it fails
ID(), State() as Begin was given it, and the state it is in
Fire(ctx, ev, arg) moves the run on; once the machine has taken an event, another Fire is ErrFired
Process() the run's process: the Caller of the effect's sends and calls
Key(), Fence() the idempotency key of this visit, and the run's epoch, raised by each claim of it
Attempt() which attempt of the effect this is in this visit, from 1

An event the machine refuses in the state is a Permanent error: trying again would not change the machine. An internal transition (fsm's Stay) takes its event without leaving the state: the effect is not run again, and the state's timer stands.

An effect runs at least once

The record is saved before each effect and when the run waits, not as an effect returns, so a crash after an effect and before the next save runs the effect again, on whichever node takes the run up. That cannot be avoided, only made safe: what an effect asks of others must be safe to ask twice.

Run.Key names the visit to the state, the same for every attempt of it: the saga's name, the run's id, the state and how many states the run has entered, as in order/order-123/Charging/2. The effect's ctx carries the key and the fence as metadata (grpcproc-saga-key, grpcproc-saga-fence), so every send and call it makes with that ctx carries them too. A participant reads them with KeyOf, keeps the key with what it did, and answers a repeat with what it answered before:

key, fence, ok := saga.KeyOf(m.Metadata)
if ok {
    prev, seen := payments.Find(key)
    switch {
    case seen && fence < prev.Fence:
        return m.Reply(nil, errStale) // an earlier owner's request, late
    case seen:
        payments.RaiseFence(key, fence) // the highest seen for key
        return m.Reply(prev.Answer, nil)
    }
}
// charge, then keep key, fence and the answer

The fence grows with each engine that claims the run, so a participant that keeps the highest it has seen for a key can refuse a request a previous owner sent before it lost the run.

Failures

An effect that returns an error is run again after a backoff, with the same key; how many times it failed, and why, are in the record. A call that timed out may have been handled, so the effect returns its error and is tried again; it is never taken for a refusal. A refusal is an answer, and the effect fires an event for it.

Option of Do
Backoff(lo, hi) the wait after the first failure, doubling to hi; 100ms to a minute by default
Attempts(n) the tries in one visit before the effect has failed for good; 0, the default, is no bound
Otherwise(ev) fires ev, with the error's text, once the effect has failed for good

Permanent(err) marks an error trying again cannot get past: the effect is not run again. Once an effect has failed for good, by a Permanent error or by running out of Attempts, its Otherwise fires and the run goes on from where the machine takes it; the error is kept as the run's Cause. One the machine takes by an internal transition leaves the run waiting in the state, for a signal or its timer. With no Otherwise, or one the machine refuses, the run is Stuck: kept as it is, and shown as such, until Resume has its effect tried again, its attempts counted from none. A compensation that keeps failing has no automatic answer, and a run that is dropped is worse than one that waits for a person.

Signals

A signal is an event sent to a run from outside it: a payment confirmed, a person who approved, a parcel delivered. Accept names the events a saga takes from outside, and how a payload is written to the run's data; AcceptSignal takes one with no payload.

orders.
    Accept(paid, func(o *ordersv1.Order, p *paymentsv1.Paid) { o.PaymentId = p.Id }).
    AcceptSignal(cancelled)

err := orders.Signal(ctx, eng, "order-123", paid, &paymentsv1.Paid{Id: "pay-9"})
err = orders.Notify(ctx, eng, "order-123", cancelled) // no payload

A signal is kept with the run until its machine is in a state that takes it. In each state the machine takes the first signal waiting that the state accepts, so of the signals a state accepts, the earlier is taken first; one that comes early waits for its state while later ones go by. The effect of a visit runs before any signal moves the run on from it. A run holds MaxInbox (64) signals that wait, and Signal refuses more with ErrInboxFull; one that no state takes waits until the run ends, so a sender that repeats itself can fill it. A run that has ended refuses signals with ErrEnded, and an id with no run is ErrNoRun; an event the saga does not Accept is refused before it is sent.

A signal that cannot be delivered, with a payload that does not decode or whose taking panics, is dropped and logged, and the run stays as it was. One whose taking fails by the machine's action stays, those behind it waiting, and is tried again a Poll later.

Timers

orders.After(AwaitingPayment, 24*time.Hour, expired)

After fires an event on a run still in the same visit to the state once the time has passed since it entered it, between attempts if its effect is failing. The time is a field of the record, and the store finds the runs whose time has come, so a timer outlasts the engine that set it, and no process waits for it. It fires once: a machine that refuses it stays in the state with no timer, and one whose action fails is asked again a Poll later.

Sequence

The saga of the textbooks is steps done in order, each with what undoes it. Sequence builds one as a machine:

orders, err := saga.Sequence("order",
    saga.Step("reserve", reserve).Undo(release),
    saga.Step("charge", charge).Undo(refund).Pivot(),
    saga.Step("ship", ship),
)

A step's effect does not fire: returning nil is the step done. A step that fails for good 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 the run only goes forward, and a step that fails for good leaves it Stuck. Without a pivot, the last step is it. A step fails for good only by a Permanent error or by running out of its Attempts; with neither, it is tried until it works.

An undo must do nothing for a step that never happened, or the rest of one that happened in part. The run's stages are the steps' names, undo <name> while that step is undone, StageDone and StageFailed. example_test.go runs two orders through this sequence, one whose card is declined.

Engines

Start runs sagas on a node, from a store, until the node stops. Engines on several nodes that share a store share the runs.

Config
Store keeps the runs; required
Name the engine's process's registered name; saga by default
Poll how often the engine asks the store for runs that are due, and Wait about a run; 1s
Lease how long a claim holds a run without being renewed; 30s
Concurrency how many runs the engine works on at once; 64

The engine is a process. It claims the runs that have something to do on each tick, at once when a run is begun, signalled or resumed through it, and when a run it let go is due before the next tick. For each run it claims it spawns a process, labelled saga:<name>, which lives while the run has work and exits when it waits. A run at work is in the process list and the Inspector; a run that waits is a record and no more.

Each claim is for a lease, and raises the run's epoch. While the run is worked on, the engine renews the lease a quarter of it after the claim and after each renewal, and tries a renewal that failed again a sixteenth of it later, logging the first failure. It counts the lease by its own clock, from before it asked for the claim. Only the owner writes the run's state, and the store refuses a write with an older epoch, so an engine that was cut off, and whose lease another took, cannot save over it. An effect's ctx ends when the store says the run is another's, or when a quarter of the lease is left and no renewal got through, before another engine may have it; the new owner runs the effect again, with the same key.

When the node stops, a run's ctx is cancelled, nothing is saved, and its lease is let go, so another engine claims it at its next Poll, without waiting the lease out. A node that dies leaves the lease to run out.

Two versions of a program

In a rolling deploy the old program meets the new one's runs, in states its machine lacks. So a saga has a version, Definition.Version(v), and a run keeps the highest that began, signalled or worked on it. An engine claims only the runs its version reaches: the old program leaves alone what the new one has touched, and the new one takes up the old one's runs as they are. Raise the version when the machine gains a state, an event or a timer. A record a program cannot read though its version says it can is Stuck, with why.

Asking about a run

Get returns a run as it stands, Wait once it is Done or Stuck, both as a Snapshot: its state, data, status, the failures of the state's effect in this visit, the last error and the Cause. A run is Active while it goes on, at work or waiting for a signal, a timer or its next attempt. Store.List returns the records of a saga, by id.

Stores

Store is one interface: Create if absent, Claim, Save (fenced by the epoch), Renew, Signal, Resume, Get and List. The engine has no state of its own: ownership is a lease in the store, a timer is a field of the record, and nothing is published, so the store is the only part that must outlast a process.

saga.Memory() keeps the runs in memory: for tests, and for sagas that need not outlast their program. grpcproc/saga/postgres keeps them in PostgreSQL:

store, err := postgres.NewStore(db, "grpcproc_sagas") // db is a *sql.DB
err = store.Migrate(ctx)                               // or apply store.Schema() yourself
eng, err := saga.Start(node, saga.Config{Store: store}, orders)

A store of your own must pass sagatest.Store, which checks what an engine relies on:

func TestStore(t *testing.T) {
    sagatest.Store(t, func(t *testing.T) saga.Store { return openEmpty(t) })
}

Every method returns when its ctx ends, and Save and Renew with another epoch than the run's return ErrLost.

Not built yet

Stores in etcd and in a leader's checkpoint, a wrapper for participants that answers a repeated key and refuses a lower fence, steps that run side by side, retention of finished runs, and grpcprocctl saga. DESIGN.md has the reasons behind the design, and its open work the rest.

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

Examples

Constants

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

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

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

Functions

func KeyOf

func KeyOf(md grpcproc.Metadata) (key string, fence uint64, ok bool)

KeyOf reads the key and the fence a saga's effect sent with a message: what a participant keeps with what it did, to answer a repeat as it answered before, and to refuse a fence lower than it has seen for the key. ok is false for a message that no effect sent.

func Permanent

func Permanent(err error) error

Permanent marks err as one that trying again cannot get past: the effect that returns it is not run again. Its state's Otherwise fires, or the run is Stuck.

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
}

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

func Sequence[D proto.Message](name string, steps ...*StepSpec[D]) (*Definition[Stage, D], error)

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

func (d *Definition[S, D]) Begin(ctx context.Context, e *Engine, id string, data D) (bool, error)

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]) Get

func (d *Definition[S, D]) Get(ctx context.Context, e *Engine, id string) (Snapshot[S, D], error)

Get returns a run as it stands; ErrNoRun if there is none.

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]) Resume

func (d *Definition[S, D]) Resume(ctx context.Context, e *Engine, id string) error

Resume has a Stuck run tried again, from the state it is in.

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.

func (*Definition[S, D]) Wait

func (d *Definition[S, D]) Wait(ctx context.Context, e *Engine, id string) (Snapshot[S, D], error)

Wait returns a run once it is Done or Stuck, asking the store every Config.Poll until then, or until ctx ends. Like Get, it fails for a run whose record this program cannot read: one a later Version wrote.

type Effect

type Effect[S comparable, D proto.Message] func(ctx context.Context, r *Run[S, D]) error

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.

func Start

func Start(n *grpcproc.Node, cfg Config, sagas ...Saga) (*Engine, error)

Start runs sagas on n, from cfg.Store, until n stops. The engine is a process, named cfg.Name; each run it works on is one too, labelled "saga:" and the saga's name, for as long as the run has work.

func (*Engine) PID

func (e *Engine) PID() grpcproc.PID

PID is the engine's process.

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]) Attempt

func (r *Run[S, D]) Attempt() int

Attempt is which attempt of the effect this is in this visit, from 1.

func (*Run[S, D]) Fence

func (r *Run[S, D]) Fence() uint64

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

func (r *Run[S, D]) Fire[A any](ctx context.Context, ev fsm.Event[A], arg A) error

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]) ID

func (r *Run[S, D]) ID() string

ID is the run's, as Begin was given it.

func (*Run[S, D]) Key

func (r *Run[S, D]) Key() string

Key names this visit to this state, the same for every attempt: the idempotency key of what the effect asks of others.

func (*Run[S, D]) Process

func (r *Run[S, D]) Process() *grpcproc.Process[proto.Message]

Process is the process the run is worked on by: the Caller of the effect's sends and calls.

func (*Run[S, D]) State

func (r *Run[S, D]) State() S

State is the state the run is in.

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.

const (
	// StageDone ends a run whose every step was done.
	StageDone Stage = "done"
	// StageFailed ends a run whose steps were undone.
	StageFailed Stage = "failed"
)

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
)

func (Status) String

func (s Status) String() string

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

type StepSpec[D proto.Message] struct {
	// contains filtered or unexported fields
}

StepSpec is a step of a Sequence; see Step.

func Step

func Step[D proto.Message](name string, do Effect[Stage, D], opts ...StepOption) *StepSpec[D]

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

func (s *StepSpec[D]) Pivot() *StepSpec[D]

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.
	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.

func Memory

func Memory() Store

Memory returns a Store that keeps the runs in memory: for tests, and for sagas that need not outlast their program. Engines on several nodes of one program may share it.

Directories

Path Synopsis
postgres module
Package sagatest checks a saga.Store: what every implementation must do for an engine to be right on it.
Package sagatest checks a saga.Store: what every implementation must do for an engine to be right on it.

Jump to

Keyboard shortcuts

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