Replicant.Connection (Replicant v3.0.0)

Copy Markdown View Source

The Postgrex.ReplicationConnection that owns the replication slot and closes the exactly-once seam (spec §2/§4/§8). It:

  • replies to a reply-requested keepalive with the last durably-checkpointed LSN while any published transaction is in flight — never advancing the slot past un-persisted publication data (walex's fire-and-forget wal_end+1 is the at-most-once bug this fixes). When IDLE (no open transaction and the checkpoint caught up), a :state_mirror sink advances the slot to the keepalive wal_end so a quiet-but-filtered publication stops pinning WAL (spec A1) — the intervening WAL carries nothing for the publication. An :append_log sink never performs that filtered-WAL advance: it acknowledges only its durable checkpoint and uses an ordinary published heartbeat transaction to release retained WAL;
  • decodes each XLogData payload behind Plan 1's value-free boundary and forwards the decoded message to Replicant.AssemblerServer — it never applies the sink, so it is always free to answer keepalives;
  • counts payload bytes and messages sent to, but not yet processed by, the assembler. WAL-position distance is not a queue-size estimate: unrelated WAL and segment switches can advance positions without publication data;
  • pauses and resumes socket delivery at the intake watermarks described in Replicant.start_link/1. Cumulative, connection-scoped processing credits cannot advance the durable checkpoint;
  • advances the ack asynchronously on {:sink_committed, L} from the AssemblerServer;
  • on connect/reconnect detects an invalidated slot (wal_status = 'lost' or conflicting on PG16) and halts the pipeline fail-closed — never silently dropping and recreating the slot (spec §8 R-ISO).

The connect chain is a handle_result/2 state machine: :identity_check → :recovery_check → :publication_check → :invalidation_check → (:create_slot if absent) → :streaming.

Backpressure and retained transactions

This implementation requires Postgrex's pause/resume callback extension. Pausing keeps the connection and slot ownership alive. Because incoming keepalives are paused, Replicant sends feedback at the durable checkpoint using a cadence derived from the replication session's wal_sender_timeout.

The assembler separately budgets retained transaction/batch payloads, spilling streamed transactions or flushing committed batches. An oversized transaction that cannot spill halts with :buffer_limit_exceeded, not a pause that would prevent its own Commit from arriving. Neither budget is an exact RSS cap: decoded-term overhead, socket buffers, and a one-message overshoot are additional.

Summary

Functions

Returns a specification to start this module under a supervisor.

Classify a pg_replication_slots invalidation-status result (spec §5/§8). [] → :absent. On the PG15 1-col row [wal_status] (PG15 has no conflicting column): wal_status = "lost" → {:invalidated, :wal_lost}, otherwise :ok. On the PG16 2-col row [wal_status, conflicting]: wal_status = "lost" → {:invalidated, :wal_lost}; conflicting = true → {:invalidated, :conflict}; otherwise :ok. On the PG17 4-col row [wal_status, conflicting, invalidation_reason, synced]: the legacy signals classify first (same as above), then any non-empty invalidation_reason → {:invalidated, <fixed atom>} via invalidation_reason_atom/1 (never String.to_atom); a nil/"" reason is :ok.

The default queued/retained payload budget in bytes when the config omits it.

Encode a Standby Status Update reporting lsn as the write/flush/apply position (spec §2 — the slot never advances past the durable checkpoint). reply_requested is 0 (we volunteer status). clock is microseconds since the PG 2000 epoch.

Start the replication connection for a pipeline (called by Replicant.Pipeline).

The Registry via-name a pipeline's Connection registers under.

Types

step()

@type step() ::
  :disconnected
  | :draining_assembler
  | :identity_check
  | :recovery_check
  | :publication_check
  | :decoder_table_discovery
  | :decoder_table_info
  | :invalidation_check
  | :waiting_for_slot
  | :create_slot
  | :create_export_slot
  | :create_incremental_slot
  | :read_backfill_origin
  | :read_slot_origin
  | :snapshotting
  | :streaming

t()

@type t() :: %Replicant.Connection{
  backfill_floor: Replicant.lsn() | nil,
  batch_delivery: keyword() | nil,
  checkpoint_lsn: Replicant.lsn(),
  checkpoint_state: :present | :empty | :fault | :fault_permanent,
  checkpoint_store: keyword() | nil,
  command_error: %{
    count: non_neg_integer(),
    max_retries: non_neg_integer(),
    store_paced: boolean()
  },
  connection: keyword(),
  decoder: %{
    kind: Replicant.Decoder.Plugin.decoder_atom(),
    cache: Replicant.Decoder.Plugin.cache(),
    discovered: [{String.t(), String.t()}] | nil,
    replication_sets: [String.t()] | nil
  },
  failover: boolean(),
  flow: struct(),
  frontier: %{epoch: non_neg_integer(), last_cast: non_neg_integer()},
  go_forward_only: boolean(),
  in_recovery: boolean(),
  in_stream: boolean(),
  in_txn: boolean(),
  last_commit_lsn: Replicant.lsn(),
  max_inflight_lag: pos_integer(),
  messages: boolean(),
  open_streams: MapSet.t(),
  publication: [String.t()] | nil,
  reader_pid: pid() | nil,
  received_lsn: Replicant.lsn(),
  server_version_num: non_neg_integer(),
  sink: module(),
  slot_name: String.t(),
  snapshot: boolean() | keyword(),
  step: step(),
  store_retry_count: non_neg_integer(),
  stream_floor_lsn: Replicant.lsn() | nil,
  streaming: keyword() | nil
}

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

classify_slot_status(list)

@spec classify_slot_status([[term()]]) ::
  :absent
  | :ok
  | {:invalidated,
     :wal_lost
     | :conflict
     | :rows_removed
     | :wal_level_insufficient
     | :invalidated}

Classify a pg_replication_slots invalidation-status result (spec §5/§8). [] → :absent. On the PG15 1-col row [wal_status] (PG15 has no conflicting column): wal_status = "lost" → {:invalidated, :wal_lost}, otherwise :ok. On the PG16 2-col row [wal_status, conflicting]: wal_status = "lost" → {:invalidated, :wal_lost}; conflicting = true → {:invalidated, :conflict}; otherwise :ok. On the PG17 4-col row [wal_status, conflicting, invalidation_reason, synced]: the legacy signals classify first (same as above), then any non-empty invalidation_reason → {:invalidated, <fixed atom>} via invalidation_reason_atom/1 (never String.to_atom); a nil/"" reason is :ok.

default_max_inflight_lag()

@spec default_max_inflight_lag() :: pos_integer()

The default queued/retained payload budget in bytes when the config omits it.

encode_status_update(lsn)

@spec encode_status_update(Replicant.lsn()) :: binary()

Encode a Standby Status Update reporting lsn as the write/flush/apply position (spec §2 — the slot never advances past the durable checkpoint). reply_requested is 0 (we volunteer status). clock is microseconds since the PG 2000 epoch.

start_link(config)

@spec start_link(Replicant.Config.t()) :: {:ok, pid()} | {:error, term()}

Start the replication connection for a pipeline (called by Replicant.Pipeline).

via(slot_name)

@spec via(String.t()) :: {:via, module(), term()}

The Registry via-name a pipeline's Connection registers under.