/** * Optional Postgres LISTEN/NOTIFY signal layer. * * Postgres is OPTIONAL for the broker (see ADR-0003). When wired up, it acts * as a sub-second wake-up channel for consumers (`pg_notify` after every * successful `AppendBlock`) and a diagnostic head-pointer table * (`streams.topic_heads`). The invariant from ADR-0003 that this module * enforces: * * **Postgres is a LOWER BOUND. Blob wins.** * * Consequences for this module: * - If the producer's `emit()` transaction fails, we log to OTEL but DO NOT * fail the producer's `send()`. The bytes are already durable in blob; * `topic_heads` and the NOTIFY are best-effort. The consumer will catch * up via its polling fallback or its next NOTIFY. * - The producer MUST do the `topic_heads` upsert AND the `pg_notify` in * ONE transaction so consumers never see a NOTIFY for un-durable * bookkeeping. A NOTIFY without a matching `topic_heads` row is an * operator pathology, not a correctness one. * - On any listener reconnect, the consumer module that owns the listener * MUST trigger a catch-up read. `pg_notify` is not buffered: a NOTIFY * emitted during the reconnect window is lost. The listener surfaces a * `'reconnect'` hook for exactly this purpose; the consumer wires its * catch-up read to it. * * Library footprint: * - We use `pg`'s `pool.query` for the emitter (no per-call connection * setup; the pool is owned by the caller). * - We use `pg-listen` (Andy Wermke, single maintainer) for the listener. * It is ~500 lines wrapping the `pg` driver's `notification` event and * handles reconnection cleanly. Mitigation if it ever dies: fork or * inline; the surface area we depend on is `connect/close/listenTo` and * two events (`notification`, `reconnect`). * * OTEL spans: * - `signal.emit` — one per `emit()` call, attrs: `signal.gen`, * `signal.offset`, `signal.byte`, `db.system='postgresql'`, * `messaging.destination=`. * - `signal.listen.connect` — one per successful initial `connect()`. * - `signal.listen.reconnect` — one per `pg-listen` reconnect event. * - `signal.listen.notify` — one per inbound NOTIFY processed. * * OTEL metrics: * - `blob_data_streamer.signal.emit_duration_ms` (histogram). * - `blob_data_streamer.signal.notifications_received_total` (counter). */ import type { ClientConfig, Pool } from 'pg'; /** * Postgres channel name for a `(tenant, topic)` pair. * * Postgres channel names follow identifier rules: ≤ 63 bytes, case-sensitive, * the characters that don't need quoting are `[a-zA-Z0-9_]` plus dollar sign. * We prefix every channel with `bds_` to namespace from any other app sharing * the database, then sanitise the tenant + topic by replacing any character * outside `[a-z0-9_]` with `_`. If the resulting name exceeds 63 bytes we * truncate from the right; collision risk is acceptable because * `(tenant, topic)` is also the primary key of `streams.topic_heads`, and * operators choose those names. * * The function is pure and deterministic — same input always yields the same * channel name. */ export declare function notifyChannel(tenant: string, topic: string): string; /** * Payload emitted on every successful `AppendBlock`. The consumer uses * `byte` to drive its next range-read on `current-N.jsonl`. */ export type SignalPayload = { /** Generation of `current-N.jsonl` at the moment of the append. */ readonly gen: number; /** Logical record offset of the head after this append. Wire format: decimal string. */ readonly offset: bigint; /** Committed byte length of `current-N.jsonl` after this append. */ readonly byte: number; /** ISO-8601 timestamp the producer recorded for this append. */ readonly at: string; }; /** * Producer-side handle. Created by {@link createSignalEmitter}. */ export type SignalEmitter = { /** * Update `streams.topic_heads` and `pg_notify` in a single transaction. * * On failure: logged to OTEL and returns normally (does NOT throw). This is * deliberate: the producer's `send()` MUST NOT fail because of a Postgres * blip — the bytes are already durable in blob. See ADR-0003. */ emit(payload: SignalPayload): Promise; /** * Release any per-emitter resources. Does NOT end the underlying pool — * the pool was passed in by the caller and is owned by them. */ close(): Promise; }; export type CreateSignalEmitterOptions = { /** * Caller-owned `pg.Pool`. We never `end()` it. Letting the caller manage * pool lifecycle keeps this module side-effect-free at config time and * makes it trivial to share one pool across many emitters/listeners. */ readonly pgPool: Pool; readonly tenant: string; readonly topic: string; /** * Diagnostic identifier of the current leader (producer). Persisted in * `.topic_heads.leader_id`. Optional — purely for operator * convenience when triaging "which producer wrote this?". */ readonly leaderId?: string; /** * Schema containing `topic_heads`. Must match the `schemaName` passed * to {@link applyMigrations}. Defaults to `streams` (the * `DEFAULT_SCHEMA_NAME` constant). Validated against the standard * identifier regex before being interpolated into the upsert SQL. */ readonly schemaName?: string; }; /** * Construct a producer-side emitter bound to `(tenant, topic)`. The channel * is resolved via {@link notifyChannel}. Idempotent at the database level: * `topic_heads` is upserted on the primary key `(tenant, topic)`. * * See ADR-0003. */ export declare function createSignalEmitter(opts: CreateSignalEmitterOptions): Promise; /** * Consumer-side handle. Created by {@link createSignalListener}. */ export type SignalListener = { /** * Register a handler for inbound NOTIFY payloads. Returns an unsubscribe * function. Multiple handlers may be registered — every payload is fanned * out to all of them. */ onSignal(handler: (payload: SignalPayload) => void): () => void; /** * Register a handler for `pg-listen`'s reconnect event. Consumers must * trigger a catch-up read on every reconnect because `pg_notify` is not * buffered. Returns an unsubscribe function. */ onReconnect(handler: () => void): () => void; /** Tear down the listener and close its underlying `pg-listen` subscriber. */ close(): Promise; }; /** * Connection input for {@link createSignalListener}. Accept either: * * - A libpq connection string (`postgres://...`) — the simple case for * connection-string-bearing environments. * - A `pg.ClientConfig` object — the right shape for managed identity / AAD. * `pg`'s `password` field accepts `() => Promise`, so a caller can * wire `@azure/identity`'s `DefaultAzureCredential.getToken(...)` to a * per-connect token-refresh callback. `pg-listen` passes the config through * to `pg.Client` unchanged, so the function-password contract works for the * subscriber and any reconnect. * * See `CLAUDE.md` §Credentials and authentication for the managed-identity * pattern. */ export type SignalListenerConnection = string | ClientConfig; export type CreateSignalListenerOptions = { readonly connection: SignalListenerConnection; readonly tenant: string; readonly topic: string; /** * `pg-listen` hardening overrides. The broker applies safe defaults; * callers tune only when their environment needs different behaviour. * * - `paranoidChecking` (default `30_000` ms): cadence at which * `pg-listen` issues a no-op SELECT to detect silent TCP drops * (common in cloud NAT environments on idle connections). Set * `false` to disable. * - `retryLimit` (default `10`): max reconnect attempts before * surfacing the failure. Set `0` for infinite retry, which masks * permanently-broken Postgres credentials behind silent * forever-retry — generally undesirable. * - `retryTimeout` (default `60_000` ms): per-attempt timeout. */ readonly pgListen?: { readonly paranoidChecking?: number | false; readonly retryLimit?: number; readonly retryTimeout?: number; }; }; /** * Construct a consumer-side listener bound to `(tenant, topic)`. The listener * connects immediately (so we surface bad credentials / unreachable DBs at * `createSignalListener` time, not at first NOTIFY). It then issues `LISTEN` * on the resolved channel. * * Reconnect handling is delegated to `pg-listen`. On reconnect, the * `onReconnect` callbacks fire — wire your consumer's catch-up read to one of * them. */ export declare function createSignalListener(opts: CreateSignalListenerOptions): Promise; //# sourceMappingURL=postgresSignal.d.ts.map