postgres

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 16 Imported by: 0 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.

Documentation

Overview

Package postgres holds a complete Storage over Postgres (§3.2): the production storage adapter, the Go stand-in for the TypeScript package's PrismaStorage.

It owns its tables, prefixed agentenkit_ by default because a production database is usually shared with the caller's own schema. Hand it any *sql.DB opened with a Postgres driver; the package never imports one.

Index

Constants

View Source
const NotifyChannel = "agentenkit_events"

NotifyChannel is the default Postgres channel every thread's events travel on. LISTEN is per connection, not per channel-pattern, so one channel and an in-process fan-out by thread id costs one connection per process however many threads it watches. BusOptions.Channel picks another one.

View Source
const StreamsChannel = "agentenkit_streams"

StreamsChannel is the default channel a stream's changes are announced on: the payload is the stream id. One channel for every stream, so a process holds one LISTEN connection however many streams it reads.

Variables

This section is empty.

Functions

This section is empty.

Types

type BindOption added in v0.3.0

type BindOption func(*Queue)

BindOption tunes Bind.

func WithDeadHandler added in v0.3.0

func WithDeadHandler(fn DeadHandler) BindOption

WithDeadHandler is told about every job the queue gives up on.

type Bus

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

Bus is an EventBus over LISTEN/NOTIFY.

At-most-once by contract, so a dropped notification is fine; the durable log is the record. What the adapter must get right is the size cap: a CHUNK carrying a tool result can exceed 8000 bytes, and NOTIFY refuses it. Such an event, durable or not, is parked in the kv under a short TTL and travels as a reference to that key. The subscriber reads it back from the kv, which needs no storage scope: a storage that requires a tenant (§2.10) cannot be read from the listener, which serves every tenant.

Each subscription remembers the last durable seq it delivered. When the LISTEN connection comes back after a drop, the bus replays what each subscriber missed from the durable store, scoped with the subscriber's own state, and delivers nothing twice.

func NewBus

func NewBus(db *sql.DB, listener Listener, events ports.EventStore, kv *Kv, opts BusOptions) *Bus

NewBus builds the bus. Publishing goes through db (pg_notify); listening through listener. kv parks oversized events; events is the durable store a reconnect replays from, and the fallback for a reference the kv no longer has. Pass the storage's Events() and the NewKv Kv.

func (*Bus) Publish

func (b *Bus) Publish(ctx context.Context, threadID string, event ports.AgentEvent) error

func (*Bus) Subscribe

func (b *Bus) Subscribe(ctx context.Context, threadID string, handler func(ports.AgentEvent)) (func() error, error)

type BusOptions

type BusOptions struct {
	// Heartbeat is the interval of the bus-only HEARTBEAT notice each
	// subscription emits. Zero means one minute.
	Heartbeat time.Duration
	// Channel is the NOTIFY channel this bus publishes and listens on. Two
	// deployments sharing one database must not share a channel, or each
	// delivers the other's events. Empty means NotifyChannel.
	Channel string
}

BusOptions tunes NewBus.

type ConnectNotifier added in v0.2.3

type ConnectNotifier interface {
	OnConnect(fn func())
}

ConnectNotifier is what a Listener can add to that: a callback for every LISTEN connection it brings up, the first one included. The bus uses it to replay, from the durable log, whatever a dropped connection missed, so a missed NOTIFY can never stall an open stream. pgxlisten implements it.

type DeadHandler added in v0.3.0

type DeadHandler func(ctx context.Context, job ports.RunJob, attempts int, cause error)

DeadHandler is told about a job the queue gave up on: its attempts are spent, or its payload cannot be read. The row is kept, dead, for an operator; the handler is where the engine fails the run so its thread does not stay RUNNING for ever.

type DeadJob added in v0.3.0

type DeadJob struct {
	ID        string       `json:"id"`
	Job       ports.RunJob `json:"job"`
	Attempts  int          `json:"attempts"`
	DeadAt    time.Time    `json:"deadAt"`
	LastError string       `json:"lastError"`
}

DeadJob is a row the queue gave up on, kept with the reason.

type Handler

type Handler func(ctx context.Context, job ports.RunJob) error

Handler is what the queue hands a job to: the runtime's worker.

type Kv

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

Kv is a Kv over Postgres: the hot state, the run locks, the HITL handoff keys and the per-thread seq counters (§3.4), in one table beside the storage tables so a single database runs the whole platform.

Expiry is enforced on read. SET NX and Incr are single statements, so two workers can never both win a lock or both take the same seq.

func NewKv

func NewKv(ctx context.Context, db *sql.DB, opts ...Option) (*Kv, error)

NewKv creates the table if it is missing and returns the Kv. The prefix matches the storage's (default "agentenkit_").

func (*Kv) Del

func (k *Kv) Del(ctx context.Context, key string) error

func (*Kv) DelIfValue added in v0.3.0

func (k *Kv) DelIfValue(ctx context.Context, key, expected string) (bool, error)

DelIfValue frees a lease only while it is still this caller's.

func (*Kv) DeleteExpired

func (k *Kv) DeleteExpired(ctx context.Context) (int64, error)

DeleteExpired drops rows past their expiry, in batches of 1,000 so a large backlog never holds one long lock on the table the run locks live in. Expiry is already enforced on read, so this is housekeeping: the Postgres bus runs it every few minutes (its parked oversized frames are rows here); without the bus, call it from a periodic job.

func (*Kv) Get

func (k *Kv) Get(ctx context.Context, key string) (string, bool, error)

func (*Kv) Incr

func (k *Kv) Incr(ctx context.Context, key string) (int64, error)

func (*Kv) IncrWithExpiry added in v0.3.0

func (k *Kv) IncrWithExpiry(ctx context.Context, key string, ttl time.Duration) (int64, error)

IncrWithExpiry is Incr that stamps a NEW counter (or one that had expired) with an expiry, so a counter nobody clears still ages out. A live counter keeps the expiry it already has.

func (*Kv) Set

func (k *Kv) Set(ctx context.Context, key, value string, opts ports.SetOptions) (bool, error)

func (*Kv) SetIfValue added in v0.3.0

func (k *Kv) SetIfValue(ctx context.Context, key, expected, value string, ttl time.Duration) (bool, error)

SetIfValue is the compare-and-set half of a lease renewal (§3.4): the write lands only while the row still holds expected and is not expired.

type Listener

type Listener interface {
	// Listen subscribes to channel and calls handler for every notification
	// until ctx ends. It reconnects on its own; a payload lost while it was
	// down is recovered by the client's cursor replay, which is what an
	// at-most-once bus is for (§2.2).
	Listen(ctx context.Context, channel string, handler func(payload string)) error
}

Listener is what the bus needs from a driver: one long-lived LISTEN connection that hands over every payload on a channel. The package never imports a driver; pgxlisten implements this over pgx.

type Option

type Option func(*Storage)

Option tunes New.

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix sets the table prefix. Default: "agentenkit_".

type PurgeFilter added in v0.3.0

type PurgeFilter struct {
	ThreadID string
	RunID    string
	Kind     *ports.JobKind
	// OlderThan keeps rows enqueued more recently than this.
	OlderThan time.Duration
	// IncludeDead purges dead rows too. Without it they are kept for their
	// operator (PurgeDead drops them by age).
	IncludeDead bool
}

PurgeFilter picks waiting rows for Purge. Every set field narrows it; an empty filter is refused, so a typo cannot empty the queue.

type Queue

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

Queue is a durable Queue over one Postgres table.

Enqueue is one INSERT; a delay is a future runAt. The consumer claims with SELECT ... FOR UPDATE SKIP LOCKED, so several processes can consume the same table, and each claim carries a lease that is renewed while the job runs and lapses when its worker dies. At-least-once: a job whose worker crashed is redelivered once its lease expires, and the engine's run lock makes the duplicate a no-op.

The claim picks across partitions: the partition with the fewest jobs in flight goes first, then priority, then dispatch time. One tenant's burst cannot hold the head of the line against everyone else.

func NewQueue

func NewQueue(ctx context.Context, db *sql.DB, opts QueueOptions, storageOpts ...Option) (*Queue, error)

NewQueue creates the table if it is missing and returns the queue. Nothing is consumed until Bind.

func (*Queue) Bind

func (q *Queue) Bind(handler Handler, opts ...BindOption)

Bind wires the worker and starts consuming. Call once; Close stops it.

func (*Queue) Cancel added in v0.3.0

func (q *Queue) Cancel(ctx context.Context, key string) error

Cancel drops every waiting row under key. A row a worker already holds is left to finish: it is a correct no-op by the engine's own rules. A dead row is kept for its operator.

func (*Queue) Close

func (q *Queue) Close()

Close stops claiming, gives running handlers DrainTimeout to finish, then cancels the ones still running and waits for everything to return.

func (*Queue) Delete added in v0.3.0

func (q *Queue) Delete(ctx context.Context, id string) (bool, error)

Delete removes one row by id, whatever its state.

func (*Queue) Enqueue

func (q *Queue) Enqueue(ctx context.Context, job ports.RunJob, opts *ports.EnqueueOptions) error

func (*Queue) Find added in v0.3.0

func (q *Queue) Find(ctx context.Context, runID string) (*ports.QueuedJob, error)

Find returns the earliest live row for a run, or nil.

func (*Queue) ListDead added in v0.3.0

func (q *Queue) ListDead(ctx context.Context, limit int) ([]DeadJob, error)

ListDead lists dead rows, newest first.

func (*Queue) Pause added in v0.3.0

func (q *Queue) Pause(ctx context.Context) error

Pause tells every consumer of this namespace to stop claiming. Durable, so it holds across every process and a restart; Resume lifts it.

func (*Queue) Pending

func (q *Queue) Pending(ctx context.Context) (int, error)

Pending counts jobs not yet taken (ready or delayed). For tests and dashboards; Stats says more.

func (*Queue) Purge added in v0.3.0

func (q *Queue) Purge(ctx context.Context, f PurgeFilter) (int64, error)

Purge deletes waiting rows that match. Rows a worker holds are left alone, and dead rows unless the filter asks for them.

func (*Queue) PurgeDead added in v0.3.0

func (q *Queue) PurgeDead(ctx context.Context, olderThan time.Duration) (int64, error)

PurgeDead drops dead rows older than the given age.

func (*Queue) Redrive added in v0.3.0

func (q *Queue) Redrive(ctx context.Context, id string) (bool, error)

Redrive puts a dead row back in line with a fresh attempt budget.

func (*Queue) Resume added in v0.3.0

func (q *Queue) Resume(ctx context.Context) error

Resume lets consumers claim again and wakes them.

func (*Queue) Stats added in v0.3.0

func (q *Queue) Stats(ctx context.Context) (ports.QueueStats, error)

Stats counts the namespace's rows and adds what this process knows about its own consumer.

type QueueOptions

type QueueOptions struct {
	// Poll is how often an idle consumer looks for work. Zero means 500ms.
	// With a Listener set, a NOTIFY wakes the consumer at once and the poll
	// is only the backstop for delayed rows and a missed notification.
	Poll time.Duration
	// Lease is how long a claimed job stays invisible to other consumers. It
	// is renewed while the handler runs, so it only needs to outlast one
	// renewal gap plus a crash. Zero means 2 minutes.
	Lease time.Duration
	// Concurrency is how many jobs one consumer runs at once. Zero means 4.
	// The per-thread run lock keeps two jobs on one thread apart regardless.
	Concurrency int
	// MaxAttempts is how many deliveries a job gets before it is kept as
	// dead. The engine's own §2.8 policy re-enqueues a run that fails; this
	// only guards against a handler that keeps dying. Zero means 5.
	MaxAttempts int
	// Namespace scopes every row this queue writes and every claim it makes,
	// so two deployments can share one table without taking each other's
	// jobs. Empty is the default namespace.
	Namespace string
	// MaxDepth refuses a fresh dispatch (ports.ErrQueueFull) once this many
	// first dispatches are waiting. Retries, redrives, resumes and expiries
	// always go in. Zero means unbounded.
	MaxDepth int
	// MaxPayloadBytes refuses a job whose encoded payload is larger
	// (ports.ErrPayloadTooLarge). Zero means 1 MiB.
	MaxPayloadBytes int
	// MaxAge keeps a fresh dispatch from running once it has been ready for
	// this long: the row is kept as dead instead, and the dead handler fails
	// its run. The wait counts from when the job was due, not when it was
	// written, so a delay never counts against it. Only JobDispatch is
	// capped: a resume, an expiry or a reclaim is the platform finishing work
	// it already took on, and failing it would lose that work. Zero means a
	// job waits for ever.
	MaxAge time.Duration
	// RetryBackoff is the delay before a job whose handler failed is offered
	// again, doubled on every further failure up to RetryBackoffMax. Zero
	// means one second; RetryBackoffMax zero means one minute.
	RetryBackoff    time.Duration
	RetryBackoffMax time.Duration
	// MaxRunTime cancels a handler that runs longer than this. The engine
	// bounds its own segments; this is the backstop for a handler that
	// ignores its context. Zero means no bound.
	MaxRunTime time.Duration
	// DrainTimeout is how long Close lets running handlers finish before it
	// cancels them. Zero cancels them at once.
	DrainTimeout time.Duration
	// Listener wakes the consumer on an enqueue instead of waiting out the
	// poll. Optional; pgxlisten implements it.
	Listener Listener
	// Log is where the queue reports what it did: a claim that failed, a
	// lease it could not renew, a job it gave up on. Nil means slog.Default().
	Log *slog.Logger
}

QueueOptions tunes NewQueue.

type RunStreams added in v0.4.0

type RunStreams struct {
	*sqlstreams.Streams
	// contains filtered or unexported fields
}

RunStreams is RunStreams over Postgres: the <prefix>streams and <prefix>stream_events tables. A write sends NOTIFY in its transaction, so readers in other processes wake when it commits.

func NewRunStreams added in v0.4.0

func NewRunStreams(ctx context.Context, db *sql.DB, opts StreamsOptions, options ...Option) (*RunStreams, error)

NewRunStreams migrates the tables and, with a Listener, starts listening. The prefix matches the storage's (default "agentenkit_").

func (*RunStreams) Shutdown added in v0.4.0

func (r *RunStreams) Shutdown()

Shutdown stops listening.

type Storage

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

Storage is a Storage over Postgres.

func New

func New(ctx context.Context, db *sql.DB, opts ...Option) (*Storage, error)

New creates the tables if they are missing, then returns the storage.

func (*Storage) Events

func (s *Storage) Events() ports.EventStore

func (*Storage) Messages

func (s *Storage) Messages() ports.MessageStore

func (*Storage) Threads

func (s *Storage) Threads() ports.ThreadStore

func (*Storage) Usage

func (s *Storage) Usage() ports.UsageStore

type StreamsOptions added in v0.4.0

type StreamsOptions struct {
	// Listener wakes readers here when another process writes. Without one
	// they see its writes on their next poll.
	Listener Listener
	// Channel is the NOTIFY channel. Default StreamsChannel.
	Channel string
	// Poll is the longest a reader waits without news. Default 1s.
	Poll time.Duration
}

StreamsOptions tunes NewRunStreams. Zero values take the defaults.

Directories

Path Synopsis
Package pgxlisten is the postgres bus's Listener over pgx v5: one dedicated connection that LISTENs and hands every notification over.
Package pgxlisten is the postgres bus's Listener over pgx v5: one dedicated connection that LISTENs and hands every notification over.

Jump to

Keyboard shortcuts

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