Documentation
¶
Overview ¶
Package postgres keeps events and projections in PostgreSQL: an event store, a projection store and an automation store that share one database.
Apply Schema before use. EventStore appends and reads the events table, and ProjectionStore keeps projection checkpoints next to the read models. Each projection Commit runs in a single Postgres transaction, so the read model's writes and the checkpoint move land together. Handlers reach the batch's transaction with Tx:
func handle(ctx context.Context, event eventsourcing.Event) error {
switch e := event.(type) {
case *events.TaskCreated:
_, err := postgres.Tx(ctx).Exec(ctx,
`INSERT INTO tasks (id, title) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING`,
e.TaskID, e.Title)
return err
}
return nil
}
The read model's tables must live in the same database as the tables Schema creates, since they are written in one transaction.
Index ¶
- Variables
- func Tx(ctx context.Context) pgx.Tx
- type AutomationStore
- func (s *AutomationStore) Acquire(ctx context.Context, name, owner string, candidates []automation.Segment, ...) (automation.AcquireResult, error)
- func (s *AutomationStore) Defer(ctx context.Context, name, key string, d time.Duration) error
- func (s *AutomationStore) DeferredFor(ctx context.Context, name, key string) (time.Duration, error)
- func (s *AutomationStore) LoadSegments(ctx context.Context, name string) ([]automation.SegmentState, error)
- func (s *AutomationStore) LoadStatuses(ctx context.Context, name string) ([]automation.Status, error)
- func (s *AutomationStore) Paused(ctx context.Context, name string) (bool, error)
- func (s *AutomationStore) Release(ctx context.Context, rel []automation.ReleaseRequest) ([]automation.SegmentLease, error)
- func (s *AutomationStore) Renew(ctx context.Context, held []automation.SegmentLease, ttl time.Duration) ([]automation.SegmentLease, error)
- func (s *AutomationStore) SaveStatus(ctx context.Context, name string, st automation.Status, ttl time.Duration) error
- func (s *AutomationStore) SetPaused(ctx context.Context, name string, paused bool) error
- type EventStore
- func (s *EventStore) Close() error
- func (s *EventStore) Head(ctx context.Context) (uint64, error)
- func (s *EventStore) LoadCorrelation(ctx context.Context, id string) (*eventsourcing.Iterator[*eventsourcing.Envelope], error)
- func (s *EventStore) LoadStream(ctx context.Context, id string) (*eventsourcing.Iterator[*eventsourcing.Envelope], error)
- func (s *EventStore) LoadStreamFrom(ctx context.Context, id string, version eventsourcing.StreamState) (*eventsourcing.Iterator[*eventsourcing.Envelope], error)
- func (s *EventStore) ReadAll(ctx context.Context, after uint64, opts eventsourcing.ReadOptions) (eventsourcing.ReadResult, error)
- func (s *EventStore) Save(ctx context.Context, events []eventsourcing.Envelope, ...) (eventsourcing.AppendResult, error)
- type ProjectionStore
- func (s *ProjectionStore) Claim(ctx context.Context, l projection.Lease, ttl time.Duration) (projection.Lease, projection.Checkpoint, bool, error)
- func (s *ProjectionStore) Commit(ctx context.Context, l projection.Lease, cp projection.Checkpoint, ...) error
- func (s *ProjectionStore) Declare(ctx context.Context, name string, segments int, replayUntil uint64) error
- func (s *ProjectionStore) DeleteDeadLetter(ctx context.Context, l projection.Lease, position uint64) error
- func (s *ProjectionStore) FailRebuild(ctx context.Context, l projection.Lease, requested uint64, errMsg string) error
- func (s *ProjectionStore) FinishReplay(ctx context.Context, l projection.Lease, number uint64, errMsg string) error
- func (s *ProjectionStore) Heartbeat(ctx context.Context, name, owner string, version int, ttl time.Duration) ([]projection.Instance, error)
- func (s *ProjectionStore) LoadDeadLetters(ctx context.Context, name string, segment int) ([]projection.DeadLetter, error)
- func (s *ProjectionStore) LoadInstances(ctx context.Context, name string) ([]projection.Instance, error)
- func (s *ProjectionStore) LoadStatuses(ctx context.Context, name string) ([]projection.Status, error)
- func (s *ProjectionStore) PendingReplays(ctx context.Context, name string) ([]projection.Replay, error)
- func (s *ProjectionStore) RebuildFailure(ctx context.Context, name string) (failed uint64, errMsg string, err error)
- func (s *ProjectionStore) Rebuilds(ctx context.Context, name string) (requested, done uint64, err error)
- func (s *ProjectionStore) Release(ctx context.Context, l projection.Lease) error
- func (s *ProjectionStore) ReplayResult(ctx context.Context, name string, number uint64) (int, []string, error)
- func (s *ProjectionStore) RequestRebuild(ctx context.Context, name string) (uint64, error)
- func (s *ProjectionStore) RequestReplay(ctx context.Context, name, streamID string) (uint64, error)
- func (s *ProjectionStore) Reset(ctx context.Context, l projection.Lease, newVersion int, ...) error
- func (s *ProjectionStore) SaveDeadLetter(ctx context.Context, l projection.Lease, d projection.DeadLetter) error
- func (s *ProjectionStore) SaveStatus(ctx context.Context, l projection.Lease, status projection.Status) error
Constants ¶
This section is empty.
Variables ¶
var Schema string
Schema creates every table the package uses: the events table of EventStore, the segment and dead-letter tables of ProjectionStore, and the three tables of AutomationStore: automation_segments, automation_controls and automation_instances. It is idempotent; run it with your migrations, or once at startup. The same SQL ships as schema.sql in this package's directory.
Schema has the tables as this release uses them, and only creates what is missing: it adds no column to a table an earlier release created. The changelog lists the ALTER TABLE statements to run when upgrading.
Functions ¶
func Tx ¶
Tx returns the transaction a projection.Runner opened for the batch being processed under ctx. Handlers and reset functions write the read model through it, so their writes commit together with the checkpoint.
Tx panics if ctx carries no transaction, which means it was called outside a projection that uses ProjectionStore: a wiring mistake, not a condition to handle at run time.
Types ¶
type AutomationStore ¶ added in v0.6.0
type AutomationStore struct {
// contains filtered or unexported fields
}
AutomationStore is the Postgres automation.Store. It keeps which instance holds each segment of an automation, and the segment's pauses, in the automation_segments table; whether the automation is paused in automation_controls; and what each instance last reported in automation_instances. Schema creates all three. Create the store with NewAutomationStore and pass it as automation.Definition.Store.
Every instance that uses the same database shares the leases, so a segment is worked by one instance at a time. Time is the database's clock, so the instances' clocks need not agree.
func NewAutomationStore ¶ added in v0.6.0
func NewAutomationStore(db *pgxpool.Pool) *AutomationStore
NewAutomationStore returns an AutomationStore on db, which must hold the tables Schema creates.
func (*AutomationStore) Acquire ¶ added in v0.6.0
func (s *AutomationStore) Acquire(ctx context.Context, name, owner string, candidates []automation.Segment, max int, ttl time.Duration) (automation.AcquireResult, error)
Acquire implements automation.Store. It runs in one transaction that records the candidates and locks their rows, in key order so that two instances acquiring at once wait for each other instead of deadlocking; it then reads them in fairness order and grants the first eligible ones.
func (*AutomationStore) Defer ¶ added in v0.6.0
Defer implements automation.Store. It records key if it is new, and keeps a longer pause that is already set.
func (*AutomationStore) DeferredFor ¶ added in v0.6.0
DeferredFor implements automation.Store.
func (*AutomationStore) LoadSegments ¶ added in v0.6.0
func (s *AutomationStore) LoadSegments(ctx context.Context, name string) ([]automation.SegmentState, error)
LoadSegments implements automation.Store.
func (*AutomationStore) LoadStatuses ¶ added in v0.6.0
func (s *AutomationStore) LoadStatuses(ctx context.Context, name string) ([]automation.Status, error)
LoadStatuses implements automation.Store.
func (*AutomationStore) Paused ¶ added in v0.6.0
Paused implements automation.Store.
func (*AutomationStore) Release ¶ added in v0.6.0
func (s *AutomationStore) Release(ctx context.Context, rel []automation.ReleaseRequest) ([]automation.SegmentLease, error)
Release implements automation.Store. Each release is fenced on owner and epoch; a lost one changes nothing. Like Renew, it locks the rows in key order before it updates them.
func (*AutomationStore) Renew ¶ added in v0.6.0
func (s *AutomationStore) Renew(ctx context.Context, held []automation.SegmentLease, ttl time.Duration) ([]automation.SegmentLease, error)
Renew implements automation.Store. A lease is renewed only while its owner and epoch are current and it has not expired. It runs in one transaction that locks the rows in key order, as Acquire does, before it updates them, so a renewal and an acquisition that meet wait for each other instead of deadlocking.
func (*AutomationStore) SaveStatus ¶ added in v0.6.0
func (s *AutomationStore) SaveStatus(ctx context.Context, name string, st automation.Status, ttl time.Duration) error
SaveStatus implements automation.Store. It also deletes the name's expired statuses, so instances that stopped do not pile up.
func (*AutomationStore) SetPaused ¶ added in v0.6.0
SetPaused implements automation.Store.
type EventStore ¶
type EventStore struct {
// contains filtered or unexported fields
}
EventStore is a PostgreSQL-backed eventsourcing.EventStore that also implements eventsourcing.GlobalReader. Stream membership and per-stream ordering are recorded in the events table's stream_id and stream_position columns; the table's own auto-incrementing id column is the GlobalPosition that EventStore.ReadAll orders by. Create one with NewEventStore.
func NewEventStore ¶
func NewEventStore(pool *pgxpool.Pool) *EventStore
NewEventStore returns a PostgreSQL-backed EventStore. The pool must already be configured to connect to a database containing the events table; NewEventStore does not create or migrate the schema.
func (*EventStore) Close ¶
func (s *EventStore) Close() error
Close closes the underlying connection pool. It is safe to call more than once.
func (*EventStore) Head ¶
func (s *EventStore) Head(ctx context.Context) (uint64, error)
Head implements eventsourcing.GlobalReader: the highest id in the events table, or 0 if it is empty.
func (*EventStore) LoadCorrelation ¶ added in v0.5.0
func (s *EventStore) LoadCorrelation(ctx context.Context, id string) (*eventsourcing.Iterator[*eventsourcing.Envelope], error)
LoadCorrelation implements eventsourcing.CorrelationLoader, using the index on correlation_id. Like EventStore.LoadStream, the iterator holds a pooled connection until it ends or is closed.
func (*EventStore) LoadStream ¶
func (s *EventStore) LoadStream(ctx context.Context, id string) (*eventsourcing.Iterator[*eventsourcing.Envelope], error)
LoadStream returns a lazy iterator over all events in the stream identified by id, in the order they were appended. It returns a non-nil error if the stream does not exist.
func (*EventStore) LoadStreamFrom ¶
func (s *EventStore) LoadStreamFrom(ctx context.Context, id string, version eventsourcing.StreamState) (*eventsourcing.Iterator[*eventsourcing.Envelope], error)
LoadStreamFrom returns a lazy iterator over the events in the stream identified by id, starting after the position identified by version. eventsourcing.NoStream requires the stream not to exist and returns a non-nil error if it does; eventsourcing.StreamExists requires that it does exist and returns a non-nil error if it does not; eventsourcing.Any reads from the beginning of the stream. Any other eventsourcing.StreamState — in practice a eventsourcing.Revision of n — is treated as a position, and events after it are returned, so a caller that has already processed n events resumes exactly where it left off; a zero revision behaves like reading from the beginning.
func (*EventStore) ReadAll ¶
func (s *EventStore) ReadAll(ctx context.Context, after uint64, opts eventsourcing.ReadOptions) (eventsourcing.ReadResult, error)
ReadAll implements eventsourcing.GlobalReader. Filters run in SQL, on exact event type names and on stream ID prefixes (with starts_with, so % and _ in a prefix are not wildcards).
Because Save commits appends one at a time in id order, every row up to the highest visible id is either committed or permanently abandoned (a rolled-back insert leaves a hole in the sequence, never a late row), so ReadAll reads up to that id without a visibility filter.
func (*EventStore) Save ¶
func (s *EventStore) Save(ctx context.Context, events []eventsourcing.Envelope, revision eventsourcing.StreamState) (eventsourcing.AppendResult, error)
Save appends events to the stream they share, enforcing the concurrency check described by revision: eventsourcing.Any skips it, eventsourcing.NoStream requires the stream not to exist yet, eventsourcing.StreamExists requires that it already does, and a eventsourcing.Revision requires the stream's current length to match exactly. All events must have the same StreamID, or Save returns a non-nil error without appending anything. The whole append happens inside a transaction serialized against other writers to the same stream by a Postgres advisory lock, so on a revision mismatch — whether caught by the check above or by a unique-constraint violation from a concurrent writer — it returns a eventsourcing.StreamRevisionConflictError and nothing is persisted.
Before inserting, Save also takes one advisory lock shared by every append, held until it commits. Ids are assigned at INSERT but become visible at COMMIT; without that lock, a transaction could commit id 52 while another still holds 51, and a reader that moved past 52 would never see 51. With it, appends assign ids and commit one at a time, so ids become visible in order and EventStore.ReadAll needs no visibility filter. The cost is that appends to different streams no longer commit in parallel; only the inserts and the commit run under the lock.
On success it returns a eventsourcing.AppendResult whose NextExpectedVersion is the stream's new length.
type ProjectionStore ¶
type ProjectionStore struct {
// contains filtered or unexported fields
}
ProjectionStore is the Postgres projection.Store. Create it with NewProjectionStore.
Commit and Reset lock the segment's row for the whole unit of work, so a Claim by another instance waits for the batch to finish instead of taking the segment over halfway. Heartbeats use clock_timestamp(), the time of the write, rather than now(), the start of the transaction, so a batch that ran longer than the claim's ttl still leaves a fresh heartbeat behind and the waiting Claim is refused.
func NewProjectionStore ¶
func NewProjectionStore(db *pgxpool.Pool) *ProjectionStore
NewProjectionStore returns a ProjectionStore that uses db. All operations open their own transactions against db except for a Commit's unit of work, which is the single transaction the handlers see through Tx.
func (*ProjectionStore) Claim ¶
func (s *ProjectionStore) Claim(ctx context.Context, l projection.Lease, ttl time.Duration) (projection.Lease, projection.Checkpoint, bool, error)
Claim implements projection.Store.
A refresh of the current claim keeps its epoch; a takeover raises it. On the right-hand side of SET, owner and epoch are the row's values before the update, and WHERE judges expiry by the current claim's own ttl_ms.
func (*ProjectionStore) Commit ¶
func (s *ProjectionStore) Commit(ctx context.Context, l projection.Lease, cp projection.Checkpoint, status projection.Status, fn func(ctx context.Context) error) error
Commit implements projection.Store. It runs fn in a transaction that first locks the segment's row, so a Claim by another instance waits for the batch instead of taking the segment over halfway.
func (*ProjectionStore) Declare ¶
func (s *ProjectionStore) Declare(ctx context.Context, name string, segments int, replayUntil uint64) error
Declare implements projection.Store: it creates the segment rows for name on first use, and verifies the count has not changed since.
func (*ProjectionStore) DeleteDeadLetter ¶
func (s *ProjectionStore) DeleteDeadLetter(ctx context.Context, l projection.Lease, position uint64) error
DeleteDeadLetter implements projection.DeadLetterStore. It is called inside the Commit that applies the event again.
func (*ProjectionStore) FailRebuild ¶ added in v0.5.0
func (s *ProjectionStore) FailRebuild(ctx context.Context, l projection.Lease, requested uint64, errMsg string) error
FailRebuild implements projection.Store, fenced by locking l's segment row as Commit does.
func (*ProjectionStore) FinishReplay ¶ added in v0.4.0
func (s *ProjectionStore) FinishReplay(ctx context.Context, l projection.Lease, number uint64, errMsg string) error
FinishReplay implements projection.DeadLetterStore, fenced by locking l's segment row as Commit does. It locks the request's row too, so of two segments finishing it at once, the second sees the first one done.
func (*ProjectionStore) Heartbeat ¶ added in v0.4.0
func (s *ProjectionStore) Heartbeat(ctx context.Context, name, owner string, version int, ttl time.Duration) ([]projection.Instance, error)
Heartbeat implements projection.Store in one statement: it upserts owner's row, deletes the rows of other instances whose own ttl has passed, and returns the live ones with the number of segments each one claims. The statement's reads see the table as it was before its writes, so owner's row comes from the upsert and is left out of the read.
func (*ProjectionStore) LoadDeadLetters ¶
func (s *ProjectionStore) LoadDeadLetters(ctx context.Context, name string, segment int) ([]projection.DeadLetter, error)
LoadDeadLetters implements projection.DeadLetterStore.
func (*ProjectionStore) LoadInstances ¶ added in v0.4.0
func (s *ProjectionStore) LoadInstances(ctx context.Context, name string) ([]projection.Instance, error)
LoadInstances implements projection.Store: it reads the rows whose own ttl has not passed, with the number of segments each one claims.
func (*ProjectionStore) LoadStatuses ¶
func (s *ProjectionStore) LoadStatuses(ctx context.Context, name string) ([]projection.Status, error)
LoadStatuses returns the status of every segment of name.
func (*ProjectionStore) PendingReplays ¶ added in v0.4.0
func (s *ProjectionStore) PendingReplays(ctx context.Context, name string) ([]projection.Replay, error)
PendingReplays implements projection.DeadLetterStore.
func (*ProjectionStore) RebuildFailure ¶ added in v0.5.0
func (s *ProjectionStore) RebuildFailure(ctx context.Context, name string) (failed uint64, errMsg string, err error)
RebuildFailure implements projection.Store.
func (*ProjectionStore) Rebuilds ¶ added in v0.3.0
func (s *ProjectionStore) Rebuilds(ctx context.Context, name string) (requested, done uint64, err error)
Rebuilds implements projection.Store.
func (*ProjectionStore) Release ¶
func (s *ProjectionStore) Release(ctx context.Context, l projection.Lease) error
Release implements projection.Store.
func (*ProjectionStore) ReplayResult ¶ added in v0.4.0
func (s *ProjectionStore) ReplayResult(ctx context.Context, name string, number uint64) (int, []string, error)
ReplayResult implements projection.DeadLetterStore.
func (*ProjectionStore) RequestRebuild ¶ added in v0.3.0
RequestRebuild implements projection.Store.
func (*ProjectionStore) RequestReplay ¶ added in v0.4.0
RequestReplay implements projection.DeadLetterStore, in one statement that records the request and a row for each segment holding dead letters of streamID. A stream without dead letters records nothing and gets 0.
func (*ProjectionStore) Reset ¶
func (s *ProjectionStore) Reset(ctx context.Context, l projection.Lease, newVersion int, wipe func(ctx context.Context) error) error
Reset implements projection.Store, in one transaction that first locks every segment row of the projection in segment order: Commits in progress finish first, and concurrent Resets cannot deadlock. On the right-hand side of SET, position and owner are the row's values before the update.
func (*ProjectionStore) SaveDeadLetter ¶
func (s *ProjectionStore) SaveDeadLetter(ctx context.Context, l projection.Lease, d projection.DeadLetter) error
SaveDeadLetter implements projection.DeadLetterStore. It is called inside the Commit that moves the checkpoint past the event.
func (*ProjectionStore) SaveStatus ¶
func (s *ProjectionStore) SaveStatus(ctx context.Context, l projection.Lease, status projection.Status) error
SaveStatus implements projection.Store.