inbox

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package inbox is a durable, deduplicated, leased work queue in Postgres for incoming external messages such as webhooks. It is independent of the event log.

A Store inserts Messages inside the caller's transaction, deduplicated by (Source, Tenant, Key). Authenticate a message before inserting it: a forged message with a real Key would drop the real delivery (ADR-0015). A Worker per Source claims due messages, runs its Handler and settles each message as done, ignored, Parked or due for a retry. Every pod runs every Source's Worker; rows are claimed with FOR UPDATE SKIP LOCKED and fenced by a claim generation, so a Worker whose claim expired can never settle a message claimed again elsewhere. There is no ordering guarantee.

Operators List messages, Redrive Parked ones and Discard the ones that should not be handled. These calls span every Tenant and do no authorization (ADR-0014): expose them only to Operators. CleanupJob deletes settled messages after a retention period; Parked messages stay until an Operator resolves them.

Index

Constants

View Source
const (
	// CleanupJobName is the scheduler job name of CleanupJob.
	CleanupJobName = "inbox.cleanup"
	// DefaultRetention is how long CleanupJob keeps settled messages when
	// its retention is not positive.
	DefaultRetention = 7 * 24 * time.Hour
)
View Source
const DefaultListLimit = 100

DefaultListLimit is the number of messages List returns when Filter.Limit is not positive.

Variables

View Source
var (
	// ErrInvalidMessage is returned by Store.Insert for a Message with an
	// empty Source, Key or Type.
	ErrInvalidMessage = errors.New("inbox: invalid message")

	// ErrInvalidConfig is returned by NewStore without a pool and by
	// NewWorker without a Store, Source or Handle.
	ErrInvalidConfig = errors.New("inbox: invalid config")

	// ErrRunning is returned by Run and Drain while another Run or Drain of
	// the same Worker is active.
	ErrRunning = errors.New("inbox: worker already running")

	// ErrNotFound is returned by Store.Redrive and Store.Discard for an
	// unknown message ID.
	ErrNotFound = errors.New("inbox: message not found")

	// ErrNotParked is returned by Store.Redrive for a message that is not
	// Parked.
	ErrNotParked = errors.New("inbox: message not parked")

	// ErrSettled is returned by Store.Discard for a message that is already
	// done, ignored or discarded.
	ErrSettled = errors.New("inbox: message already settled")
)
View Source
var DefaultRetries = []time.Duration{
	2 * time.Second, 30 * time.Second, 2 * time.Minute, 10 * time.Minute,
	time.Hour, 6 * time.Hour, 24 * time.Hour,
}

DefaultRetries is the retry schedule used when Config.Retries is nil. After the last step a failing message is Parked.

Functions

func CleanupJob

func CleanupJob(store *Store, retention time.Duration) scheduler.Job

CleanupJob returns a daily scheduler.Job that runs store.Cleanup for the messages settled longer than retention ago, measured on the Store clock. A retention that is not positive uses DefaultRetention. Parked messages are never deleted. The run's Outcome counts the deleted messages as Candidates.

func Ignore

func Ignore(reason string) error

Ignore returns the Handler result that settles a message as ignored, for a message that is valid but needs no action. The reason is stored as the message's error.

func Permanent

func Permanent(err error) error

Permanent returns the Handler result that Parks a message immediately, without further retries. A nil err is replaced by a generic one.

Types

type Config

type Config struct {
	// Source is the Source whose messages the Worker handles. Required.
	Source string
	// Handle handles each message. Required.
	Handle Handler
	// Concurrency is the number of messages handled at once. Default 1.
	Concurrency int
	// Timeout bounds one Handle call. A claim lasts Timeout+30s. Default 60s.
	Timeout time.Duration
	// Retries are the delays after each failed attempt; once spent, the
	// message is Parked. Nil uses DefaultRetries; an empty non-nil slice
	// Parks on the first failure. Delays are jittered down by up to a fifth.
	Retries []time.Duration
}

Config configures a Worker.

type Delivery

type Delivery struct {
	Message
	// ID is the message's row ID.
	ID int64
	// Attempt counts the attempts including this one, starting at 1.
	Attempt int
	// ReceivedAt is when the message was inserted.
	ReceivedAt time.Time
}

Delivery is one attempt to handle a Message.

type Filter

type Filter struct {
	// Source restricts the list to one Source; empty means all Sources.
	Source string
	// Status restricts the list to one Status; empty means all.
	Status Status
	// Limit caps the number of messages. Not positive uses
	// DefaultListLimit.
	Limit int
}

Filter selects the messages List returns.

type Handler

type Handler func(ctx context.Context, d Delivery) error

Handler handles one Delivery. Its result settles the message:

  • nil: done
  • Ignore(reason): ignored
  • Permanent(err): Parked
  • any other error, or a panic: retried after the next step of the retry schedule, and Parked once the schedule is spent

The ctx carries the Actor system:inbox:<source>, the Correlation inbox:<source>:<key>, the message's Tenant when it has one, and the Worker's Timeout as its deadline.

type Message

type Message struct {
	// Source names the origin of the message, such as one webhook provider.
	// Required.
	Source string
	// Key identifies the message within its Source and Tenant. Required, at
	// most 256 bytes.
	Key string
	// Type classifies the message for the Handler. Required.
	Type string
	// Tenant is the message's Tenant, or empty for none.
	Tenant string
	// Payload is the raw message body.
	Payload []byte
}

Message is an incoming external message.

type Option

type Option func(*options)

Option configures a Worker beyond Config.

func WithClaims

func WithClaims(c *lease.Claims) Option

WithClaims makes Run report the inbox.messages and inbox.pending.oldest_age gauges while it holds the Source's telemetry lease, so that only one pod reports them. Without it, the gauges are not reported.

func WithListener

func WithListener(l *notify.Listener) Option

WithListener makes Run wake up on the <schema>.inbox notify channel as soon as a message of the Worker's Source is inserted. Without it, Run only polls.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger. Default slog.Default(). The Source is bound to every record.

func WithMeterProvider

func WithMeterProvider(mp metric.MeterProvider) Option

WithMeterProvider records metrics with mp instead of the global provider.

func WithPollInterval

func WithPollInterval(d time.Duration) Option

WithPollInterval sets how often Run looks for due messages without a notification, jittered down by up to a fifth. Default 1s.

func WithTracerProvider

func WithTracerProvider(tp trace.TracerProvider) Option

WithTracerProvider records spans with tp instead of the global provider.

type Record

type Record struct {
	Message
	// ID is the message's row ID.
	ID     int64
	Status Status
	// Attempts counts the claims since insert or the last Redrive.
	Attempts int
	// Error is the last failure, the Ignore reason or the Discard reason.
	Error         string
	ReceivedAt    time.Time
	NextAttemptAt time.Time
	// SettledAt is when the message reached a final status; zero while
	// pending or Parked.
	SettledAt   time.Time
	DiscardedAt time.Time
	DiscardedBy string
}

Record is a stored message with its processing state.

type Status

type Status string

Status is the state of a stored message.

const (
	// StatusPending is due for a first attempt or a retry, or claimed.
	StatusPending Status = "pending"
	// StatusDone was handled.
	StatusDone Status = "done"
	// StatusIgnored was ignored by its Handler.
	StatusIgnored Status = "ignored"
	// StatusParked failed for good and waits for Redrive or Discard.
	StatusParked Status = "parked"
	// StatusDiscarded was discarded by an operator.
	StatusDiscarded Status = "discarded"
)

Statuses of a stored message.

type Store

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

Store reads and writes the inbox_messages table.

func NewStore

func NewStore(pool *pgxpool.Pool, cfg StoreConfig, opts ...StoreOption) (*Store, error)

NewStore returns a Store on pool. It fails with notify.ErrInvalidChannel when the schema makes the derived channel name invalid, and with ErrInvalidConfig without a pool.

func (*Store) Cleanup

func (s *Store) Cleanup(ctx context.Context, before time.Time) (int64, error)

Cleanup deletes the done, ignored and discarded messages settled before before and reports how many it deleted. Pending and Parked messages are never deleted. A deleted key can be inserted again.

func (*Store) Discard

func (s *Store) Discard(ctx context.Context, id int64, reason string) error

Discard settles the pending or Parked message id as discarded. The row is kept with the discard time and the ctxutil.ResolveActor of ctx, so its key stays deduplicated and the decision stays traceable. A non-empty reason replaces the message's Error. It fails with ctxutil.ErrNoActor when ctx names no one, ErrNotFound for an unknown id and ErrSettled for a message that is already done, ignored or discarded. It is an Operator call: id is not checked against the ctx Tenant (ADR-0014).

func (*Store) Insert

func (s *Store) Insert(ctx context.Context, m Message) (inserted bool, err error)

Insert stores m as a pending message, inside the transaction carried by ctx when there is one. It reports false when a message with the same Source, Tenant and Key already exists, whatever its status; an empty Tenant only matches an empty Tenant. Authenticate m before calling Insert and reject it without inserting when that fails (ADR-0015). It fails with ErrInvalidMessage when Source, Key or Type is empty. The current span's trace context is stored so the handling span can link to it.

func (*Store) List

func (s *Store) List(ctx context.Context, f Filter) ([]Record, error)

List returns the messages matching f, oldest first, with their Payload. It is an Operator call: it lists every Tenant's messages (ADR-0014).

func (*Store) Redrive

func (s *Store) Redrive(ctx context.Context, id int64) error

Redrive makes the Parked message id due now with its attempts reset, so its next attempt counts as the first. It wakes the Workers listening for the message's Source. It fails with ErrNotFound for an unknown id and ErrNotParked for a message that is not Parked. It is an Operator call: id is not checked against the ctx Tenant (ADR-0014).

type StoreConfig

type StoreConfig struct {
	// Schema qualifies the inbox_messages table and derives the notify
	// channel <schema>.inbox. Defaults to public.
	Schema string
}

StoreConfig configures a Store.

type StoreOption

type StoreOption func(*Store)

StoreOption configures a Store beyond StoreConfig.

func WithClock

func WithClock(now func() time.Time) StoreOption

WithClock sets the time source for received, due, claim and settle times. It defaults to time.Now().UTC(). Workers use their Store's clock.

type Worker

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

Worker claims and handles the messages of one Source.

func NewWorker

func NewWorker(store *Store, cfg Config, opts ...Option) (*Worker, error)

NewWorker returns a Worker for cfg.Source on store. It fails with ErrInvalidConfig when store, Source or Handle is missing.

func (*Worker) Drain

func (w *Worker) Drain(ctx context.Context) error

Drain handles every message of the Source that is due when it is called, and messages that become due while it runs, until none is due. It returns ErrRunning while Run or another Drain of this Worker is active.

func (*Worker) Run

func (w *Worker) Run(ctx context.Context) error

Run handles due messages until ctx ends and then returns nil, after the messages in flight have been settled. It looks for due messages on every notification for its Source (with WithListener) and at least every poll interval. It returns ErrRunning while Drain or another Run of this Worker is active.

Jump to

Keyboard shortcuts

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