Documentation
¶
Overview ¶
Package eddy runs reconcile loops with Postgres as the source of truth, the queue and the leader election.
A Table maps a Go struct to a database table. Open returns a DB, which is used like a pgx pool; each Insert, Update, Delete and Exec through a Table enqueues the touched rows' reconciles in the same transaction. DB.Run is the controller: run it on any number of replicas, and the one that holds a Postgres advisory lock works the jobs on River. It loads each row, calls the function registered with Reconcile, and saves the status fields that function set; deleted rows go to the function registered with Teardown.
An object has at most one waiting reconcile job: a write or a resync uses the one that waits (writes bring it forward), and a Retry gives way to a job that already waits. A write while the object's reconcile runs still enqueues one more.
Kind and Handle are the smaller core underneath, for objects that are not one row of one table.
Example ¶
package main
import (
"context"
"log"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Anhui-tqhuang/eddy"
)
// Service is one row of the services table.
type Service struct {
ID uuid.UUID `db:",default"`
Image string
Phase string `db:",status"` // written only by the controller
}
// Services is shared by the API and the controller.
var Services = eddy.NewTable[Service]("services")
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, "postgres://localhost/app")
if err != nil {
log.Fatal(err)
}
db, err := eddy.Open(ctx, pool)
if err != nil {
log.Fatal(err)
}
// API: the write enqueues the reconcile itself.
svc := Service{Image: "web:1"}
if err := Services.Insert(ctx, db, &svc); err != nil {
log.Fatal(err)
}
// Controller: run on any number of replicas; one leads.
err = db.Run(ctx,
eddy.Reconcile(Services, func(ctx context.Context, svc *Service) error {
// Converge the outside world, then record the result.
svc.Phase = "ready"
return nil
}),
eddy.Teardown(Services, func(ctx context.Context, svc *Service) error {
// svc is the row as it was when deleted.
return nil
}),
)
if err != nil {
log.Fatal(err)
}
}
Output:
Index ¶
- Constants
- Variables
- func Attempt(ctx context.Context) int
- func BackoffAfter(first, longest time.Duration, attempt int) time.Duration
- func ColumnStatus[ID any](db Execer, cols StatusColumns) func(ctx context.Context, id ID, o Outcome) error
- func IsPermanent(err error) bool
- func Migrate(ctx context.Context, pool *pgxpool.Pool) error
- func Permanent(err error) error
- func Retry(after time.Duration) error
- func RetryDelay(err error) (time.Duration, bool)
- type AdvisoryLockOption
- type DB
- func (db *DB) Begin(ctx context.Context) (*Tx, error)
- func (db *DB) Enqueue(ctx context.Context, refs ...Ref) error
- func (db *DB) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
- func (db *DB) InTx(ctx context.Context, fn func(tx *Tx) error) error
- func (db *DB) Leading() bool
- func (db *DB) Pool() *pgxpool.Pool
- func (db *DB) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
- func (db *DB) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
- func (db *DB) Run(ctx context.Context, opts ...Option) error
- func (db *DB) WithTx(tx pgx.Tx) *Tx
- type Elector
- type Embedded
- type Execer
- type Handler
- type Kind
- type KindOption
- type Middleware
- type Option
- func Handle[ID any](k Kind[ID], f func(ctx context.Context, id ID) error) Option
- func OnLeadershipChange(f func(leading bool)) Option
- func Perform[T any](t Task[T], f func(ctx context.Context, payload T) error) Option
- func Reconcile[T any](t *Table[T], f func(ctx context.Context, row *T) error) Option
- func Record[ID any](k Kind[ID], f func(ctx context.Context, id ID, o Outcome) error) Option
- func Resync[ID any](k Kind[ID], every time.Duration, list func(ctx context.Context) ([]ID, error)) Option
- func Teardown[T any](t *Table[T], f func(ctx context.Context, row *T) error) Option
- func WithElector(e Elector) Option
- func WithLogger(l *slog.Logger) Option
- func WithMiddleware(m ...Middleware) Option
- func WithObjectLocks() Option
- func WithQueue(name string) Option
- func WithReconcileTimeout(d time.Duration) Option
- func WithResync(every time.Duration) Option
- func WithShutdownTimeout(d time.Duration) Option
- func WithWorkers(n int) Option
- func WithoutMigrate() Option
- type Outcome
- type Querier
- type Ref
- type SchedulingOption
- type Session
- type StatusColumns
- type Table
- func (t *Table[T]) Delete(ctx context.Context, s Session, id any) error
- func (t *Table[T]) Exec(ctx context.Context, s Session, sql string, args ...any) (int64, error)
- func (t *Table[T]) Get(ctx context.Context, q Querier, id any) (*T, error)
- func (t *Table[T]) Insert(ctx context.Context, s Session, row *T) error
- func (t *Table[T]) Name() string
- func (t *Table[T]) Of(id any) Ref
- func (t *Table[T]) SaveStatus(ctx context.Context, q Querier, row *T) error
- func (t *Table[T]) Select(ctx context.Context, q Querier, clause string, args ...any) ([]T, error)
- func (t *Table[T]) Update(ctx context.Context, s Session, row *T) error
- type TableOption
- type Task
- type TaskOption
- type Tx
Examples ¶
Constants ¶
const ( // DefaultQueue is the River queue eddy uses unless WithQueue says // otherwise. DefaultQueue = "eddy" // DefaultResync is how often every row of a reconciled table is enqueued // again unless WithResync says otherwise. DefaultResync = 10 * time.Minute )
Variables ¶
var ErrNotFound = errors.New("eddy: row not found")
ErrNotFound is returned when the row a Table call names does not exist.
var ErrUnknownKind = errors.New("eddy: no reconciler registered for kind")
ErrUnknownKind is returned (and retried) for a job whose kind has no reconciler, so jobs enqueued ahead of a rollout are not lost.
var ErrUnknownTask = errors.New("eddy: no Perform registered for task")
ErrUnknownTask is returned (and retried) for a task with no Perform registered, so tasks enqueued ahead of a rollout are not lost.
Functions ¶
func Attempt ¶
Attempt returns the attempt number (1 for the first try) of the reconcile running in ctx, or 0 outside one.
func BackoffAfter ¶
BackoffAfter is how long Backoff(first, longest) waits after the attempt-th attempt failed.
func ColumnStatus ¶
func ColumnStatus[ID any](db Execer, cols StatusColumns) func(ctx context.Context, id ID, o Outcome) error
ColumnStatus returns a Record func that updates status columns on the object's own row:
eddy.Record(Apps, eddy.ColumnStatus[uuid.UUID](pool, eddy.StatusColumns{
Table: "apps", Error: "reconcile_error", ReconciledAt: "reconciled_at",
}))
It panics if cols names no table or no column, which is a programming error.
func IsPermanent ¶
IsPermanent reports whether err was marked with Permanent.
func Migrate ¶
Migrate creates or upgrades River's tables in pool's current schema. Open does this for you; call it yourself only together with WithoutMigrate, to run migrations as a separate step. It is a no-op when they are current.
func Permanent ¶
Permanent marks err as not worth retrying: the job is cancelled instead of retried. Use it when the row itself is invalid and only a new write can fix it. Permanent(nil) is nil.
Types ¶
type AdvisoryLockOption ¶
type AdvisoryLockOption func(*advisoryLock)
AdvisoryLockOption configures AdvisoryLock.
func WithLockRetry ¶
func WithLockRetry(d time.Duration) AdvisoryLockOption
WithLockRetry sets how often a follower retries the lock and how often the leader checks its connection. The default is 2s.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is eddy's handle on your database, used by the API and the controller alike. Use it like a pgx pool: Exec, Query and QueryRow pass straight through. Writes made through a Table enqueue the row's reconcile themselves, and Run works those reconciles.
func Attach ¶
Attach returns a DB on pool that enqueues through a River client you already run, instead of opening its own. It does not migrate. See Embed for working eddy's jobs on that client too.
func Open ¶
Open returns a DB on pool. Unless WithoutMigrate is given, it first creates or upgrades River's tables, which hold eddy's jobs.
func (*DB) Begin ¶
Begin starts a transaction. Table writes made through the returned Tx commit or roll back with it, jobs included.
func (*DB) Enqueue ¶
Enqueue schedules a reconcile of each ref. Table writes do this for you; it is for kinds registered with Handle, or to nudge a row by hand.
func (*DB) Exec ¶
Exec runs sql on the pool. It enqueues nothing; see Table.Exec for writes to a reconciled table.
func (*DB) InTx ¶
InTx runs fn in a transaction: it commits when fn returns nil and rolls back otherwise.
func (*DB) Leading ¶
Leading reports whether Run on this DB currently leads. Wire it to a readiness probe if only the leader should count as ready.
func (*DB) Run ¶
Run is the controller: it campaigns for leadership and, while leading, works the queue with the reconcilers given in opts. Start it on any number of replicas; only the leader reconciles. When leadership is lost it drains and campaigns again. It returns nil once ctx is done and in-flight reconciles have finished or timed out.
db.Run(ctx, eddy.Reconcile(Apps, reconcileApp), eddy.Teardown(Apps, teardownApp), )
type Elector ¶
type Elector interface {
// Campaign blocks until this replica leads or ctx is done. The returned
// context is cancelled when leadership is lost. The controller calls
// release once its reconcilers have stopped; only then may another
// replica take over.
Campaign(ctx context.Context) (lead context.Context, release func(), err error)
}
Elector decides which replica works the queue. Only the leader runs reconcilers, so one object is never reconciled by two replicas at once.
func AdvisoryLock ¶
func AdvisoryLock(pool *pgxpool.Pool, name string, opts ...AdvisoryLockOption) Elector
AdvisoryLock returns an Elector backed by a session-level Postgres advisory lock keyed on name. The leader holds one pool connection for as long as it leads; if that connection fails, leadership is lost. It needs nothing but the database eddy already uses.
type Embedded ¶
type Embedded struct {
// contains filtered or unexported fields
}
Embedded plugs eddy into a River client you already run, instead of DB.Run starting its own. Register its workers, queue and periodic jobs on your client, then get the DB from it:
ed, _ := eddy.Embed(pool, eddy.Reconcile(Apps, reconcileApp))
workers := river.NewWorkers()
ed.AddWorkers(workers)
// ... your own workers ...
queues := ed.Queues()
queues[river.QueueDefault] = river.QueueConfig{MaxWorkers: 50}
client, _ := river.NewClient(riverpgxv5.New(pool), &river.Config{
Queues: queues,
Workers: workers,
PeriodicJobs: ed.PeriodicJobs(),
})
db := ed.DB(client)
There is no eddy leader election here: every process that lists eddy's queues works them. Reconciles of one object are serialised within a process; add WithObjectLocks to serialise them across processes too. Resync jobs run on River's own elected leader.
func Embed ¶
Embed returns eddy's workers for use with your own River client. WithElector, OnLeadershipChange, WithShutdownTimeout and WithoutMigrate do not apply: your client owns its lifecycle and you run River's migrations.
func (*Embedded) AddWorkers ¶
AddWorkers registers eddy's workers on ws.
func (*Embedded) PeriodicJobs ¶
func (e *Embedded) PeriodicJobs() []*river.PeriodicJob
PeriodicJobs are the resync jobs; add them to your client's PeriodicJobs.
type Execer ¶
type Execer interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}
Execer runs a statement. *pgxpool.Pool, *pgx.Conn and pgx.Tx satisfy it.
type Kind ¶
type Kind[ID any] struct { // contains filtered or unexported fields }
Kind names a type of object that eddy reconciles, together with the Go type of its identifier. It is the layer under Table, for objects that are not one row of one table. Declare one per resource type and share it between the API (which enqueues) and the controller (which handles):
var Apps = eddy.NewKind[uuid.UUID]("app")
ID must round-trip through encoding/json; uuid.UUID, int64 and string all do.
type KindOption ¶
type KindOption interface {
// contains filtered or unexported methods
}
KindOption configures NewKind.
type Middleware ¶
Middleware wraps every reconcile, for every kind: the place for metrics, tracing, logging or panic recovery. The first middleware given is the outermost. Attempt(ctx) reports the attempt number inside it.
func timing(next eddy.Handler) eddy.Handler {
return func(ctx context.Context, ref eddy.Ref) error {
start := time.Now()
err := next(ctx, ref)
observe(ref.Kind(), time.Since(start), err)
return err
}
}
An error for which RetryDelay reports true is a requested retry, not a failure.
type Option ¶
type Option func(*config) error
Option configures Open and DB.Run. Open needs only the connection options (WithQueue, WithLogger, WithoutMigrate); everything else matters to Run. Options given to Open also apply to Run.
func Handle ¶
Handle registers f as the reconciler for kind k. f gets only the id: it loads what it needs, must be idempotent, and treats a missing object as "tear everything down". Returning an error retries with backoff; see Retry and Permanent. For a table, use Reconcile.
func OnLeadershipChange ¶
OnLeadershipChange calls f with true when this replica starts leading and with false when it stops. f must not block. It applies to DB.Run only; with Embed, leadership is River's.
func Perform ¶
Perform registers f as what performs task t. f gets the payload it was enqueued with. Returning an error tries again after the task's Backoff, until its Attempts are used; Permanent gives up at once, and Retry waits without using an attempt.
func Reconcile ¶
Reconcile registers f as the reconciler for t's rows. eddy loads the row before each call, so f always sees current state; a row that no longer exists is skipped (see Teardown). Whatever f assigns to row's status fields is saved when it returns, on success and on failure alike.
f must be idempotent. Returning an error retries with backoff; see Retry and Permanent. Every row is also reconciled again periodically (see WithResync).
func Record ¶
Record calls f after every reconcile attempt of kind k, success or failure, so the outcome can be written back where the API can show it. A failing f is logged and does not fail the reconcile. ColumnStatus builds an f for the common case. It is for kinds registered with Handle; a Table records the same through its "error" and "reconciled" fields.
func Resync ¶
func Resync[ID any](k Kind[ID], every time.Duration, list func(ctx context.Context) ([]ID, error)) Option
Resync enqueues every object list returns, once when Run starts leading and then every interval. Tables resync by themselves; this is for kinds registered with Handle.
func Teardown ¶
Teardown registers f to run when a row of t is deleted through the Table (Delete, or Exec with a DELETE). row is the row as it was when deleted, so f knows what to tear down without a soft-delete column. It is retried like a reconcile until it returns nil.
func WithElector ¶
WithElector sets how replicas decide which one works the queue. The default is a Postgres advisory lock named after the queue.
func WithLogger ¶
WithLogger sets the logger; the default is slog.Default().
func WithMiddleware ¶
func WithMiddleware(m ...Middleware) Option
WithMiddleware appends middleware around every reconcile.
func WithObjectLocks ¶
func WithObjectLocks() Option
WithObjectLocks makes eddy take a Postgres advisory lock per object for the length of each reconcile, so no two processes ever reconcile one object at once, even across a leadership handoff or when several processes work the queue (see Embed). Each running reconcile holds one pool connection while it runs, on top of whatever the reconciler uses: size the pool for at least twice the worker count.
Without it, eddy serialises reconciles of an object within one process.
func WithQueue ¶
WithQueue sets the River queue eddy inserts into and works. The default is DefaultQueue. Every process must agree on it.
func WithReconcileTimeout ¶
WithReconcileTimeout bounds a single reconcile. The default is River's job timeout (one minute).
func WithResync ¶
WithResync sets how often every row of each reconciled table is enqueued again, to repair drift and catch rows changed outside eddy. The default is DefaultResync; zero turns it off.
func WithShutdownTimeout ¶
WithShutdownTimeout bounds how long Run waits for in-flight reconciles when it stops or loses leadership, before cancelling them. The default is 30s.
func WithWorkers ¶
WithWorkers sets how many reconciles run at once on the shared queue. The default is 10. Kinds declared with MaxWorkers run on top of that, each in its own queue.
func WithoutMigrate ¶
func WithoutMigrate() Option
WithoutMigrate stops Open from creating or upgrading River's tables; Open then fails when they are missing or out of date. Use it when migrations run as a separate step (see Migrate).
type Outcome ¶
type Outcome struct {
// Err is the reconciler's error; nil on success and on a Retry.
Err error
// RetryAfter is positive when the reconciler asked for a Retry: it is
// not done, but has not failed either.
RetryAfter time.Duration
// Attempt is 1 for the first try.
Attempt int
// Final is true when no retry follows: success, a Permanent error, or
// the last allowed attempt.
Final bool
// Duration is how long Reconcile ran.
Duration time.Duration
}
Outcome describes one finished reconcile attempt, for Record.
type Querier ¶
type Querier interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}
Querier runs SQL. *pgxpool.Pool, pgx.Tx, *DB and *Tx all satisfy it; Table reads accept any of them.
type Ref ¶
type Ref struct {
// contains filtered or unexported fields
}
Ref points at one object: a kind name and an encoded identifier. Build one with Kind.Of or Table.Of. The zero Ref is invalid.
func (Ref) Deleted ¶
Deleted reports whether the reference is to a deleted table row, whose reconcile is a teardown. It is set only on the Ref middleware receives.
type SchedulingOption ¶
type SchedulingOption interface {
KindOption
TableOption
TaskOption
}
SchedulingOption is accepted by NewKind, NewTable and NewTask: see Priority and MaxWorkers.
func MaxWorkers ¶
func MaxWorkers(n int) SchedulingOption
MaxWorkers caps how many reconciles of this kind run at once, by giving the kind a queue of its own, separate from the shared one sized by WithWorkers. A slow or noisy kind then cannot crowd out the others, and the others cannot starve it.
func Priority ¶
func Priority(n int) SchedulingOption
Priority sets how urgently this kind's reconciles are picked up relative to other kinds sharing a queue: 1 (the default) is most urgent, 4 least. Use a higher number for bulk or background kinds.
type Session ¶
type Session interface {
Querier
// contains filtered or unexported methods
}
Session is where Table writes happen: a *DB (each write runs in its own transaction) or a *Tx (writes join that transaction). Either way the row and its reconcile job are written atomically.
type StatusColumns ¶
type StatusColumns struct {
// Table may be schema-qualified ("app.apps").
Table string
// ID is the key column matched against the object's ID; default "id".
ID string
// Error (text) receives the error message, or NULL on success.
Error string
// ReconciledAt (timestamptz) is set to now() on success.
ReconciledAt string
// AttemptedAt (timestamptz) is set to now() on every attempt.
AttemptedAt string
// MaxErrorLen truncates the message, in bytes; default 1024.
MaxErrorLen int
}
StatusColumns names where ColumnStatus writes. Table is required, along with at least one of Error, ReconciledAt and AttemptedAt; empty columns are not written.
type Table ¶
type Table[T any] struct { // contains filtered or unexported fields }
Table maps Go struct T to a database table. Writes through it enqueue the row's reconcile in the same transaction, so there is no enqueue call to remember:
type App struct {
ID uuid.UUID `db:",default"` // filled by the database when zero
Image string
Phase string `db:",status"` // written only by the controller
}
var Apps = eddy.NewTable[App]("apps")
A column is named by the `db` tag, or by the snake_case field name without one; `db:"-"` skips a field. Options follow the name:
- default: left out of Insert when zero, so the database default applies
- status: never written by Insert or Update; saved after each reconcile
- error: a status string that eddy sets to the last reconcile error
- reconciled: a status time that eddy sets on each successful reconcile
Fields must round-trip through encoding/json, which is how a deleted row reaches Teardown.
func NewTable ¶
func NewTable[T any](name string, opts ...TableOption) *Table[T]
NewTable returns the Table for struct T stored in the table called name (optionally schema-qualified). It panics when T cannot be mapped: these are programming errors, caught at start-up.
func (*Table[T]) Delete ¶
Delete removes the row with key id and enqueues its teardown: the row's last state travels with the job, and the function registered with Teardown receives it. It returns ErrNotFound when no row has that key.
func (*Table[T]) Exec ¶
Exec runs a free-form INSERT, UPDATE or DELETE on this table and enqueues every row it touched, in the same transaction. Use it for bulk changes and anything Insert, Update and Delete cannot express:
Apps.Exec(ctx, db, "UPDATE apps SET image = $1 WHERE team_id = $2", image, team)
It returns the number of rows touched. eddy learns which rows those were by adding a RETURNING clause, so sql must not have one, must be a single statement, and must not alias the table.
func (*Table[T]) Insert ¶
Insert adds row and enqueues its reconcile. Fields tagged "default" are left to the database when zero. row is refreshed from the database, so generated keys and defaults are filled in on return.
func (*Table[T]) Of ¶
Of returns a reference to the row with key id, for DB.Enqueue. It panics when id is not of the key's type.
func (*Table[T]) SaveStatus ¶
SaveStatus writes row's status columns, and nothing else, to the row with the same key. It enqueues nothing. Reconcile already does this when the reconciler returns; call it yourself only to save progress midway.
type TableOption ¶
type TableOption interface {
// contains filtered or unexported methods
}
TableOption configures NewTable.
func KindName ¶
func KindName(name string) TableOption
KindName sets the kind name used in jobs; the default is the table name.
type Task ¶
type Task[T any] struct { // contains filtered or unexported fields }
Task names a kind of one-off job that carries its own payload: send an email, report a usage event, deliver an audit record. Where a Kind or a Table names an object to converge, and two writes of one object are one reconcile, every task enqueued is performed, each with its payload. Declare one per kind of task and share it between whoever enqueues and the controller:
var Emails = eddy.NewTask[Email]("email", eddy.Attempts(10))
T must round-trip through encoding/json.
func NewTask ¶
func NewTask[T any](name string, opts ...TaskOption) Task[T]
NewTask returns the Task called name. Names must be unique within a controller, and must not be empty.
type TaskOption ¶
type TaskOption interface {
// contains filtered or unexported methods
}
TaskOption configures NewTask: Priority, MaxWorkers, Attempts and Backoff.
func Attempts ¶
func Attempts(n int) TaskOption
Attempts sets how many times a task is tried before it is given up on. The default is River's (25). Retry does not use an attempt.
func Backoff ¶
func Backoff(first, longest time.Duration) TaskOption
Backoff sets how long a task waits after an attempt fails: first after the first, twice as long after each one after that, never more than longest. The default is River's backoff, which grows with the fourth power of the attempt.