effects

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package effects runs server-side reactions to committed changes: webhooks, notifications, search indexing, agents — anything that should happen after a row is written and is not itself part of the write.

It is a consumer of the engine's change feed (server.Changes), packaged so that every adopter does not rebuild the same drain loop. What it adds over calling Changes directly is the bookkeeping that is easy to get subtly wrong: a durable position kept in the engine's own store, scheduling that wakes a workspace when it is written, backoff and health for a handler that keeps failing, and before-state for handlers that react to a transition rather than to a state.

The contract

Handlers run POST-COMMIT, on a background goroutine, never inside the write transaction they react to. Side effects must stay out of retried write closures, and Mutate is non-reentrant, so a handler is free to write back through the server API — it is not running inside anything.

Delivery is AT-LEAST-ONCE. A crash between a handler acting and its position committing redelivers the change, by design: it is the only recovery an outbound effect has, since there is no reconcile pass that can un-send an email or notice a webhook was never posted. Handlers must be idempotent. One that writes back should do so through server.MutateIdempotent keyed on the change (workspace, entity, key and seq identify it exactly).

Ordering is PER WORKSPACE, matching the feed. One consumer's handler runs serially for a workspace; different workspaces, and different consumers, proceed independently.

A handler that keeps failing WEDGES its own consumer for that workspace: the position does not advance, the change is retried with backoff, and everything behind it waits. This is deliberate — the alternative is skipping a change with no record and no repair path — and it is bounded to one consumer, since each has its own position. Watch Health to see it happen; nothing else will tell you.

What the feed can and cannot tell you

The feed reports STATE, not transitions, and coalesces by row: a handler sees the latest state of a row, never every intermediate write. Declaring Watch fields recovers the part of a transition that matters — what those fields held when this consumer last acted on the row — but it cannot recover writes that coalesced away in between.

It is also not an event log. Changes older than the workspace's tombstone horizon are collected, and a consumer that falls that far behind resets and resumes at the current sequence, having permanently missed what it never saw. An effect that must not miss anything needs the event persisted as a row through Mutate, where it syncs and is retained under normal row rules.

What it costs across many workspaces

A runtime is expected to carry a consumer across every workspace in a store, so nothing here is allowed to scale with how many of those there are.

Work is scheduled, not polled. Writing a workspace wakes it through the notifier's activity stream — one subscription for the whole store, not one per workspace — and a periodic sweep asks the engine which workspaces each consumer is behind on rather than opening a transaction per workspace to find out. What runs is bounded by a fixed pool of workers, and what is REMEMBERED is bounded by the work outstanding: a (consumer, workspace) pair costs memory while it has work queued, a pass running or a failure being retried, and is forgotten once it has drained, because everything durable about its progress is in the workspace's store. Tracked reports that resident set.

The two things that do scale with the store are a sweep's query, once per interval per consumer, and the storage the positions themselves occupy. Both are proportional to workspaces that have been written, neither is on the path a reaction takes, and GC collects the positions of consumers that have gone.

Several instances

Every pass runs under a per-(consumer, workspace) lease from the server's locker (server.Leases), so processes running the same consumer against one store divide the workspaces instead of each draining every one. The lease is advisory: it can be lost without the holder noticing, and a locker the runtime cannot reach makes the pass run unleased. Single delivery is therefore the common case, not a contract — at-least-once stands, and a rolling deploy or a lost lease can still hand one change to two processes. The dedup is only as wide as the locker's: with a process-local one (the fallback when the adapter is not a lease.Provider) concurrent processes still each fire the handler.

Index

Constants

This section is empty.

Variables

View Source
var ErrLeaseHeld = errors.New("effects: another drainer holds the lease for this consumer and workspace")

ErrLeaseHeld reports a pass that was skipped because another drainer — usually the same consumer on another node — holds the (consumer, workspace) lease and is mid-drain on the same work. Drain returns it; the background loops treat it as someone else's turn and leave the position, the health record and the backoff state alone. The position not advancing is what brings the workspace back on a later sweep if the holder dies without finishing.

Functions

func On

func On[T proto.Message](rt *Runtime, name string, fn func(context.Context, Event[T]) error, opts ...Option) error

On registers an in-process handler for one entity's changes, under a durable consumer name.

The entity comes from T, and the handler runs post-commit on a background goroutine, serially per workspace, at-least-once — see the package comment for what that obliges a handler to do. A handler returning an error wedges this consumer on that workspace until the change goes through; returning nil is how a handler declines a change it does not care about.

effects.On(rt, "slack-status", func(ctx context.Context, ev effects.Event[*issuev1.Issue]) error {
    if ev.Deleted || !ev.DidChange("status") || ev.After.GetStatus() != done {
        return nil
    }
    return postToSlack(ctx, ev.After)
}, effects.Watch("status"))

It is a package-level function rather than a method because Go has no generic methods; everything that does not need the type parameter is on Runtime.

Types

type Change

type Change struct {
	Workspace string
	Entity    string
	Key       string
	// Seq is the workspace sequence of the mutation that wrote this state.
	Seq uint64
	// Deleted reports a tombstone: the row is gone and After is nil.
	Deleted bool
	// Actor is who made the write, as the feed reports it — the row's LAST
	// writer, not the writer of every change that coalesced into this one. Use
	// it to suppress a consumer's own echo, not as an audit record; see
	// server.Change.Actor for the blind spot that comes with it.
	Actor storage.Actor
	// After is the row's new state, nil when Deleted and nil when the entity is
	// not registered on this server.
	After proto.Message
	// Before holds the watched fields as they stood when this consumer last
	// acted on the row, and nil when it never has (or declared no Watch
	// fields). Only watched fields are populated — it is a shadow of the row,
	// not the row.
	Before proto.Message
	// Changed names the watched fields whose value differs between Before and
	// After. Empty when nothing watched changed, and empty when there is no
	// Before to compare against.
	Changed []string
	// FirstSeen reports that this consumer held no shadow of the row, so there
	// was no before-state to diff and Changed is empty. It is the honest answer
	// to "did status become Done" when the consumer has never looked at the row:
	// not "no", but "unknown".
	//
	// It is true for a row created just now, for a row that existed before the
	// consumer was registered, and for the first sighting after a horizon reset
	// — the shadow is the consumer's memory, not the row's history, so the three
	// are indistinguishable. Handlers choose: skip them to react only to
	// observed transitions, or treat them as changes to react to what is
	// already there. Always false for a consumer that declared no Watch fields,
	// which keeps no memory to be first against.
	FirstSeen bool
}

Change is one committed change as an effect consumer sees it: the feed's change, plus whatever before-state the consumer declared an interest in. It is what a Sink receives; the typed Event handlers get is a view of it.

type Config

type Config struct {
	// Server is the engine whose change feed the runtime drains. Required.
	Server *server.Server
	// BatchSize bounds rows per change-feed page (default 256). A page is
	// delivered handler by handler and its bookkeeping commits once, so this is
	// also how much work one crash can redeliver.
	BatchSize int
	// Workers bounds how many drain passes run at once, across every consumer
	// and workspace (default 16). It is the runtime's only concurrency bound: a
	// sweep can queue as many pairs as there are workspaces with work, and what
	// keeps that from arriving at the storage layer all at once is the size of
	// this pool.
	//
	// Raise it for sinks that are slow and I/O-bound — a webhook consumer with
	// thousands of workspaces is limited by this number times the per-pass
	// latency, not by the engine. Lower it to leave more of the store's read
	// capacity to serving clients. Passes for one (consumer, workspace) never
	// overlap whatever this is set to.
	Workers int
	// Interval is how often the runtime sweeps for work it was not told about.
	// 0 means the default (15 seconds); negative disables the periodic sweep,
	// leaving activity signals and Kick as the only triggers. Start always
	// sweeps once, so a runtime finds what is already waiting for it however
	// this is set.
	//
	// The sweep is a safety net rather than the main path. A workspace that is
	// written wakes its consumers through the notifier, so reaction latency is
	// not this interval — but notifier signals carry no guarantee, and a
	// notifier that cannot report activity at all (see
	// server.SubscribeActivity) leaves the sweep as the only way to find work.
	// Disabling it is therefore a choice to rely on the notifier.
	Interval time.Duration
	// RetryMin and RetryMax bound per-consumer, per-workspace backoff after a
	// failed pass: the delay doubles from RetryMin (default 5s) up to RetryMax
	// (default 5m), jittered so consumers failing against the same destination
	// do not retry in lockstep. A negative RetryMin disables backoff, so every
	// trigger attempts.
	RetryMin time.Duration
	RetryMax time.Duration
	// OnHealth is called with a consumer's status after every pass, successful
	// or not. It is the surface that makes a wedged consumer visible; without it
	// (or without polling Health) a handler failing forever looks like a handler
	// with nothing to do.
	//
	// It runs on the worker's goroutine, inside the pass it describes, so it
	// must not block for long and must not call Drain for that same consumer and
	// workspace — the pass it would wait for is the one calling it. Health and
	// HealthAll are safe to call from it.
	OnHealth func(Health)
	// TracerProvider and MeterProvider are the OpenTelemetry providers the
	// runtime records on. nil means the global provider, which is no-op until
	// the process installs an SDK — the same fallback Logger makes to
	// slog.Default().
	//
	// Per-(consumer, workspace) health is deliberately NOT a metric: workspace
	// is an unbounded partition key, and a runtime is expected to carry a
	// consumer across every workspace in the store. Lag is exported as a
	// maximum per consumer; use OnHealth or HealthAll to find WHICH workspace
	// is behind. See docs/reference/telemetry.md.
	TracerProvider trace.TracerProvider
	MeterProvider  metric.MeterProvider
	// Workspaces enumerates the workspaces a sweep considers. Setting it
	// REPLACES the engine's pending-work query with a plain list, which is the
	// escape hatch for a runtime that has to cover workspaces the engine cannot
	// be asked about — and it costs a queued pass per workspace per sweep,
	// whether or not there is anything to do. Leave it nil unless that trade is
	// the one you want.
	//
	// It bounds the sweep only. A workspace that announces itself through the
	// notifier, or arrives via Kick, is drained either way.
	Workspaces func(ctx context.Context) ([]string, error)
	// Logger is the structured logger the background loops write to. Failures
	// are logged and never returned — a reaction failing must not take the
	// process down — with "component", "consumer" and "workspace" attributes.
	// nil means slog.Default().
	Logger *slog.Logger
	// HealthRetention bounds how many pairs that have drained and gone quiet
	// keep a Health entry (default 1024; negative keeps none). See Health for
	// what the runtime does and does not remember.
	HealthRetention int
}

Config wires a Runtime to a server.

type Event

type Event[T proto.Message] struct {
	Workspace string
	Entity    string
	Key       string
	// Seq is the workspace sequence of the mutation that wrote this state.
	// Together with Workspace, Entity and Key it identifies this delivery
	// exactly, which is what a handler writing back keys its idempotency on.
	Seq uint64
	// Deleted reports a tombstone: the row is gone and After is the zero value.
	// A handler that dereferences After must check this first.
	Deleted bool
	// Actor is the row's last writer — see Change.Actor for what that does and
	// does not answer.
	Actor storage.Actor
	// After is the row's new state; the zero value when Deleted.
	After T
	// Before holds the watched fields as they stood when this consumer last
	// acted on this row. It is the zero value when the consumer declared no
	// Watch fields, and when it has never acted on this row before — a first
	// sighting and a row that just came into existence are indistinguishable
	// here, because the shadow is this consumer's memory rather than the row's
	// history.
	//
	// Only watched fields are populated. Everything else is zero, which is not
	// a claim that it was empty.
	Before T
	// Changed names the watched fields whose value differs between Before and
	// After. Empty when nothing watched changed, and empty when there is no
	// Before to compare against — so "did this become Done" is DidChange plus a
	// check on After, never DidChange alone.
	Changed []string
	// FirstSeen reports that this consumer had no shadow of the row, so Changed
	// is empty because nothing was known, not because nothing moved. See
	// Change.FirstSeen for which situations produce it and what a handler does
	// about them.
	FirstSeen bool
}

Event is one committed change, typed to the entity its handler registered for. It is the typed view of Change.

func (Event[T]) DidChange

func (e Event[T]) DidChange(field string) bool

DidChange reports whether the named watched field is among Changed. The name is a field path as declared to Watch.

type Health

type Health struct {
	Consumer    string
	WorkspaceID string
	// LastAttempt is when the most recent pass ran; zero if none has.
	LastAttempt time.Time
	// LastSuccess is when a pass last completed without error; zero if never.
	LastSuccess time.Time
	// LastError is the most recent failure, cleared to nil by any success.
	LastError error
	// ConsecutiveFailures counts failures since the last success, and is the
	// backoff exponent.
	ConsecutiveFailures int
	// NextAttempt is the earliest time the runner will retry. Zero when not
	// backing off — after a success, or when backoff is disabled.
	NextAttempt time.Time
	// Position is the feed sequence the consumer has fully acted on, and Head
	// the workspace's current sequence. Head-Position is the lag: it stays put
	// while a consumer is wedged and grows as writes pile up behind it.
	Position uint64
	Head     uint64
}

Health is one consumer's status on one workspace, as of its last pass.

Failures inside the workers are logged and never returned — a reaction must not take the process down — so this is the surface that reports them. It is also the only thing that distinguishes a wedged consumer from an idle one: a handler failing forever and a handler with nothing to do both look like silence from the outside.

What is remembered

A pair the runtime is actively tracking always has an entry, which includes every FAILING pair: a consumer that cannot make progress stays visible for as long as that is true. A pair that drained its workspace and went quiet is forgotten — first from the runtime, then, once Config.HealthRetention newer pairs have finished behind it, from here.

So an absent entry means "not currently tracked, and not recently drained", which covers a workspace this consumer has never had work for and one it finished with long ago. It never means "failing" — that is the whole point of the asymmetry. Read Health to find what is wedged or behind, not to enumerate what is healthy.

func (Health) Lag

func (h Health) Lag() uint64

Lag is how many sequences behind the workspace head this consumer is.

type Option

type Option func(*registration)

Option configures a consumer registration.

func Watch

func Watch(fields ...string) Option

Watch declares the fields whose before-state a handler needs, as field paths ("status", "settings.color") with the same meaning masks have everywhere else in the engine — including keyed collection items ("tags.red") and oneof groups named by the group.

Declaring a field is what makes Event.Before and Event.Changed answer for it, and it is not free: the consumer keeps a shadow row per row it has seen, holding those fields' values, written on every delivery. Declaring nothing (the default) keeps no shadows at all and costs nothing, which is why after-state is the default and transitions are opt-in.

The shadow records what THIS consumer last acted on, not the row's previous version. Writes that coalesced into one change are invisible to it, and so is anything that happened while the consumer was resetting past the tombstone horizon. It answers "has this changed since I last looked", which is the question a reaction actually has.

type Runtime

type Runtime struct {
	// contains filtered or unexported fields
}

Runtime drains the change feed into registered consumers. Build one with New, register consumers, then Start it.

What it holds while running is proportional to the work outstanding, not to the store: a fixed pool of workers, one activity subscription, one sweep timer, and a pair of bookkeeping structs per (consumer, workspace) that has something to do. A workspace that is quiet costs nothing, and one that has drained is forgotten until it is written again.

func New

func New(cfg Config) (*Runtime, error)

New validates cfg and builds a Runtime with no consumers registered.

func (*Runtime) Close

func (rt *Runtime) Close() error

Close stops the workers and waits for in-flight passes to finish. It does not close the sinks — the caller owns those. Idempotent.

func (*Runtime) Drain

func (rt *Runtime) Drain(ctx context.Context, consumer, workspaceID string) error

Drain runs one pass for one consumer on one workspace, on the calling goroutine, and returns whatever stopped it. It is the manual entry point: Start drives this same pass from activity signals and the sweep, and both record Health, so a runtime driven by hand is exactly as observable as a started one.

Backoff is ignored — the caller asked — and, like a worker, it drains the feed to exhaustion before returning. It does honour the per-workspace ordering contract: if a worker is mid-pass on this same pair, Drain waits for it rather than running a second pass alongside it. It also honours the cross-process one, returning ErrLeaseHeld without draining when another process holds this consumer's lease on the workspace.

func (*Runtime) Health

func (rt *Runtime) Health(consumer, workspaceID string) (Health, bool)

Health returns one consumer's status on one workspace. The bool is false when the runtime holds no entry for that pair — see Health for what it keeps.

func (*Runtime) HealthAll

func (rt *Runtime) HealthAll() []Health

HealthAll returns every consumer/workspace pair the runtime holds an entry for, ordered by consumer then workspace.

func (*Runtime) Kick

func (rt *Runtime) Kick(workspaceID string)

Kick schedules a near-immediate pass for every consumer on the workspace, coalescing with one already pending. Wire it to whatever knows a workspace changed before the engine does; a workspace the runtime holds no state for starts here rather than waiting for the next sweep.

func (*Runtime) Register

func (rt *Runtime) Register(name string, sink Sink, entities ...proto.Message) error

Register wires a Sink to the changes of the given entities, under a durable consumer name. Passing no entities subscribes to every entity in the workspace, including ones registered later and ones this server cannot decode (whose changes arrive with a nil After).

The name is the identity of the consumer's durable position, so it must be stable across restarts: renaming a consumer does not carry its progress over, it starts a first run — which, against a workspace that has collected tombstones, means resuming at the current sequence rather than replaying history. Register before Start; registering afterwards is an error, because runners are built per consumer when they start.

func (*Runtime) Start

func (rt *Runtime) Start(ctx context.Context) error

Start launches the background loops and returns. Close (or cancelling ctx) stops everything.

Work reaches a consumer three ways, in descending order of how much they carry: the activity stream wakes the workspaces that are being written, a sweep finds work the stream did not carry (a signal lost, a node restarted, a consumer registered against a store with history), and Kick is the manual nudge. All three feed one queue drained by a fixed pool of workers.

Failures inside the workers are logged and retried with backoff — a reaction that fails must not take the process down — so Health is where a consumer that cannot make progress becomes visible.

func (*Runtime) Tracked

func (rt *Runtime) Tracked() int

Tracked reports how many (consumer, workspace) pairs the runtime is holding state for: those with work queued, a pass running, or a failure being retried. A pair that has drained its workspace is not among them.

It is the resident-set size — the number that stays flat as a store grows and climbs when consumers fall behind — so it belongs on a graph next to the lag in Health. A number that tracks the workspace count instead means work is arriving faster than the workers drain it.

type Sink

type Sink interface {
	Deliver(ctx context.Context, ch Change) error
}

Sink receives the changes one consumer is interested in. It is the seam between the runtime's bookkeeping and what actually reacts: the in-process handlers registered with On are one implementation, and publishing to a broker — where retry schedules, dead-lettering and fan-out become the broker's job rather than this package's — is the other one it is shaped for.

Deliver is called serially per workspace, in feed order, from the runtime's runner goroutine. Returning an error wedges the consumer on that workspace until the change goes through, so return nil for anything the sink means to skip. The runtime does not own the sink and never closes it.

type SinkFunc

type SinkFunc func(ctx context.Context, ch Change) error

SinkFunc adapts a plain function to Sink.

func (SinkFunc) Deliver

func (f SinkFunc) Deliver(ctx context.Context, ch Change) error

Jump to

Keyboard shortcuts

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