eddy

package module
v0.0.0-...-1a2ecfd Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 21 Imported by: ? modules, 0 packages

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

eddy

eddy

Reconcile loops for Go, with Postgres as the only moving part.
Built on River.


Status: pre-alpha. The API may still change.

An eddy is a current that curls back on itself inside a river. eddy is the reconcile loop that runs on River.

Your API owns plain Postgres rows: the desired state. eddy turns those rows into real resources somewhere else, such as cloud resources, Kubernetes objects, DNS records or third-party SaaS state, and keeps them converged. It's the controller pattern without a Kubernetes API server. Postgres stores the state, carries the queue and elects the leader.

Languages

eddy is available for Go and Python. Each has its own usage documentation.

Language Package Documentation
Go github.com/Anhui-tqhuang/eddy This README
Python eddy-pg on PyPI eddy-python README

The two store jobs in the same format and share the leader lock, so they can be mixed on one database: a Python API can feed a Go controller, or the reverse. The rest of this page covers Go.

Install

go get github.com/Anhui-tqhuang/eddy

Quick start

Describe the table as a Go struct, then use one eddy.DB on both sides.

type App struct {
    ID    uuid.UUID `db:",default"`  // filled by the database when zero
    Name  string
    Image string
    Phase string    `db:",status"`   // written only by the controller
}

var Apps = eddy.NewTable[App]("apps")

db, _ := eddy.Open(ctx, pool)        // creates eddy's job tables if needed

API: write through the table. The reconcile is enqueued for you, in the same transaction as the row.

app := App{Name: "web", Image: "web:1"}
Apps.Insert(ctx, db, &app)           // app.ID is filled in
app.Image = "web:2"
Apps.Update(ctx, db, &app)           // never touches phase
Apps.Delete(ctx, db, app.ID)

Controller: run it on any number of replicas. One is elected leader and does the work.

db.Run(ctx,
    eddy.Reconcile(Apps, func(ctx context.Context, app *App) error {
        if err := deploy(ctx, app); err != nil {
            return err               // retried with backoff
        }
        app.Phase = "ready"          // saved when the function returns
        return nil
    }),
    eddy.Teardown(Apps, func(ctx context.Context, app *App) error {
        return undeploy(ctx, app)    // app is the row as it was when deleted
    }),
)

If a write commits, its reconcile is guaranteed to happen. If it rolls back, nothing happens. There is no enqueue call to remember, no dual write and no outbox table.

One waiting job per object. A write to an object whose reconcile already waits to run uses that job, and brings it forward if it waits for later (a Retry, or backoff after an error); the reconcile still runs after the write. A write while the object's reconcile is running does enqueue, since that run may have read the row before the write. A resync skips objects whose job already waits, and a reconcile that asks for a Retry while another job for its object waits finishes instead. So an object that keeps asking for a Retry has one retry loop, however many resyncs and writes come by. Deletions are never merged.

Writing rows

eddy.DB is used like a pgx pool, and *eddy.Tx has every pgx.Tx method.

got, err := Apps.Get(ctx, db, id)                          // eddy.ErrNotFound when missing
list, _ := Apps.Select(ctx, db, "WHERE name = $1", "web")
db.Query(ctx, "SELECT ...")                                // anything else: plain pgx

Transactions. Table writes take the DB (each write is its own transaction) or a Tx (writes join it).

db.InTx(ctx, func(tx *eddy.Tx) error {
    if err := Teams.Insert(ctx, tx, &team); err != nil {
        return err
    }
    return Apps.Insert(ctx, tx, &app)    // both rows and both jobs, or none
})

tx := db.WithTx(pgxTx)                   // join a pgx transaction you already hold

Free-form SQL. Table.Exec runs your own INSERT, UPDATE or DELETE and enqueues every row it touched. Use it for bulk changes and anything the typed methods can't express.

n, err := Apps.Exec(ctx, db, "UPDATE apps SET image = $1 WHERE team_id = $2", image, teamID)

eddy finds the touched rows by adding a RETURNING clause, so the statement must be a single statement without its own RETURNING and without a table alias.

What is not captured. db.Exec, psql and other services write rows without enqueueing anything. Those rows are picked up by the periodic resync, or at once if you call db.Enqueue(ctx, Apps.Of(id)).

Reconciling

  • The row is always fresh. eddy loads it before each call, so the function sees current state however stale the job is. It must be idempotent.
  • Status is saved for you. Whatever the function assigns to status fields is written back when it returns, whether it succeeded or failed. Apps.SaveStatus(ctx, db, app) saves midway through a long reconcile.
  • Errors retry. A returned error retries with backoff. eddy.Permanent(err) stops retrying, for a row only a new write can fix. eddy.Retry(15*time.Second) checks again later without counting as a failure, for polling something that is still converging.
  • Deletes carry the row. Delete sends the row's last state with the job, and Teardown receives it. You don't need a soft-delete column to know what to tear down. Teardowns retry like reconciles.
  • Every row is re-checked. Each table is resynced every 10 minutes by default, and when a replica becomes leader. eddy.WithResync(d) changes the interval; zero turns it off.
  • No overlap per object. One row is never reconciled twice at once.

eddy can also record how each reconcile went, with two more field tags:

type App struct {
    ...
    Error        *string    `db:"reconcile_error,error"`  // last error; cleared on success
    ReconciledAt *time.Time `db:",reconciled"`            // time of the last success
}

Soft delete

eddy has no soft-delete setting. A soft delete is an ordinary update that the reconciler acts on. Use it when the row should stay visible while its resources are torn down, or when a failed teardown should show in the row's status columns.

type App struct {
    ...
    DeletedAt *time.Time             // set by the API; an ordinary column
}

// API: mark the row. Its reconcile is enqueued like any other write.
Apps.Exec(ctx, db, "UPDATE apps SET deleted_at = now() WHERE id = $1", id)

// Controller: tear down, then remove the row.
eddy.Reconcile(Apps, func(ctx context.Context, app *App) error {
    if app.DeletedAt != nil {
        if err := undeploy(ctx, app); err != nil {
            return err               // retried; the row and its error stay visible
        }
        _, err := db.Exec(ctx, "DELETE FROM apps WHERE id = $1", app.ID)
        return err
    }
    ...
})
  • Remove the row with plain db.Exec. It enqueues nothing, so the table needs no Teardown. Apps.Delete would enqueue a teardown for work that is already done.
  • The teardown branch must be idempotent. Until the row is removed, the resync keeps reconciling it.
  • To keep the row for good, skip the final DELETE, record that teardown finished in a status field, and return early when it is set.
  • Filter your own reads. Get and Select return soft-deleted rows; add deleted_at IS NULL where the API should hide them.

Field tags

Tag Meaning
db:"col" Column name. Without one, the snake_case field name (CreatedAt is created_at)
db:",default" Left out of Insert when zero, so the database default applies
db:",status" Never written by Insert or Update; saved after each reconcile
db:",error" A status string or *string that eddy sets to the last reconcile error
db:",reconciled" A status time.Time or *time.Time that eddy sets on each success
db:"-" Not a column

The key column is id unless you pass eddy.Key("uid"). eddy.KindName("app") names the job kind differently from the table. Embedded structs are flattened. Fields must survive encoding/json, which is how a deleted row reaches Teardown.

How it works

 Table.Insert/Update/Delete/Exec ──tx──▶ your row + river_job ──▶ leader ──▶ Reconcile(row) ──▶ outside world
                                                                    ▲             │
                                                   resync every N ──┘   status fields on your row ◀┘
  • Jobs carry a pointer, not data. A job holds only the kind and the key, and the row is reloaded before every reconcile. The one exception is a delete, which carries the deleted row.
  • One leader, elected in Postgres. Replicas compete for a session-level advisory lock. The leader holds one pooled connection, and if that connection drops, the lease is gone. On a clean handoff the old leader drains its in-flight reconciles before it releases the lock. If its connection drops instead, Postgres frees the lock at once while the old leader is still draining. Add WithObjectLocks() to rule out overlap even then. You don't need Kubernetes, etcd or ZooKeeper.
  • Jobs live in River's tables. Open creates and upgrades them. To run migrations as a separate step, call eddy.Migrate(ctx, pool) there and pass eddy.WithoutMigrate() to Open.

Without a table

Under the table layer is a smaller core for objects that aren't one row of one table. Declare a kind, enqueue it yourself, and load what you need in the handler:

var Clusters = eddy.NewKind[uuid.UUID]("cluster")   // any JSON-encodable ID

db.InTx(ctx, func(tx *eddy.Tx) error {
    // ... your own SQL on tx ...
    return tx.Enqueue(ctx, Clusters.Of(clusterID))
})

db.Run(ctx,
    eddy.Handle(Clusters, func(ctx context.Context, id uuid.UUID) error { ... }),
    eddy.Resync(Clusters, 10*time.Minute, listClusterIDs),
    eddy.Record(Clusters, eddy.ColumnStatus[uuid.UUID](db, eddy.StatusColumns{
        Table: "clusters", Error: "reconcile_error", ReconciledAt: "reconciled_at",
    })),
)

Record runs after every attempt with an Outcome (error, attempt number, duration, whether a retry follows). ColumnStatus writes the usual columns; pass your own function for anything else.

Tasks

A reconcile converges an object, and two writes of one object are one reconcile. Some work is not like that: an email, a usage event, an audit record to deliver. A task is a one-off job that carries its own payload, and every one enqueued is performed:

type Email struct{ To, Subject string }

var Emails = eddy.NewTask[Email]("email",
    eddy.Attempts(10),                        // give up after 10 failed attempts (River's default is 25)
    eddy.Backoff(5*time.Second, 5*time.Minute), // 5s after the first failure, doubling, at most 5m
)

db.InTx(ctx, func(tx *eddy.Tx) error {
    // ... your own writes on tx ...
    return Emails.Enqueue(ctx, tx, Email{To: "ada@example.com", Subject: "Welcome"})
})

db.Run(ctx, eddy.Perform(Emails, func(ctx context.Context, e Email) error { ... }))
  • Enqueued with what it belongs to. On a *Tx the task is performed only once the transaction commits, and never when it rolls back. On a *DB it is enqueued by itself.
  • What Perform returns decides what happens next. nil is done. An error is tried again after the task's Backoff, until its Attempts are used. eddy.Permanent(err) gives up at once. eddy.Retry(d) waits d without using an attempt.
  • MaxWorkers and Priority work on tasks too. A task with MaxWorkers(n) gets a queue of its own, eddy-task-<name>.
  • A task with no Perform waits. It is retried like any failure, so tasks enqueued ahead of a rollout are not lost.
  • Run can perform only tasks, with no table or kind to reconcile.

Scheduling

Declare how a kind is scheduled where you declare the table or kind, so the API and the controller agree:

var Reports = eddy.NewTable[Report]("reports",
    eddy.MaxWorkers(2),   // at most 2 report reconciles at once
    eddy.Priority(3),     // 1 (default) is most urgent, 4 least
)
  • MaxWorkers(n) gives the kind a queue of its own with n workers, on top of the shared pool sized by WithWorkers. A slow kind can't crowd out the others, and the others can't starve it.
  • Priority(n) orders kinds that share a queue. Lower-priority reconciles are picked up only when nothing more urgent is waiting.

Both also work on eddy.NewKind.

Metrics and tracing

Ready-made instrumentation lives in two small modules, so the core depends on neither OpenTelemetry nor Prometheus.

OpenTelemetry (go get github.com/Anhui-tqhuang/eddy/eddyotel): a span and a duration measurement per reconcile.

db.Run(ctx, ...,
    eddy.WithMiddleware(eddyotel.Middleware()),   // uses the global providers by default
)

Spans are named eddy.reconcile <kind> or eddy.teardown <kind> and carry eddy.kind, eddy.id, eddy.attempt and eddy.outcome. The histogram is eddy.reconcile.duration, in seconds. Spans the reconciler starts become children.

Prometheus (go get github.com/Anhui-tqhuang/eddy/eddyprom):

m, _ := eddyprom.New(prometheus.DefaultRegisterer)

db.Run(ctx, ...,
    eddy.WithMiddleware(m.Middleware()),
    eddy.OnLeadershipChange(m.SetLeading),
)
Metric Labels
eddy_reconcile_duration_seconds kind, operation, outcome Histogram of reconcile and teardown durations
eddy_reconciles_in_flight kind Reconciles running now
eddy_leader — 1 while this replica leads

In both, the outcome is ok, retry (asked to be checked again later), error (will be retried) or permanent.

Your own middleware wraps every reconcile and teardown the same way:

func logging(next eddy.Handler) eddy.Handler {
    return func(ctx context.Context, ref eddy.Ref) error {
        err := next(ctx, ref)
        slog.InfoContext(ctx, "reconciled", "kind", ref.Kind(), "id", ref.ID(),
            "attempt", eddy.Attempt(ctx), "teardown", ref.Deleted(), "error", err)
        return err
    }
}

The first middleware given is the outermost. db.Leading() reports leadership, for a readiness probe.

Already running River?

Embed hands eddy's workers to your River client instead of Run starting its own:

ed, _ := eddy.Embed(pool, eddy.Reconcile(Apps, reconcileApp))

workers := river.NewWorkers()
ed.AddWorkers(workers)
river.AddWorker(workers, &YourOtherWorker{})

queues := ed.Queues()              // eddy's queues and their sizes
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)                // the same eddy.DB, enqueueing through your client

An API-only process uses eddy.Attach(pool, client) to get the DB. eddy doesn't elect a leader in this mode: every process whose client lists ed.Queues() works them. List them on one process only, or add WithObjectLocks() so processes never overlap on a row. Resync jobs run on River's own elected leader, and you run River's migrations.

Options

Option Default
Reconcile(table, f) — Reconcile a table's rows
Teardown(table, f) — Tear down a table's deleted rows
WithResync(every) 10m How often every row is re-checked; 0 turns it off
Handle(kind, f) — Reconcile a bare kind
Resync(kind, every, list) off Periodically enqueue the listed objects of a bare kind
Record(kind, f) off Record each attempt of a bare kind (see ColumnStatus)
WithWorkers(n) 10 Concurrent reconciles on the shared queue; kinds with MaxWorkers run on top
WithElector(e) advisory lock Leader election; Solo() for a single replica
WithObjectLocks() off Per-object advisory lock across processes; holds one pool connection per running reconcile
WithReconcileTimeout(d) 1m Bound on one reconcile
WithShutdownTimeout(d) 30s Drain time on stop or lost leadership
WithMiddleware(m...) — Wrap every reconcile (metrics, tracing, logging)
OnLeadershipChange(f) — Called on gaining or losing leadership
WithQueue(name) eddy River queue; set it on Open
WithoutMigrate() — Don't create River's tables in Open
WithLogger(l) slog.Default()

Options can go to Open or to Run; those given to Open apply to every Run on that DB.

Development

make test      # unit tests
make test-db   # plus integration tests against Postgres
               # (TEST_DB_URL=postgres://localhost:5432/eddy_test?sslmode=disable)

River version

eddy is built on River v0.51.2, pinned in go.mod here and in the eddyotel and eddyprom modules.

Keep this repository and eddy-python on the same River version. The two libraries share River's tables, so they must agree on the table layout.

When upgrading River:

  1. Update go.mod in this repository and in eddyotel and eddyprom, then run make test-db.
  2. Upgrade eddy-python in the same change window. It bundles River's migration files and works the job table with its own SQL, so it may need code changes as well as new files; see "River version" in its README.
  3. Change the version stated in this section.

License

MIT. eddy is built on River, which is licensed under MPL-2.0.

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

Index

Examples

Constants

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

View Source
var ErrNotFound = errors.New("eddy: row not found")

ErrNotFound is returned when the row a Table call names does not exist.

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

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

func Attempt(ctx context.Context) int

Attempt returns the attempt number (1 for the first try) of the reconcile running in ctx, or 0 outside one.

func BackoffAfter

func BackoffAfter(first, longest time.Duration, attempt int) time.Duration

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

func IsPermanent(err error) bool

IsPermanent reports whether err was marked with Permanent.

func Migrate

func Migrate(ctx context.Context, pool *pgxpool.Pool) error

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

func Permanent(err error) error

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.

func Retry

func Retry(after time.Duration) error

Retry returns an error that reconciles the object again after d without counting as a failure: use it to poll something that is still converging.

if !ready {
	return eddy.Retry(15 * time.Second)
}

func RetryDelay

func RetryDelay(err error) (time.Duration, bool)

RetryDelay reports whether err asks for a Retry, and after how long. Middleware uses it to tell a retry from a failure.

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

func Attach(pool *pgxpool.Pool, client *river.Client[pgx.Tx], opts ...Option) (*DB, error)

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

func Open(ctx context.Context, pool *pgxpool.Pool, opts ...Option) (*DB, error)

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

func (db *DB) Begin(ctx context.Context) (*Tx, error)

Begin starts a transaction. Table writes made through the returned Tx commit or roll back with it, jobs included.

func (*DB) Enqueue

func (db *DB) Enqueue(ctx context.Context, refs ...Ref) error

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

func (db *DB) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)

Exec runs sql on the pool. It enqueues nothing; see Table.Exec for writes to a reconciled table.

func (*DB) InTx

func (db *DB) InTx(ctx context.Context, fn func(tx *Tx) error) error

InTx runs fn in a transaction: it commits when fn returns nil and rolls back otherwise.

func (*DB) Leading

func (db *DB) Leading() bool

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

func (db *DB) Pool() *pgxpool.Pool

Pool returns the underlying pool.

func (*DB) Query

func (db *DB) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)

Query runs sql on the pool.

func (*DB) QueryRow

func (db *DB) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row

QueryRow runs sql on the pool.

func (*DB) Run

func (db *DB) Run(ctx context.Context, opts ...Option) error

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

func (*DB) WithTx

func (db *DB) WithTx(tx pgx.Tx) *Tx

WithTx adapts a pgx transaction you already hold, so Table writes can join it.

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.

func Solo

func Solo() Elector

Solo returns an Elector that always leads at once. Use it when exactly one replica runs, or in tests.

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

func Embed(pool *pgxpool.Pool, opts ...Option) (*Embedded, error)

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

func (e *Embedded) AddWorkers(ws *river.Workers)

AddWorkers registers eddy's workers on ws.

func (*Embedded) DB

func (e *Embedded) DB(client *river.Client[pgx.Tx]) *DB

DB returns the DB that enqueues through client.

func (*Embedded) PeriodicJobs

func (e *Embedded) PeriodicJobs() []*river.PeriodicJob

PeriodicJobs are the resync jobs; add them to your client's PeriodicJobs.

func (*Embedded) Queues

func (e *Embedded) Queues() map[string]river.QueueConfig

Queues are eddy's queues and their sizes: the shared one, sized by WithWorkers, plus one per kind declared with MaxWorkers. Add them all to your client's Queues.

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 Handler

type Handler func(ctx context.Context, ref Ref) error

Handler reconciles the object ref points at. Middleware wraps 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.

func NewKind

func NewKind[ID any](name string, opts ...KindOption) Kind[ID]

NewKind returns the Kind called name. Names must be unique within a controller, and must not be empty.

func (Kind[ID]) Name

func (k Kind[ID]) Name() string

Name returns the kind's name.

func (Kind[ID]) Of

func (k Kind[ID]) Of(id ID) Ref

Of returns a reference to the object of this kind identified by id, ready to enqueue. It panics if id cannot be encoded as JSON, which for the usual identifier types never happens.

type KindOption

type KindOption interface {
	// contains filtered or unexported methods
}

KindOption configures NewKind.

type Middleware

type Middleware func(next Handler) Handler

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

func Handle[ID any](k Kind[ID], f func(ctx context.Context, id ID) error) Option

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

func OnLeadershipChange(f func(leading bool)) Option

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

func Perform[T any](t Task[T], f func(ctx context.Context, payload T) error) Option

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

func Reconcile[T any](t *Table[T], f func(ctx context.Context, row *T) error) Option

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

func Record[ID any](k Kind[ID], f func(ctx context.Context, id ID, o Outcome) error) Option

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

func Teardown[T any](t *Table[T], f func(ctx context.Context, row *T) error) Option

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

func WithElector(e Elector) Option

WithElector sets how replicas decide which one works the queue. The default is a Postgres advisory lock named after the queue.

func WithLogger

func WithLogger(l *slog.Logger) Option

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

func WithQueue(name string) Option

WithQueue sets the River queue eddy inserts into and works. The default is DefaultQueue. Every process must agree on it.

func WithReconcileTimeout

func WithReconcileTimeout(d time.Duration) Option

WithReconcileTimeout bounds a single reconcile. The default is River's job timeout (one minute).

func WithResync

func WithResync(every time.Duration) Option

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

func WithShutdownTimeout(d time.Duration) Option

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

func WithWorkers(n int) Option

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.

func (Outcome) OK

func (o Outcome) OK() bool

OK reports whether the reconcile finished without error and without asking for a Retry.

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

func (r Ref) Deleted() bool

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.

func (Ref) ID

func (r Ref) ID() string

ID returns the object's identifier as JSON text, e.g. 42 or "acme", for logs, metrics labels and span attributes.

func (Ref) Kind

func (r Ref) Kind() string

Kind returns the referenced object's kind name.

func (Ref) String

func (r Ref) String() string

String formats the reference as kind/id, for logs.

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

func (t *Table[T]) Delete(ctx context.Context, s Session, id any) error

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

func (t *Table[T]) Exec(ctx context.Context, s Session, sql string, args ...any) (int64, error)

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

func (t *Table[T]) Get(ctx context.Context, q Querier, id any) (*T, error)

Get returns the row with key id, or ErrNotFound.

func (*Table[T]) Insert

func (t *Table[T]) Insert(ctx context.Context, s Session, row *T) error

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

func (t *Table[T]) Name() string

Name returns the table name.

func (*Table[T]) Of

func (t *Table[T]) Of(id any) Ref

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

func (t *Table[T]) SaveStatus(ctx context.Context, q Querier, row *T) error

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.

func (*Table[T]) Select

func (t *Table[T]) Select(ctx context.Context, q Querier, clause string, args ...any) ([]T, error)

Select returns the rows matching clause, which follows the FROM (for example "WHERE team_id = $1 ORDER BY name"); an empty clause returns every row.

func (*Table[T]) Update

func (t *Table[T]) Update(ctx context.Context, s Session, row *T) error

Update writes row's non-status columns to the row with the same key and enqueues its reconcile. row is refreshed from the database. It returns ErrNotFound when no row has that key.

type TableOption

type TableOption interface {
	// contains filtered or unexported methods
}

TableOption configures NewTable.

func Key

func Key(column string) TableOption

Key names the key column; the default is "id".

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.

func (Task[T]) Enqueue

func (t Task[T]) Enqueue(ctx context.Context, s Session, payload T) error

Enqueue schedules the task with payload. On a *Tx it is performed only once the transaction commits, and never when it is rolled back; on a *DB it is enqueued by itself.

func (Task[T]) Name

func (t Task[T]) Name() string

Name returns the task's name.

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.

type Tx

type Tx struct {
	pgx.Tx
	// contains filtered or unexported fields
}

Tx is a pgx transaction that knows how to enqueue reconciles. It has every pgx.Tx method (Exec, Query, Commit, Rollback and the rest).

func (*Tx) Enqueue

func (t *Tx) Enqueue(ctx context.Context, refs ...Ref) error

Enqueue schedules a reconcile of each ref when the transaction commits.

Jump to

Keyboard shortcuts

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