decode

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 15 Imported by: 1 module, 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 decode owns the copy-and-swap route's logical-decoding state and the contracts its consumers depend on (ST-3, ST-4, CO-4, CO-8). It creates the single-table publication and the replication slot preflight named for a target, with an exported snapshot and the consistent point decoding starts from; drops them, waiting out a walsender that still holds the slot and never touching a slot another database owns or a publication it did not make; and reads a slot's pg_replication_slots row, including the WAL it retains and whether the server has declared that WAL lost. A Stream decodes the slot with pgoutput into ChangeEvents — one per committed row change, every Column carried with its presence and its value readable only together with it, so an unchanged out-of-line value the server omitted is never mistaken for a value, and the key a moved row had — and keeps two positions apart: what it has delivered, which every transaction yielded so far committed at or below, and what the caller has confirmed applied, which is the only position it ever reports to the server. Both order transactions by commit, since the server sends a transaction whole when it commits: a change's own LSN can lie below either, and the position a caller may confirm while a change is unapplied is the delivered position the change arrived with. The server ending replication is ErrStreamEnded, the clean resume a new stream from the confirmed position continues. Replication commands run on a dedicated connection from pkg/dbconn, proven before any slot command to be a session of the same cluster and database as the caller's pool; catalog reads and the publication run on that pool. Refusals are typed — *ForeignStateError for state of the derived name that is not the route's, *PublicationPrivilegeError when the role may not create the publication, *SlotExistsError for the route's own earlier slot — so a caller routes on the type, never on message text.

Index

Constants

View Source
const DefaultSlotLagCeiling int64 = 1 << 30

DefaultSlotLagCeiling is the most WAL a slot may retain before the route aborts: one GiB (D11). A slot is cluster state that keeps WAL on the volume until it is confirmed or dropped, so the bound is hard and the abort fails closed.

View Source
const MarkerPrefix = "pgsprite"

MarkerPrefix names the logical messages the engine writes into the WAL as position markers; nothing decodes them, and the prefix only tells a reader of the WAL whose they are.

View Source
const SlotNamePrefix = "pgsprite_"

SlotNamePrefix is what every engine slot name starts with; a reaper lists candidates by it and then asks IsEngineSlotName about each.

Variables

View Source
var ErrForeignDecodingState = errors.New("logical-decoding state of the derived name is not this route's")

ErrForeignDecodingState is the sentinel every refusal of foreign state unwraps to: the publication or the slot of the derived name turned out not to be this route's. Neither is ever adopted or dropped; the operator resolves it by renaming or dropping the foreign object. The refusal is deliberately total — a foreign slot leaves the publication of the name in place too — and a caller must not answer it with DropSlot, which would wait out and drop whatever the other owner is still streaming from.

View Source
var ErrInvariantViolation = dbconn.ErrInvariantViolation

ErrInvariantViolation is the fail-closed sentinel for state this package cannot have produced: a zero or non-decoding target, or a slot name that is not the engine's.

View Source
var ErrSlotActive = errors.New("replication slot is held by another process")

ErrSlotActive reports a slot DropIdleSlot found held by a walsender or a backend at the moment of the drop: whoever holds it is the judge of it, so the slot and its publication are left as found.

View Source
var ErrSlotLagCeiling = errors.New("replication slot retains more WAL than the lag ceiling allows")

ErrSlotLagCeiling is the sentinel a SlotLagExceededError unwraps to: the slot retains more WAL than the ceiling allows (ST-3).

View Source
var ErrSlotLagUnknown = errors.New("replication slot's retained WAL cannot be measured")

ErrSlotLagUnknown reports a slot whose retained WAL the server could not measure while it is not lost: on a server in recovery, where the write position cannot be read. An unknown amount is never read as nothing retained, so a ceiling cannot be enforced against it and the check fails closed (ST-3).

View Source
var ErrSlotLost = errors.New("replication slot is lost")

ErrSlotLost is the sentinel a SlotLostError unwraps to: the slot can no longer be read from — the server removed WAL it needed, or the slot is gone — which is the modeled state ST-4 enters rather than a crash.

View Source
var ErrSourceShapeChanged = errors.New("the source table's shape changed under the stream")

ErrSourceShapeChanged is returned when pgoutput describes the target table differently from how the stream first saw it: a column added, dropped, renamed, or retyped, or the replica identity changed. The decoded columns would no longer line up with the shadow, so the stream stops rather than guess; the route's resume path decides what to do with the shadow.

View Source
var ErrStreamEnded = errors.New("the server ended the replication stream")

ErrStreamEnded is returned when the server ends replication in an orderly way — a shutdown with the slot intact — rather than with an error. This is the clean resume ST-4 separates from slot loss: the slot survives with a position at or below the last confirm (a confirm that only moves the slot's confirmed position is not always written out before a shutdown), and a new stream started from the caller's own checkpoint continues where this one stopped, since the server forwards a start that lies below the slot's position.

View Source
var ErrUnsupportedChange = errors.New("the source table received a change the route does not replay")

ErrUnsupportedChange is returned when the stream decodes a change to the target table that the route does not replay row by row — a TRUNCATE. The shadow cannot be brought back into step by applying rows, so the stream stops and the route decides whether to restart the copy.

Functions

func DropIdleSlot added in v0.4.0

func DropIdleSlot(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, name string) error

DropIdleSlot is DropSlot for a caller that must not wait out a holder: the slot is dropped with DROP_REPLICATION_SLOT without WAIT, so a slot a walsender or a backend holds when the drop reaches the server is refused with ErrSlotActive and left in place, publication and all. Whether the slot is held is judged by the server at the drop itself, not by a catalog read before it, so a slot that becomes held between a caller's read and the drop is still left alone. Everything else is as for DropSlot.

func DropSlot added in v0.4.0

func DropSlot(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, name string) error

DropSlot drops the engine's replication slot and publication of the given name from pool's database. The slot is dropped with DROP_REPLICATION_SLOT … WAIT on a fresh replication connection built from cfg, proven to be on the pool's own cluster and database before the drop is issued, so a walsender still holding the slot is waited for rather than failed on; ctx is the only bound on that wait, and a wait that ctx ends is cancelled on the server and reported as an error carrying ctx's own — never as a drop, and the slot stays for the holder to release and the next attempt to drop. The cancel request travels on a connection of its own, so a caller that must know what the server did re-reads InspectSlot. A drop is reported only once the catalog no longer shows the slot. A slot already absent is success, so the drop is idempotent.

Only the engine's own state is dropped: a slot of the name that belongs to another database or is physical, and a publication of the name that is not one CreateSlot would have created, are refused with a *ForeignStateError and left as found — a foreign slot leaves the publication of the name in place too, since the whole name is then in dispute. A name outside the engine's shape is an invariant violation.

func IsEngineSlotName added in v0.4.0

func IsEngineSlotName(name string) bool

IsEngineSlotName reports whether name has the shape this package creates and drops. A name that merely wears the prefix is not the engine's and is never dropped.

Types

type ChangeEvent

type ChangeEvent struct {
	Kind ChangeKind
	// LSN is the WAL position the change was written at. The server sends
	// a transaction when it commits, so LSN can lie below a position the
	// stream has already delivered or the caller has already confirmed:
	// it orders changes within their transaction, not against the stream.
	LSN LSN
	// Delivered is the stream's delivered position when the change
	// arrived. It lies below the change's commit and never below anything
	// already confirmed, so it is the position a caller may confirm while
	// the change is unapplied: a stream reopened from it replays the
	// change's transaction.
	Delivered LSN
	// Xid is the transaction the change belongs to, as the server numbers
	// transactions. The server sends a transaction once its commit is in
	// the WAL, which is before the committing backend has made it visible
	// to snapshots — a backend waiting for synchronous replication sits
	// between the two for as long as the wait lasts — so a reader that
	// takes a snapshot after the change arrived checks Xid against that
	// snapshot before it trusts a read to see the change.
	Xid     uint32
	Key     int64
	OldKey  *int64
	Columns []Column
}

ChangeEvent is one decoded row change. OldKey is non-nil only when an update moved the key.

func (ChangeEvent) PresentColumns

func (e ChangeEvent) PresentColumns() []Column

PresentColumns returns only values present in the decoded row image.

type ChangeKind

type ChangeKind uint8

ChangeKind identifies a decoded row operation.

const (
	// Insert creates a row.
	Insert ChangeKind = iota + 1
	// Update changes a row.
	Update
	// Delete removes a row.
	Delete
)

func (ChangeKind) String

func (k ChangeKind) String() string

String returns the stable operation name.

type Column

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

Column is one decoded column: its name, and the value pgoutput carried for it when it carried one. An absent column is the unchanged-TOAST marker — pgoutput omitted the value because the stored one is unchanged, so an applier leaves the stored value untouched (CO-8) — and it has no value to read: Get reports the absence instead of a value. A SQL NULL is a present column whose value is nil, which is why presence is read with the value and never inferred from it.

func AbsentColumn added in v0.4.0

func AbsentColumn(name string) Column

AbsentColumn is a column pgoutput sent as the unchanged-TOAST marker: the stored value is unchanged and was not carried.

func PresentColumn added in v0.4.0

func PresentColumn(name string, value any) Column

PresentColumn is a column pgoutput carried a value for. A NULL is a present column with a nil value. The stream carries the text form pgoutput sent, so a value it decodes is a string; the applier binds a value as a text parameter, so a caller building its own events passes a string or nil.

func (Column) Get added in v0.4.0

func (c Column) Get() (value any, present bool)

Get returns the column's value together with whether the column carries one, so a reader takes the presence with the value. An absent column yields nil and false, and the nil is not a value: the stored value is unchanged and unknown here. Go still lets a caller discard the presence; a test in this package refuses that in production code, and the applier's bind refuses an absent column before any statement runs.

func (Column) Name

func (c Column) Name() string

Name is the column's name as the relation declares it.

func (Column) Present

func (c Column) Present() bool

Present reports whether the column carries a value; a NULL does.

func (Column) String added in v0.4.0

func (c Column) String() string

String renders the column as name=<absent>, name=NULL, or name=<value>, so a log line or a test failure tells the three apart. It never renders the value itself, which is row data. A Column has no exported fields, so it carries no JSON encoding.

type Delivery added in v0.4.0

type Delivery struct {
	// Change is the decoded row change; nil for a progress-only delivery.
	Change *ChangeEvent
	// Delivered is the stream's position after this delivery: every
	// transaction that committed at or below it has been yielded in full,
	// so it is the ceiling of what the caller may confirm. A change's own
	// LSN can lie below it, since a transaction is sent when it commits,
	// not when its rows were written. For a change delivery it equals
	// Change.Delivered.
	Delivered LSN
}

Delivery is what one call to Stream.Next yields: a decoded change, or nothing but a position when the server reported progress without a change — a transaction's commit, or a keepalive while the table is quiet.

type ForeignObject added in v0.4.0

type ForeignObject string

ForeignObject names which logical-decoding object of the derived name a ForeignStateError is about.

const (
	// ForeignObjectSlot is a replication slot of the derived name that
	// belongs to another database or is physical.
	ForeignObjectSlot ForeignObject = "slot"
	// ForeignObjectPublication is a publication of the derived name that is
	// not the one CreateSlot would have created for the target.
	ForeignObjectPublication ForeignObject = "publication"
)

type ForeignStateError added in v0.4.0

type ForeignStateError struct {
	Object ForeignObject
	// Name is the derived name the object wears.
	Name string
	// Detail says what made the object foreign: the database that owns the
	// slot, or what the publication publishes that the route's would not.
	Detail string
}

ForeignStateError is the refusal CreateSlot and DropSlot return for foreign state, so a caller can route on which object was foreign and report why without reading message text. It unwraps to ErrForeignDecodingState.

func (*ForeignStateError) Error added in v0.4.0

func (e *ForeignStateError) Error() string

func (*ForeignStateError) Unwrap added in v0.4.0

func (e *ForeignStateError) Unwrap() error

Unwrap makes every ForeignStateError match ErrForeignDecodingState.

type InvalidationReason added in v0.4.0

type InvalidationReason string

InvalidationReason is pg_replication_slots.invalidation_reason: the server's cause for giving up on a slot.

const (
	// InvalidationWALRemoved means WAL the slot needed was removed, as
	// when the slot's retention passed max_slot_wal_keep_size.
	InvalidationWALRemoved InvalidationReason = "wal_removed"
	// InvalidationRowsRemoved means rows the slot's catalog snapshot
	// needed were removed on a standby, a recovery conflict.
	InvalidationRowsRemoved InvalidationReason = "rows_removed"
	// InvalidationWALLevelInsufficient means the primary's wal_level fell
	// below logical while a standby held the slot, a recovery conflict.
	InvalidationWALLevelInsufficient InvalidationReason = "wal_level_insufficient"
	// InvalidationIdleTimeout means the slot sat unused past the server's
	// idle slot timeout (PostgreSQL 18 and later).
	InvalidationIdleTimeout InvalidationReason = "idle_timeout"
)

type LSN

type LSN uint64

LSN is a PostgreSQL log sequence number.

func MarkWAL added in v0.4.0

func MarkWAL(ctx context.Context, tx pgx.Tx) (LSN, error)

MarkWAL writes a marker into the WAL from inside tx and returns the position just past it. Every transaction visible to tx's snapshot committed before the marker, so a stream confirmed past the marker's position has delivered every change the snapshot saw.

The marker is a non-transactional logical message with an empty payload. The server writes it to the WAL at once, outside any transaction, and tx's commit — a transaction that wrote WAL but holds no transaction ID — asks the WAL writer to flush through it, so the walsender reads past the marker within the WAL writer's delay whatever else is open on the server. The server's insert position would bound the same commits, but it can sit in a WAL tail that nothing flushes while another session holds a transaction open after its last write, and a consumer cannot confirm what the walsender cannot read. The message names no table and the stream does not ask for messages, so the decoder skips it and the shadow is not written.

func ParseLSN added in v0.4.0

func ParseLSN(s string) (LSN, error)

ParseLSN reads the PostgreSQL X/Y representation — the text form of a pg_lsn value — back into an LSN. Both halves are hexadecimal and each must fit in 32 bits; anything else is an error naming the input.

func (LSN) String

func (l LSN) String() string

String renders the PostgreSQL X/Y representation.

type PublicationPrivilegeError added in v0.4.0

type PublicationPrivilegeError struct {
	Publication string
	Database    string
	// Privilege is the database privilege the role lacks.
	Privilege string
	Err       error
}

PublicationPrivilegeError is CreateSlot's refusal when the connected role may not create the route's publication. CREATE PUBLICATION needs the named privilege on the database; nothing has been created when it is returned. It wraps the server's own error, so the SQLSTATE stays reachable through errors.As.

func (*PublicationPrivilegeError) Error added in v0.4.0

func (e *PublicationPrivilegeError) Error() string

func (*PublicationPrivilegeError) Unwrap added in v0.4.0

func (e *PublicationPrivilegeError) Unwrap() error

Unwrap exposes the server's error.

type RetainedWAL added in v0.4.0

type RetainedWAL struct {
	Bytes int64
	Known bool
}

RetainedWAL is the WAL a slot keeps on the volume. Known is false when the server cannot measure it — the slot has no restart position, as after the server removed the WAL it needed, or the server is in recovery and has no write position to measure against — so an unknown amount is never read as nothing retained.

type Slot added in v0.4.0

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

Slot is a logical replication slot this package created, with the replication connection that created it still open. The connection is kept because the exported snapshot lives only as long as the walsender's transaction, which ends with the connection's next command or its close; a caller that wants to copy from the slot's own snapshot imports it (SET TRANSACTION SNAPSHOT) before either happens. The slot itself is durable and outlives Close.

func CreateSlot added in v0.4.0

func CreateSlot(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, target preflight.CopySwapTarget) (*Slot, error)

CreateSlot creates the single-table publication and the logical replication slot for a copy-and-swap target, both under the name preflight derived for it, and returns the slot with its exported snapshot and consistent point. The publication is created on pool first — a publication the engine already created for exactly this table is reused, one that publishes anything else or anything less is refused as a *ForeignStateError — so a privilege refusal (*PublicationPrivilegeError) leaves no slot behind. The slot is created on a fresh replication connection built from cfg, proven to be on the pool's own cluster and database before the slot exists anywhere; the connection stays open inside the returned Slot. A logical slot of the derived name already present in the target's database is reported as a *SlotExistsError.

No error leaves a slot behind: a refusal before the create makes none, a create the caller's context ends is cancelled on the server — the slot under construction goes with its walsender, and the error carries the context's own error — and a slot the server created but did not describe usably is dropped before the error is returned. The publication is left in place between the two — it is the route's own and the next attempt reuses it. A run calls it under the engine's lock on the slot's name (checkpoint.Store.WithSlotLock), the same lock the reaper holds while it judges a slot, so a slot with no row is one the reaper may drop only once the run's claim has ended: an orphan, never a slot mid-claim.

func ReplaceSlot added in v0.4.0

func ReplaceSlot(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, target preflight.CopySwapTarget) (*Slot, error)

ReplaceSlot drops the engine's slot of the target's derived name, if one is there, and creates a fresh one as CreateSlot does, keeping the publication of the name in place between the two. The slot is dropped as DropSlot drops it — waiting out a holder under ctx alone, refusing a foreign slot of the name as a *ForeignStateError — and the publication is then verified as CreateSlot verifies it, so a publication that is not the route's own is refused rather than adopted.

The publication stays because the source stays live: a write to the target table looks up the publications that publish it while it runs, and a publication dropped in that window fails the write with an internal error. A caller that replaces a lost slot under live traffic must not take the publication away from that traffic. The caller holds the engine's lock on the slot's name, as for CreateSlot.

func (*Slot) Close added in v0.4.0

func (s *Slot) Close(ctx context.Context) error

Close ends the replication connection. The server ends the exported snapshot when the connection's walsender exits, which is after Close returns: a caller that needs the snapshot gone waits for that backend to leave pg_stat_activity. The slot persists.

func (*Slot) ConsistentPoint added in v0.4.0

func (s *Slot) ConsistentPoint() LSN

ConsistentPoint is the LSN from which decoding on this slot yields every change not already visible in the exported snapshot.

func (*Slot) Name added in v0.4.0

func (s *Slot) Name() string

Name is the slot's name, which is also the publication's.

func (*Slot) SnapshotName added in v0.4.0

func (s *Slot) SnapshotName() string

SnapshotName is the exported snapshot's name, importable by another session of the same database while the replication connection's walsender runs.

type SlotExistsError added in v0.4.0

type SlotExistsError struct {
	Name string
}

SlotExistsError is returned by CreateSlot when a logical slot of the derived name already exists in the target's database. Preflight has already ruled out a foreign slot of that name, so this is the route's own earlier slot, and whether to resume on it or drop it is the caller's decision, never this package's.

func (*SlotExistsError) Error added in v0.4.0

func (e *SlotExistsError) Error() string

type SlotInvalidation added in v0.4.0

type SlotInvalidation struct {
	Reason   InvalidationReason
	Reported bool
}

SlotInvalidation is the server's cause for a lost slot. Reported is false on a server that has no invalidation_reason column (before PostgreSQL 17), so a cause the server never had is told apart from a slot the server has not invalidated — which has Reported true and an empty Reason. The lost state (ST-4) is read from WALStatus, never from here: the cause only explains it.

func (SlotInvalidation) String added in v0.4.0

func (i SlotInvalidation) String() string

String renders the cause for an operator: the server's word when it has one, and whether a missing cause is the server's silence or its verdict that nothing is wrong.

type SlotLagExceededError added in v0.4.0

type SlotLagExceededError struct {
	Slot     string
	Retained int64
	Ceiling  int64
}

SlotLagExceededError is the typed abort for a slot over the ceiling: what the slot retained when it was read and the ceiling it crossed, both in WAL bytes. It unwraps to ErrSlotLagCeiling.

func (*SlotLagExceededError) Error added in v0.4.0

func (e *SlotLagExceededError) Error() string

func (*SlotLagExceededError) Unwrap added in v0.4.0

func (e *SlotLagExceededError) Unwrap() error

Unwrap makes every SlotLagExceededError match ErrSlotLagCeiling.

type SlotLostError added in v0.4.0

type SlotLostError struct {
	Slot         string
	Found        bool
	WALStatus    WALStatus
	Invalidation SlotInvalidation
}

SlotLostError is the typed state for a slot the route can no longer decode from. Found is false when no slot of the name exists any more; otherwise WALStatus is the server's verdict, "lost" when WAL the slot needed has been removed, and Invalidation is the server's cause for it when the server reports one. It unwraps to ErrSlotLost.

func (*SlotLostError) Error added in v0.4.0

func (e *SlotLostError) Error() string

func (*SlotLostError) Unwrap added in v0.4.0

func (e *SlotLostError) Unwrap() error

Unwrap makes every SlotLostError match ErrSlotLost.

type SlotStatus added in v0.4.0

type SlotStatus struct {
	Name string
	// Database owns the slot; the route's own slots are in the pool's
	// current database and only those are ever dropped or reaped.
	Database string
	Logical  bool
	// Own is true for a logical slot of the pool's current database, the
	// only kind this route creates, decodes from, drops, or replaces (ST-3).
	// A physical slot or another database's logical slot of the name is
	// foreign, whatever else the catalog says of it.
	Own bool
	// Active is true while a walsender or a backend holds the slot;
	// ActivePID is that process, zero when inactive.
	Active    bool
	ActivePID int32
	WALStatus WALStatus
	// RestartLSN is the oldest WAL the slot may still need; zero when the
	// server reports none.
	RestartLSN LSN
	// ConfirmedFlushLSN is the position up to which the consumer has
	// confirmed receipt; zero for a physical slot or when unset.
	ConfirmedFlushLSN LSN
	// Retained is the WAL between RestartLSN and the current write
	// position — what the slot keeps on the volume and what D11's lag
	// ceiling bounds.
	Retained RetainedWAL
	// Conflicting is the server's conflict flag for a logical slot
	// (PostgreSQL 16 and later; false before). Before 17 every
	// invalidation sets it; from 17 only a recovery conflict does —
	// Invalidation carries the cause either way.
	Conflicting bool
	// Invalidation is why the server invalidated the slot, when it says.
	Invalidation SlotInvalidation
	// InactiveSince is when the slot was last released by its holder
	// (PostgreSQL 17 and later); zero while held or when unreported.
	InactiveSince time.Time
}

SlotStatus is one replication slot as pg_replication_slots reports it, with the WAL the slot retains measured against the server's current write position.

func InspectSlot added in v0.4.0

func InspectSlot(ctx context.Context, db dbconn.RowQuerier, name string) (status SlotStatus, found bool, err error)

InspectSlot reads the named slot from pg_replication_slots on db, a pool or one connection of the caller's. found is false when no slot of that name exists on the cluster; a slot of another database, or a physical one, is reported with Own false and its Database so the caller never mistakes it for its own. On a server in recovery the slot's retained WAL is unknown and the rest of the row is reported. The invalidation cause is Reported only on a server that has the column.

func (SlotStatus) Lost added in v0.4.0

func (s SlotStatus) Lost() bool

Lost reports whether the server has given up on the slot: WAL it needs has been removed, so no stream can ever read it again (ST-4).

func (SlotStatus) LostState added in v0.4.0

func (s SlotStatus) LostState() *SlotLostError

LostState is the typed state for a slot the server reports lost, carrying the server's verdict and its cause; it is nil while the slot is readable, and a caller returns it as an error only after checking that.

func (SlotStatus) WithinLagCeiling added in v0.4.0

func (s SlotStatus) WithinLagCeiling(ceiling int64) error

WithinLagCeiling judges the slot against a ceiling in WAL bytes. It is nil while the slot retains at most ceiling bytes; a lost slot is a *SlotLostError before any measure is read, since nothing it retains can be streamed; a slot whose retention the server could not measure is ErrSlotLagUnknown rather than within the ceiling; and a slot over it is a *SlotLagExceededError carrying both figures. A ceiling below one byte is an invariant violation: it would abort every slot.

type Stream added in v0.4.0

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

Stream decodes the route's slot into ChangeEvents. It owns one replication connection from the start position onwards and keeps two positions: what it has delivered to the caller, and what the caller has confirmed applied, which is the only position it ever reports to the server (ST-4 — the slot's confirmed position is the resume point, so it moves only on the caller's word). Both positions order transactions by their commit: a transaction is sent whole when it commits, so a change's own LSN can lie below either of them.

A Stream is used from one goroutine, which must call Next often enough to answer the server's keepalives within wal_sender_timeout. The server's fast shutdown waits for the stream to confirm everything it was sent, so the caller confirms Delivered whenever it holds nothing unapplied, and closes a stream that can neither confirm nor make progress rather than keep it open.

func OpenStream added in v0.4.0

func OpenStream(ctx context.Context, cfg dbconn.Config, catalog dbconn.RowQuerier, target preflight.CopySwapTarget, from LSN) (*Stream, error)

OpenStream starts decoding the target's slot from a position, on a fresh replication connection built from cfg and proven to be a session of the catalog session's cluster on the target's database — a database of the target's name on another cluster holds a slot of the same derived name, whose rows would otherwise arrive as this target's changes. catalog is the pool, or one connection of the caller's for a caller that holds a pool connection open while it opens the stream and must not wait on the pool for a second. The position is the slot's consistent point for a first run or the checkpointed applied position for a resume; the server replays every transaction that committed above the slot's confirmed position, so a resume sees again what it applied but never confirmed. The exported snapshot of a Slot is unaffected, since the slot's own connection is not used.

func (*Stream) Close added in v0.4.0

func (s *Stream) Close(ctx context.Context) error

Close ends the replication connection. The slot persists with the position last confirmed.

func (*Stream) Confirm added in v0.4.0

func (s *Stream) Confirm(ctx context.Context, lsn LSN) error

Confirm reports to the server that every transaction that committed at or below lsn has been applied durably, which lets the slot release the WAL below it and makes lsn the point a later stream resumes from. The position must not fall below an earlier confirmation and must not exceed what the stream has delivered: confirming further would let the server discard a transaction the caller never saw. A change whose own LSN lies below lsn is not thereby covered — only its commit is — so the position a caller confirms while changes are unapplied is the Delivered the earliest of them arrived with. The server itself never moves the slot's position backwards, so confirming a position below the slot's current one — which a resumed stream can produce from a replayed transaction's early changes — is accepted and has no effect on the server. A position the server could not be told ends the stream, since the connection can no longer carry a report; the record of what was confirmed is left where it was.

func (*Stream) Confirmed added in v0.4.0

func (s *Stream) Confirmed() LSN

Confirmed is the position last reported to the server as applied; zero before the first Confirm.

func (*Stream) Delivered added in v0.4.0

func (s *Stream) Delivered() LSN

Delivered is the position every transaction yielded so far committed at or below, and the ceiling of what the caller may confirm.

func (*Stream) Next added in v0.4.0

func (s *Stream) Next(ctx context.Context, wait time.Duration) (Delivery, error)

Next yields the next delivery: a decoded change, or a progress-only delivery when a transaction commits or the server sends a keepalive. When nothing arrives within wait it yields the current position with no change, so a quiet table never blocks the caller for longer than wait. A keepalive that asks for a reply is answered with the confirmed position, never the server's own. An error from the server, a change the stream cannot decode, a report the connection cannot carry, or the server ending replication (ErrStreamEnded) ends the stream: the error is returned now and from every later call.

A wait that runs out is also reported to the server, with the confirmed position, so the stream is never silent for longer than wait. Each wait that runs out costs one report, so on a quiet table wait is also the report interval: a caller that polls with a short wait sends a message per call, and before the first Confirm each report draws a keepalive back. The report is what wakes a walsender that missed the signal for committed WAL: the walsender registers for that signal only after it has checked the flush position, and a commit that lands in between is noticed only on its next wake — a message from the client, or its own keepalive tick at half wal_sender_timeout. Logical replication subscribers mask the same gap by reporting their status on an interval; the stream reports on the caller's wait instead, so the changes it is owed arrive within wait, not within half wal_sender_timeout. The report's write is bounded by neither wait nor ctx: a peer that has stopped reading can hold the call until the socket's send buffer is full and then fails.

func (*Stream) ServerWALEnd added in v0.4.0

func (s *Stream) ServerWALEnd() LSN

ServerWALEnd is the walsender's send position from its last keepalive — the end of the last record it decoded — and never less than Delivered. A change does not move it: a change's XLogData carries the change's own position, which under commit ordering can lie below Delivered. Delivered subtracted from it is a lower bound on the stream's lag, not the lag itself: while the walsender works through a backlog, most of the backlog is WAL it has not decoded yet, so the figure stays small exactly when the stream is furthest behind. Lag against the server's WAL end is measured on a pool, against pg_current_wal_lsn(). Delivered until the server reports.

func (*Stream) Slot added in v0.4.0

func (s *Stream) Slot() string

Slot is the name of the slot the stream decodes, so a caller can inspect the slot it is confirming to.

func (*Stream) Start added in v0.4.0

func (s *Stream) Start() LSN

Start is the position decoding was requested from. The server never decodes from below the slot's confirmed position, so a request below it is forwarded there; what the stream was actually sent first shows in the first delivery's position.

type WALStatus added in v0.4.0

type WALStatus string

WALStatus is pg_replication_slots.wal_status: the server's own verdict on whether the WAL a slot still needs is there to be read.

const (
	// WALStatusReserved means the slot's WAL is within max_wal_size.
	WALStatusReserved WALStatus = "reserved"
	// WALStatusExtended means the slot holds WAL past max_wal_size, bounded
	// by max_slot_wal_keep_size or unbounded when that is -1.
	WALStatusExtended WALStatus = "extended"
	// WALStatusUnreserved means the slot's WAL is no longer protected from
	// removal and will be lost at the next checkpoint.
	WALStatusUnreserved WALStatus = "unreserved"
	// WALStatusLost means WAL the slot needs has been removed; the slot can
	// never be read again (ST-4 slot loss).
	WALStatusLost WALStatus = "lost"
)

Jump to

Keyboard shortcuts

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