pgstore

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package pgstore holds every SQL statement of Foreman (pgx v5): inserts (multi-row and COPY), the fetch queries with SKIP LOCKED, fairness and per-key limits, batched completions and heartbeats under the completion guard, leases, maintenance, admin operations and the LISTEN connection. Time values always come from the caller's clock.

store, err := pgstore.New(pool, "public")
rows, err := store.Fetch(ctx, job.FetchParams{Queue: "default", ClientID: id, Limit: 10, Now: now})

Index

Constants

View Source
const (
	OpCancel  = "cancel"
	OpDiscard = "discard"
	OpRetry   = "retry"
)

Admin operations on jobs.

View Source
const CopyThreshold = 10

CopyThreshold is the batch size from which inserts go through COPY into a temporary table; smaller batches use one multi-row statement.

View Source
const DefaultSchema = "public"

DefaultSchema is the schema used when none is configured.

Variables

This section is empty.

Functions

This section is empty.

Types

type DB

type DB 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
	CopyFrom(ctx context.Context, table pgx.Identifier, cols []string, src pgx.CopyFromSource) (int64, error)
	Begin(ctx context.Context) (pgx.Tx, error)
}

DB is satisfied by *pgxpool.Pool and pgx.Tx: statements that may run in a caller's transaction (InsertTx, CompleteTx) accept either.

type Filter

type Filter struct {
	IDs           []int64
	Kinds         []string
	Queues        []string
	States        []job.State
	CreatedAfter  time.Time
	CreatedBefore time.Time
	// BeforeID restricts to ids below it (list cursor); 0 = no restriction.
	BeforeID int64
}

Filter selects jobs for list and bulk operations; empty fields match all.

type Leader

type Leader struct {
	Name      string
	LeaderID  string
	ElectedAt time.Time
	ExpiresAt time.Time
}

Leader is the current lease holder.

type Listener

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

Listener holds a dedicated connection for LISTEN; it implements job.Listener. The connection is taken out of the pool for its whole life and closed on Close, so a broken connection is never returned to the pool.

func (*Listener) Close

func (l *Listener) Close(ctx context.Context) error

Close closes the connection.

func (*Listener) Connect

func (l *Listener) Connect(ctx context.Context) error

Connect acquires and detaches a connection from the pool.

func (*Listener) Listen

func (l *Listener) Listen(ctx context.Context, channel string) error

Listen subscribes to channel.

func (*Listener) Ping

func (l *Listener) Ping(ctx context.Context) error

Ping runs an empty statement on the connection.

func (*Listener) WaitForNotification

func (l *Listener) WaitForNotification(ctx context.Context) (job.Notification, error)

WaitForNotification blocks until a notification arrives or ctx is done.

type Names

type Names struct {
	// Schema is the unquoted schema name.
	Schema string
	// Quoted is the schema as a quoted SQL identifier.
	Quoted string
	// InsertChannel receives the queue name when available jobs are inserted.
	InsertChannel string
	// ControlChannel receives cancel, pause and resume commands as JSON.
	ControlChannel string
	// LeaderChannel is notified when a leader resigns.
	LeaderChannel string
	// LockPrefix scopes advisory lock keys to the schema ("" for public).
	LockPrefix string
}

Names are the schema-dependent identifiers of one Foreman installation.

func NewNames

func NewNames(schema string) (Names, error)

NewNames validates schema and derives the identifiers. Channels keep the documented names (foreman_insert, foreman_control) in the public schema and are prefixed with the schema name otherwise, so installations sharing a database do not wake each other.

type PeriodicRow

type PeriodicRow struct {
	Name     string
	LastTick time.Time
	Ticks    int64
}

PeriodicRow summarises the ticks recorded for one periodic job.

type QueueRow

type QueueRow struct {
	Name      string
	PausedAt  *time.Time
	UpdatedAt *time.Time
	Counts    map[job.State]int64
}

QueueRow describes one queue for admin views.

type Store

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

Store implements the job store ports on Postgres with pgx v5. Every SQL statement of Foreman lives in this package; every time value comes from the caller (client clock), never from now().

func New

func New(pool *pgxpool.Pool, schema string) (*Store, error)

New returns a Store for schema (default public).

func (*Store) AcquireLease

func (s *Store) AcquireLease(ctx context.Context, name, id string, now time.Time, ttl time.Duration) (bool, error)

AcquireLease implements job.LeaseStore.

func (*Store) CancelRequested

func (s *Store) CancelRequested(ctx context.Context, ids []int64) ([]int64, error)

CancelRequested implements job.CancelPoller.

func (*Store) Complete

func (s *Store) Complete(ctx context.Context, clientID string, cs []job.Completion) ([]int64, error)

Complete implements job.CompletionWriter.

func (*Store) CompleteTx

func (s *Store) CompleteTx(ctx context.Context, tx pgx.Tx, clientID string, ref job.Ref, now time.Time) error

CompleteTx marks one attempt completed inside the caller's transaction (foreman.CompleteTx). It returns job.ErrStale when the guard rejects it.

func (*Store) DeleteFinalized

func (s *Store) DeleteFinalized(ctx context.Context, state job.State, cutoff time.Time, limit int) (int, error)

DeleteFinalized implements job.MaintenanceStore.

func (*Store) EnqueueTick

func (s *Store) EnqueueTick(ctx context.Context, name string, tick time.Time, p job.InsertParams) (bool, error)

EnqueueTick implements job.MaintenanceStore: the tick row and the job are inserted in one transaction, so a tick is enqueued at most once.

func (*Store) Fetch

func (s *Store) Fetch(ctx context.Context, p job.FetchParams) ([]*job.Row, error)

Fetch implements job.Fetcher.

func (*Store) FetchByID

func (s *Store) FetchByID(ctx context.Context, id int64, clientID string, now time.Time) (*job.Row, error)

FetchByID marks one available job running for clientID. It returns job.ErrNotFound for unknown ids and an InvalidTransitionError when the job is not available (or is locked by another fetch).

func (*Store) Heartbeat

func (s *Store) Heartbeat(ctx context.Context, clientID string, now time.Time, refs []job.Ref) (int, error)

Heartbeat implements job.HeartbeatWriter.

func (*Store) Insert

func (s *Store) Insert(ctx context.Context, db DB, ps []job.InsertParams) ([]job.InsertResult, error)

Insert inserts jobs through db (the pool or a caller's transaction) and returns one result per input in input order.

func (*Store) JobDeleteAll

func (s *Store) JobDeleteAll(ctx context.Context, f Filter) (int, error)

JobDeleteAll deletes the non-running jobs matching f in batches.

func (*Store) JobGet

func (s *Store) JobGet(ctx context.Context, id int64) (*job.Row, error)

JobGet returns one job or job.ErrNotFound.

func (*Store) JobList

func (s *Store) JobList(ctx context.Context, f Filter, limit int) ([]*job.Row, error)

JobList returns up to limit jobs matching f, newest first.

func (*Store) JobUpdate

func (s *Store) JobUpdate(ctx context.Context, op string, f Filter, now time.Time, limit int) ([]*job.Row, error)

JobUpdate applies op to the jobs matching f (at most limit of them) and returns the changed rows.

func (*Store) JobUpdateAll

func (s *Store) JobUpdateAll(ctx context.Context, op string, f Filter, now time.Time) (int, error)

JobUpdateAll applies op in batches until no matching job is left and returns the number of jobs changed.

func (*Store) KeyStats

func (s *Store) KeyStats(ctx context.Context, queue string, limit int, withRunning bool) ([]job.KeyStat, error)

KeyStats implements job.Fetcher.

func (*Store) LastTicks

func (s *Store) LastTicks(ctx context.Context) (map[string]time.Time, error)

LastTicks implements job.MaintenanceStore.

func (*Store) LeaderGet

func (s *Store) LeaderGet(ctx context.Context, name string) (*Leader, error)

LeaderGet returns the lease row, or job.ErrNotFound when there is none.

func (*Store) MarkPeriodicStart

func (s *Store) MarkPeriodicStart(ctx context.Context, name string, now time.Time) error

MarkPeriodicStart implements job.MaintenanceStore: a tick row without a job marks when the periodic job was first scheduled.

func (*Store) Names

func (s *Store) Names() Names

Names returns the schema-dependent identifiers.

func (*Store) NewListener

func (s *Store) NewListener() *Listener

NewListener returns a listener on pool.

func (*Store) PeriodicList

func (s *Store) PeriodicList(ctx context.Context) ([]*PeriodicRow, error)

PeriodicList lists periodic jobs that have enqueued at least one tick.

func (*Store) Pool

func (s *Store) Pool() *pgxpool.Pool

Pool returns the underlying pool.

func (*Store) PromoteDue

func (s *Store) PromoteDue(ctx context.Context, now time.Time, limit int) (int, error)

PromoteDue implements job.MaintenanceStore.

func (*Store) PruneTicks

func (s *Store) PruneTicks(ctx context.Context, cutoff time.Time) (int, error)

PruneTicks deletes tick records older than cutoff, keeping the latest tick of every periodic job (needed to compute missed ticks).

func (*Store) QueueDepths

func (s *Store) QueueDepths(ctx context.Context) ([]job.QueueDepth, error)

QueueDepths implements job.MaintenanceStore (pending states only).

func (*Store) QueueHeartbeat

func (s *Store) QueueHeartbeat(ctx context.Context, queue string, now time.Time) (bool, error)

QueueHeartbeat implements job.Fetcher.

func (*Store) QueueList

func (s *Store) QueueList(ctx context.Context) ([]*QueueRow, error)

QueueList lists known queues with pending job counts per state.

func (*Store) QueueSetPaused

func (s *Store) QueueSetPaused(ctx context.Context, name string, paused bool, now time.Time) error

QueueSetPaused pauses (paused=true) or resumes a queue and notifies clients.

func (*Store) Reindex

func (s *Store) Reindex(ctx context.Context) (bool, error)

Reindex implements job.MaintenanceStore. It skips the run when another CREATE INDEX or REINDEX is in progress, and first drops invalid leftovers of an interrupted REINDEX CONCURRENTLY.

func (*Store) ReleaseLease

func (s *Store) ReleaseLease(ctx context.Context, name, id string) error

ReleaseLease implements job.LeaseStore; it notifies the other clients.

func (*Store) RenewLease

func (s *Store) RenewLease(ctx context.Context, name, id string, now time.Time, ttl time.Duration) (bool, error)

RenewLease implements job.LeaseStore.

func (*Store) Rescue

func (s *Store) Rescue(ctx context.Context, cutoff time.Time, cs []job.Completion) (int, error)

Rescue implements job.MaintenanceStore: the guard requires the job to be still running the same attempt with a heartbeat older than cutoff.

func (*Store) ServedQueues

func (s *Store) ServedQueues(ctx context.Context, cutoff time.Time) ([]string, error)

ServedQueues lists queues a producer reported since cutoff.

func (*Store) StuckJobs

func (s *Store) StuckJobs(ctx context.Context, cutoff time.Time, limit int) ([]*job.Row, error)

StuckJobs implements job.MaintenanceStore.

Jump to

Keyboard shortcuts

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