@syncular/server 0.39.1 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -135,7 +135,10 @@ the complete [backup and restore runbook](https://syncular.dev/server-operations
135
135
  A `SyncError` answers with its catalog code and status. By default, any other exception an
136
136
  adapter catches answers `sync.internal_error` and is handed to
137
137
  `SyncServerConfig.onError` exactly once; a throwing observer does not change
138
- the response. The same config accepts an optional synchronous `mapError` hook:
138
+ the response. A `SyncError` never reaches `onError`: observe a catalog failure
139
+ through the `request.handled` event (`outcome`, `errorCode`, `clientId`) or the
140
+ client's stored `lastErrorCode` / `consecutiveFailures` / `lastRoundAtMs`, which
141
+ `ServerStorage.recordClientRoundFailure` updates on every failed round. The same config accepts an optional synchronous `mapError` hook:
139
142
  after `onError` observes the original, `mapError` may return a catalog
140
143
  `SyncError` (with structured `details`, for example `retryAfterMs`) that the
141
144
  adapter answers instead. Return `undefined` to keep `sync.internal_error`. A
@@ -1292,15 +1295,13 @@ install no fanout at all.
1292
1295
  ```ts
1293
1296
  import { PostgresFanout, type PgNotificationConnection } from '@syncular/server';
1294
1297
 
1295
- // node-postgres: a dedicated Client for LISTEN + the pool for NOTIFY.
1298
+ // Bun.sql over the direct (unpooled) URL: LISTEN needs a session-mode
1299
+ // connection, and Bun.sql reconnects a dropped listener and re-runs onListen.
1300
+ const sql = new Bun.SQL(process.env.DATABASE_URL_DIRECT!);
1296
1301
  const conn: PgNotificationConnection = {
1297
- async listen(channel, handler) {
1298
- const client = await pool.connect(); // long-lived, NOT released
1299
- client.on('notification', (m) => m.payload && handler(m.payload));
1300
- await client.query(`LISTEN ${channel}`);
1301
- },
1302
- notify: (channel, payload) =>
1303
- pool.query('SELECT pg_notify($1, $2)', [channel, payload]).then(() => {}),
1302
+ listen: (channel, handler, onListen) =>
1303
+ sql.listen(channel, handler, onListen).then(() => {}),
1304
+ notify: (channel, payload) => sql.notify(channel, payload).then(() => {}),
1304
1305
  };
1305
1306
  const fanout = new PostgresFanout(conn);
1306
1307
  await fanout.install(hub); // start the LISTEN loop
@@ -1308,10 +1309,16 @@ await fanout.install(hub); // start the LISTEN loop
1308
1309
  await fanout.notifyCommit(partition, commitSeq);
1309
1310
  ```
1310
1311
 
1312
+ Notifications sent while a listener session is down are lost. Every
1313
+ `onListen` after the first therefore wakes all local sessions with
1314
+ `catchup-required` (`hub.wakeAll`). A node-postgres adapter reconnects its
1315
+ dedicated `Client` on `end` and calls `onListen` after each `LISTEN`.
1316
+
1311
1317
  pglite is single-connection and cannot exercise cross-connection NOTIFY,
1312
1318
  so the fanout integration test is env-gated on `SYNCULAR_PG_URL` (it wires
1313
- Bun.sql as a worked example) and skips cleanly; the payload encode/parse
1314
- and wake wiring are unit-tested hermetically.
1319
+ Bun.sql as a worked example and terminates the listener backend to cover the
1320
+ reconnect path) and skips cleanly; the payload encode/parse and wake wiring
1321
+ are unit-tested hermetically.
1315
1322
 
1316
1323
  ### Bench lane
1317
1324
 
package/dist/admin.d.ts CHANGED
@@ -51,6 +51,12 @@ export interface AdminClient {
51
51
  readonly connected?: boolean;
52
52
  /** When the client's oldest open socket opened. */
53
53
  readonly connectedSinceMs?: number;
54
+ /** When its last sync round finished, successfully or not. */
55
+ readonly lastRoundAtMs?: number;
56
+ /** Catalog code of its last round; present only while that round failed. */
57
+ readonly lastErrorCode?: string;
58
+ /** Rounds failed in a row since its last success; absent at zero. */
59
+ readonly consecutiveFailures?: number;
54
60
  }
55
61
  export interface AdminListClientsOptions {
56
62
  /** Default 200. */
package/dist/admin.js CHANGED
@@ -926,6 +926,15 @@ export class SyncularAdmin {
926
926
  ? { connected: connectedSinceMs !== undefined }
927
927
  : {}),
928
928
  ...(connectedSinceMs !== undefined ? { connectedSinceMs } : {}),
929
+ ...(record.lastRoundAtMs !== undefined
930
+ ? { lastRoundAtMs: record.lastRoundAtMs }
931
+ : {}),
932
+ ...(record.lastErrorCode !== undefined
933
+ ? { lastErrorCode: record.lastErrorCode }
934
+ : {}),
935
+ ...(record.consecutiveFailures !== undefined
936
+ ? { consecutiveFailures: record.consecutiveFailures }
937
+ : {}),
929
938
  };
930
939
  };
931
940
  }
@@ -124,6 +124,7 @@ export declare class D1ServerStorage implements ServerStorage {
124
124
  scanRowsByIndex(partition: string, query: IndexRowScanQuery): Promise<StoredRow[]>;
125
125
  getClientRecord(partition: string, clientId: string): Promise<ClientRecord | undefined>;
126
126
  putClientRecord(partition: string, record: ClientRecord): Promise<void>;
127
+ recordClientRoundFailure(partition: string, clientId: string, actorId: string, errorCode: string, atMs: number): Promise<void>;
127
128
  advanceClientCursor(partition: string, clientId: string, actorId: string, logEpoch: string, cursor: number, updatedAtMs: number): Promise<void>;
128
129
  updateClientCursor(partition: string, clientId: string, cursor: number, updatedAtMs: number): Promise<void>;
129
130
  getActiveClientCursorFloor(partition: string, cutoffMs: number): Promise<number | null>;
@@ -1,7 +1,7 @@
1
1
  var _a;
2
2
  import { validateCommitPruneQuery } from './prune.js';
3
3
  import { StorageQueryError } from './storage-errors.js';
4
- import { PARTITION_TOUCH_INTERVAL_MS } from './storage.js';
4
+ import { clientRoundState, PARTITION_TOUCH_INTERVAL_MS } from './storage.js';
5
5
  /**
6
6
  * Cloudflare D1 server storage for Workers deployments.
7
7
  *
@@ -46,9 +46,9 @@ import { PARTITION_TOUCH_INTERVAL_MS } from './storage.js';
46
46
  import { decodeRow } from '@syncular/core';
47
47
  import { bindAuthoritativePartition, prepareAuthoritativeQuery, } from './authoritative-query.js';
48
48
  import { syncError } from './errors.js';
49
- import { assertAppendOnlyMigration, assertPhysicalColumns, assertStoredLayouts, commitWindowPageSql, LATEST_SCOPED_CHANGE_SEQ_SQLITE_SQL, deleteRowSql, deleteSqliteRowScopesSql, dropTableDdl, indexRowPageStatement, layoutsOf, migratePayload, parseLayouts, quoteIdent, retiredTableNames, rewritePlan, rewriteRowSql, rewriteValues, SCHEMA_META_DDL_SQLITE, SYNC_COLUMN_VERSIONS_COLUMN, SYNC_PARTITION_COLUMN, SYNC_PAYLOAD_COLUMN, SYNC_ROW_ID_COLUMN, SYNC_SCOPES_COLUMN, SYNC_VERSION_COLUMN, scanRowPageSql, schemaDdl, SQLITE_TABLE_INDEXES_SQL, sqliteIndexSignatures, selectRowScopesSql, selectRowSql, selectRowsForRewriteSql, tableColumnNames, toSqlValue, upsertSql, upsertValues, } from './relational-rows.js';
49
+ import { assertAppendOnlyMigration, assertPhysicalColumns, assertStoredLayouts, commitWindowPageSql, LATEST_SCOPED_CHANGE_SEQ_SQLITE_SQL, deleteRowSql, deleteSqliteRowScopesSql, dropTableDdl, indexRowPageStatement, layoutsOf, migratePayload, parseLayouts, quoteIdent, retiredTableNames, rewritePlan, rewriteRowSql, rewriteValues, SCHEMA_META_DDL_SQLITE, SYNC_COLUMN_VERSIONS_COLUMN, SYNC_PARTITION_COLUMN, SYNC_PAYLOAD_COLUMN, SYNC_ROW_ID_COLUMN, SYNC_SCOPES_COLUMN, SYNC_VERSION_COLUMN, scanRowPageSql, schemaDdl, serverIndexDdl, SQLITE_TABLE_INDEXES_SQL, sqliteIndexSignatures, selectRowScopesSql, selectRowSql, selectRowsForRewriteSql, tableColumnNames, toSqlValue, upsertSql, upsertValues, } from './relational-rows.js';
50
50
  import { matchesEffective } from './scopes.js';
51
- import { asUint8Array, collectCommitWindowPage, deserializePushResult, placeholders, ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL, eraseScopeValueHistoryParams, LIST_SCOPE_VALUE_ROWS_SQLITE_SQL, serializePushResult, sqliteDdlStatements, toStoredChange, toStoredRow, } from './sqlite-dialect.js';
51
+ import { asUint8Array, collectCommitWindowPage, deserializePushResult, placeholders, ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL, eraseScopeValueHistoryParams, LIST_SCOPE_VALUE_ROWS_SQLITE_SQL, serializePushResult, sqliteDdlStatements, SYNC_CLIENT_ROUND_COLUMNS, toStoredChange, toStoredRow, } from './sqlite-dialect.js';
52
52
  import { isD1ConstraintError, StorageConstraintError } from './storage-errors.js';
53
53
  import { assertScopeIndexedScan, resolveIndexRowScan } from './storage-query.js';
54
54
  function toStoredReaction(record) {
@@ -617,6 +617,11 @@ export class D1ServerStorage {
617
617
  if (!results.some((column) => column.name === 'wire_version')) {
618
618
  await this.#db.exec('ALTER TABLE sync_clients ADD COLUMN wire_version INTEGER NOT NULL DEFAULT 1;');
619
619
  }
620
+ for (const [name, definition] of Object.entries(SYNC_CLIENT_ROUND_COLUMNS)) {
621
+ if (!results.some((column) => column.name === name)) {
622
+ await this.#db.exec(`ALTER TABLE sync_clients ADD COLUMN ${name} ${definition};`);
623
+ }
624
+ }
620
625
  }
621
626
  /** Resolve a table's compiled schema; row operations require `ensureSchema`. */
622
627
  table(name) {
@@ -713,6 +718,30 @@ export class D1ServerStorage {
713
718
  primaryKeyPosition: column.pk,
714
719
  })), 'sqlite');
715
720
  }
721
+ // A database from before the round-state columns gains them in place.
722
+ statementsExecuted++;
723
+ const clientColumns = await this.#db
724
+ .prepare('PRAGMA table_info("sync_clients")')
725
+ .all();
726
+ const missingRoundColumns = Object.entries(SYNC_CLIENT_ROUND_COLUMNS).filter(([name]) => !clientColumns.results.some((column) => column.name === name));
727
+ if (missingRoundColumns.length > 0) {
728
+ await batch(missingRoundColumns.map(([name, definition]) => this.#db.prepare(`ALTER TABLE sync_clients ADD COLUMN ${name} ${definition}`)));
729
+ }
730
+ // Server-only indexes reconcile at every open of a database already at
731
+ // this version: they never reach a client, so no version bump is needed.
732
+ const indexes = new Map();
733
+ for (const table of tables) {
734
+ statementsExecuted++;
735
+ const { results } = await this.#db
736
+ .prepare(SQLITE_TABLE_INDEXES_SQL)
737
+ .bind(table.name)
738
+ .all();
739
+ indexes.set(table.name, new Map(Object.entries(sqliteIndexSignatures(results))));
740
+ }
741
+ const reconcile = serverIndexDdl(schema, indexes);
742
+ if (reconcile.length > 0) {
743
+ await batch(reconcile.map((sql) => this.#db.prepare(sql)));
744
+ }
716
745
  this.#tables = schema.tables;
717
746
  this.#schemaVersion = schema.version;
718
747
  return { complete: true, statementsExecuted };
@@ -816,12 +845,11 @@ export class D1ServerStorage {
816
845
  const columns = await this.#db
817
846
  .prepare('PRAGMA table_info("sync_clients")')
818
847
  .all();
819
- const needsWireVersion = !columns.results.some((column) => column.name === 'wire_version');
820
- if (!(await save({ ...state, phase: 'prepare', offset: 0 }, needsWireVersion
821
- ? [
822
- this.#db.prepare('ALTER TABLE sync_clients ADD COLUMN wire_version INTEGER NOT NULL DEFAULT 1'),
823
- ]
824
- : [])))
848
+ const missingColumns = Object.entries({
849
+ wire_version: 'INTEGER NOT NULL DEFAULT 1',
850
+ ...SYNC_CLIENT_ROUND_COLUMNS,
851
+ }).filter(([name]) => !columns.results.some((column) => column.name === name));
852
+ if (!(await save({ ...state, phase: 'prepare', offset: 0 }, missingColumns.map(([name, definition]) => this.#db.prepare(`ALTER TABLE sync_clients ADD COLUMN ${name} ${definition}`)))))
825
853
  break;
826
854
  }
827
855
  else if (state.phase === 'prepare') {
@@ -1562,7 +1590,7 @@ export class D1ServerStorage {
1562
1590
  }
1563
1591
  async getClientRecord(partition, clientId) {
1564
1592
  const record = await this.#db
1565
- .prepare('SELECT client_id, actor_id, wire_version, cursor, subscriptions, updated_at_ms FROM sync_clients WHERE partition=? AND client_id=?')
1593
+ .prepare('SELECT client_id, actor_id, wire_version, cursor, subscriptions, updated_at_ms, last_round_at_ms, last_error_code, consecutive_failures FROM sync_clients WHERE partition=? AND client_id=?')
1566
1594
  .bind(partition, clientId)
1567
1595
  .first();
1568
1596
  if (record === null)
@@ -1574,6 +1602,7 @@ export class D1ServerStorage {
1574
1602
  cursor: record.cursor,
1575
1603
  updatedAtMs: record.updated_at_ms,
1576
1604
  subscriptions: JSON.parse(record.subscriptions),
1605
+ ...clientRoundState(record.last_round_at_ms, record.last_error_code, record.consecutive_failures),
1577
1606
  };
1578
1607
  }
1579
1608
  async putClientRecord(partition, record) {
@@ -1581,14 +1610,26 @@ export class D1ServerStorage {
1581
1610
  // (partition, client_id). Every non-key field is written from the new
1582
1611
  // record; a delete-and-insert would drop and recreate the row instead.
1583
1612
  await this.#db
1584
- .prepare(`INSERT INTO sync_clients(partition, client_id, actor_id, wire_version, cursor, subscriptions, updated_at_ms) VALUES (?,?,?,?,?,?,?)
1613
+ .prepare(`INSERT INTO sync_clients(partition, client_id, actor_id, wire_version, cursor, subscriptions, updated_at_ms, last_round_at_ms) VALUES (?,?,?,?,?,?,?,?)
1585
1614
  ON CONFLICT(partition, client_id) DO UPDATE SET
1586
1615
  actor_id=excluded.actor_id,
1587
1616
  wire_version=excluded.wire_version,
1588
1617
  cursor=excluded.cursor,
1589
1618
  subscriptions=excluded.subscriptions,
1590
- updated_at_ms=excluded.updated_at_ms`)
1591
- .bind(partition, record.clientId, record.actorId, record.wireVersion, record.cursor, JSON.stringify(record.subscriptions), record.updatedAtMs)
1619
+ updated_at_ms=excluded.updated_at_ms,
1620
+ last_round_at_ms=excluded.last_round_at_ms,
1621
+ last_error_code=NULL,
1622
+ consecutive_failures=0`)
1623
+ .bind(partition, record.clientId, record.actorId, record.wireVersion, record.cursor, JSON.stringify(record.subscriptions), record.updatedAtMs, record.updatedAtMs)
1624
+ .run();
1625
+ }
1626
+ async recordClientRoundFailure(partition, clientId, actorId, errorCode, atMs) {
1627
+ await this.#db
1628
+ .prepare(`UPDATE sync_clients
1629
+ SET last_round_at_ms=?, last_error_code=?,
1630
+ consecutive_failures=consecutive_failures+1
1631
+ WHERE partition=? AND client_id=? AND actor_id=?`)
1632
+ .bind(atMs, errorCode, partition, clientId, actorId)
1592
1633
  .run();
1593
1634
  }
1594
1635
  async advanceClientCursor(partition, clientId, actorId, logEpoch, cursor, updatedAtMs) {
@@ -1686,7 +1727,7 @@ export class D1ServerStorage {
1686
1727
  // -- admin/console read surface --------------------------------------------
1687
1728
  async listClientRecords(partition) {
1688
1729
  const { results } = await this.#db
1689
- .prepare('SELECT client_id, actor_id, wire_version, cursor, subscriptions, updated_at_ms FROM sync_clients WHERE partition=? ORDER BY updated_at_ms DESC')
1730
+ .prepare('SELECT client_id, actor_id, wire_version, cursor, subscriptions, updated_at_ms, last_round_at_ms, last_error_code, consecutive_failures FROM sync_clients WHERE partition=? ORDER BY updated_at_ms DESC')
1690
1731
  .bind(partition)
1691
1732
  .all();
1692
1733
  return results.map((record) => ({
@@ -1696,6 +1737,7 @@ export class D1ServerStorage {
1696
1737
  cursor: record.cursor,
1697
1738
  updatedAtMs: record.updated_at_ms,
1698
1739
  subscriptions: JSON.parse(record.subscriptions),
1740
+ ...clientRoundState(record.last_round_at_ms, record.last_error_code, record.consecutive_failures),
1699
1741
  }));
1700
1742
  }
1701
1743
  async listCommitMetadata(partition, query) {
package/dist/handler.js CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { DecodeError, decodeMessage, } from '@syncular/core';
13
13
  import { clockOf, limitsOf, REMOTE_COMMAND_CLIENT_ID_PREFIX, RESOLVER_OUTAGE, touchAuthenticatedPartition, } from './context.js';
14
- import { SyncError, syncError } from './errors.js';
14
+ import { reportError, SyncError, syncError } from './errors.js';
15
15
  import { emitEvent, } from './events.js';
16
16
  import { END_FRAME_BYTES, encodeResponseFrame, responseEnvelopeHeader, } from './frame-bytes.js';
17
17
  import { ACCEPT_EXTERNAL_ROWS, ACCEPT_INLINE_ROWS, clampPullLimits, prepareSections, preparedSection, } from './pull.js';
@@ -495,6 +495,7 @@ async function* streamResponse(plan, ctx, schema, report) {
495
495
  report.outcome = 'error';
496
496
  report.errorCode = error.code;
497
497
  }
498
+ await recordRoundFailure(ctx, plan.header.clientId, error);
498
499
  // §1.6: in-band ERROR, then END, nothing else.
499
500
  yield encodeResponseFrame({
500
501
  type: 'ERROR',
@@ -519,8 +520,15 @@ async function* streamResponse(plan, ctx, schema, report) {
519
520
  */
520
521
  export async function createSyncResponseStream(bytes, ctx) {
521
522
  const sink = ctx.events;
522
- if (sink === undefined)
523
- return createStreamCore(bytes, ctx, undefined);
523
+ if (sink === undefined) {
524
+ try {
525
+ return await createStreamCore(bytes, ctx, undefined);
526
+ }
527
+ catch (error) {
528
+ await recordRoundFailure(ctx, requestClientId(bytes), error);
529
+ throw error;
530
+ }
531
+ }
524
532
  // Instrumented path: measure with the ctx clock, count bytes at the
525
533
  // seam, emit exactly one `request.handled` per request. Every event of
526
534
  // this request carries one `requestId`.
@@ -535,6 +543,7 @@ export async function createSyncResponseStream(bytes, ctx) {
535
543
  return await createStreamCore(bytes, requestCtx, events, startedAtMs);
536
544
  }
537
545
  catch (error) {
546
+ const clientId = requestClientId(bytes);
538
547
  emitEvent(events, {
539
548
  type: 'request.handled',
540
549
  kind: 'sync',
@@ -545,11 +554,51 @@ export async function createSyncResponseStream(bytes, ctx) {
545
554
  bytesIn: bytes.length,
546
555
  bytesOut: 0,
547
556
  outcome: 'rejected',
557
+ ...(clientId !== undefined ? { clientId } : {}),
548
558
  errorCode: error instanceof SyncError ? error.code : 'internal',
549
559
  pushCommits: 0,
550
560
  pulled: false,
551
561
  subscriptions: 0,
552
562
  });
563
+ await recordRoundFailure(ctx, clientId, error);
564
+ throw error;
565
+ }
566
+ }
567
+ /** The `REQ_HEADER` clientId of a request that failed before planning. */
568
+ function requestClientId(bytes) {
569
+ try {
570
+ const message = decodeMessage(bytes);
571
+ const header = message.frames[0];
572
+ return message.msgKind === 'request' && header?.type === 'REQ_HEADER'
573
+ ? header.clientId
574
+ : undefined;
575
+ }
576
+ catch {
577
+ return undefined;
578
+ }
579
+ }
580
+ /**
581
+ * Record a failed round on the client's stored record so an operator can see
582
+ * a stuck client and why. A storage failure here is reported through
583
+ * `onError` and never replaces the round's own outcome.
584
+ */
585
+ async function recordRoundFailure(ctx, clientId, error) {
586
+ if (clientId === undefined)
587
+ return;
588
+ try {
589
+ await ctx.storage.recordClientRoundFailure(ctx.partition, clientId, ctx.actorId, error instanceof SyncError ? error.code : 'sync.internal_error', clockOf(ctx)());
590
+ }
591
+ catch (failure) {
592
+ reportError(failure, ctx.onError, 'sync');
593
+ }
594
+ }
595
+ /** Record a failure thrown while the response streams (after planning). */
596
+ async function* recordedStream(stream, ctx, clientId) {
597
+ try {
598
+ yield* stream;
599
+ }
600
+ catch (error) {
601
+ await recordRoundFailure(ctx, clientId, error);
553
602
  throw error;
554
603
  }
555
604
  }
@@ -623,9 +672,10 @@ async function createStreamCore(bytes, ctx, events, startedAtMs = 0) {
623
672
  for (const chunk of buffered)
624
673
  yield chunk;
625
674
  };
626
- if (events === undefined)
627
- return verified();
628
- return instrumentedStream(verified(), ctx, events, plan, report, bytes.length, startedAtMs);
675
+ if (events === undefined) {
676
+ return recordedStream(verified(), ctx, plan.header.clientId);
677
+ }
678
+ return recordedStream(instrumentedStream(verified(), ctx, events, plan, report, bytes.length, startedAtMs), ctx, plan.header.clientId);
629
679
  }
630
680
  /** Counts response bytes and emits `request.handled` when the stream
631
681
  * finishes — including a thrown host failure mid-stream (fail loud). */
@@ -29,6 +29,14 @@
29
29
  * The payload carries `commitSeq` purely for observability/ordering in logs;
30
30
  * the wake itself is seq-agnostic (a session pulls whatever it is behind).
31
31
  *
32
+ * ## Listener gaps
33
+ *
34
+ * Postgres drops notifications for a session that is not listening, so a
35
+ * LISTEN connection that dies and reconnects (server restart, failover, a
36
+ * serverless compute suspending) misses every commit in between. The
37
+ * connection reports each LISTEN that takes effect through `onListen`; every
38
+ * report after the first wakes all local sessions with `catchup-required`.
39
+ *
32
40
  * pglite cannot exercise cross-connection NOTIFY, so the integration
33
41
  * (`postgres-fanout.integration.test.ts`) is env-gated on `SYNCULAR_PG_URL`
34
42
  * and skips cleanly; the payload encode/parse is unit-tested hermetically.
@@ -51,18 +59,23 @@ export declare function parseFanoutPayload(text: string): FanoutPayload | undefi
51
59
  /** The hub surface the fanout wakes (a `RealtimeHub` satisfies this). */
52
60
  export interface FanoutWakeTarget {
53
61
  wake(partition: string, reason: WakeReason): void;
62
+ wakeAll(reason: WakeReason): void;
54
63
  }
55
64
  /**
56
65
  * A raw notification connection. Production wires a driver's LISTEN support:
66
+ * - Bun.sql and postgres.js: `sql.listen(channel, handler, onListen)`; both
67
+ * reconnect a dropped listener and call `onListen` again;
57
68
  * - node-postgres: a dedicated `Client` with `client.on('notification', …)`
58
- * after `LISTEN syncular_commit`;
59
- * - Bun.sql: `sql.listen(channel, handler)`.
69
+ * after `LISTEN syncular_commit`, reconnected by the host.
60
70
  * The `notify` side can reuse the main pool (`SELECT pg_notify($1,$2)`), but
61
- * LISTEN needs its own long-lived connection.
71
+ * LISTEN needs its own long-lived, unpooled connection.
62
72
  */
63
73
  export interface PgNotificationConnection {
64
- /** Register a payload handler for the channel and begin listening. */
65
- listen(channel: string, handler: (payload: string) => void): Promise<void> | void;
74
+ /**
75
+ * Register a payload handler for the channel and begin listening. Call
76
+ * `onListen` every time LISTEN takes effect, including after a reconnect.
77
+ */
78
+ listen(channel: string, handler: (payload: string) => void, onListen: () => void): Promise<void> | void;
66
79
  /** Send a notification on the channel. */
67
80
  notify(channel: string, payload: string): Promise<void>;
68
81
  close?(): Promise<void>;
@@ -54,11 +54,17 @@ export class PostgresFanout {
54
54
  if (this.#installed)
55
55
  throw new Error('fanout already installed');
56
56
  this.#installed = true;
57
+ let listening = false;
57
58
  await this.#conn.listen(FANOUT_CHANNEL, (payload) => {
58
59
  const parsed = parseFanoutPayload(payload);
59
60
  if (parsed === undefined)
60
61
  return; // ignore malformed frames
61
62
  hub.wake(parsed.partition, FANOUT_WAKE_REASON);
63
+ }, () => {
64
+ // A repeated LISTEN follows a gap whose notifications are lost.
65
+ if (listening)
66
+ hub.wakeAll(FANOUT_WAKE_REASON);
67
+ listening = true;
62
68
  });
63
69
  }
64
70
  /** Fan an applied commit out to the other instances. */
@@ -69,7 +69,7 @@ import type { AuthoritativeQueryRequest, AuthoritativeQueryResult, CheckpointDec
69
69
  * set, §5.9.5) as an index range, never a scan. `postgres-explain
70
70
  * .test.ts` asserts an `Index` node here too.
71
71
  */
72
- export declare const POSTGRES_DDL = "\nCREATE TABLE IF NOT EXISTS sync_partitions(\n partition TEXT PRIMARY KEY,\n max_commit_seq BIGINT NOT NULL DEFAULT 0,\n horizon_seq BIGINT NOT NULL DEFAULT 0\n);\nCREATE TABLE IF NOT EXISTS sync_partition_registry(\n partition TEXT PRIMARY KEY,\n log_epoch TEXT NOT NULL,\n epoch_required BOOLEAN NOT NULL DEFAULT FALSE,\n last_authenticated_at_ms BIGINT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS sync_row_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, row_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, row_id)\n);\nCREATE INDEX IF NOT EXISTS sync_row_scopes_by_row\n ON sync_row_scopes(partition, tbl, row_id);\nCREATE TABLE IF NOT EXISTS sync_commits(\n partition TEXT NOT NULL, commit_seq BIGINT NOT NULL,\n client_id TEXT NOT NULL, client_commit_id TEXT NOT NULL,\n actor_id TEXT NOT NULL, created_at_ms BIGINT NOT NULL,\n writer_version BIGINT,\n PRIMARY KEY(partition, commit_seq)\n);\nCREATE INDEX IF NOT EXISTS sync_commits_by_time\n ON sync_commits(partition, created_at_ms);\nCREATE TABLE IF NOT EXISTS sync_changes(\n partition TEXT NOT NULL, commit_seq BIGINT NOT NULL, idx INTEGER NOT NULL,\n tbl TEXT NOT NULL, row_id TEXT NOT NULL, op SMALLINT NOT NULL,\n row_version BIGINT, scopes JSONB NOT NULL, payload BYTEA,\n PRIMARY KEY(partition, commit_seq, idx)\n);\nCREATE INDEX IF NOT EXISTS sync_changes_by_table\n ON sync_changes(partition, commit_seq, tbl, idx);\nCREATE TABLE IF NOT EXISTS sync_change_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, commit_seq BIGINT NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, commit_seq)\n);\nCREATE TABLE IF NOT EXISTS sync_push_results(\n partition TEXT NOT NULL, client_id TEXT NOT NULL,\n client_commit_id TEXT NOT NULL, result JSONB NOT NULL,\n PRIMARY KEY(partition, client_id, client_commit_id)\n);\nCREATE TABLE IF NOT EXISTS sync_reactions(\n partition TEXT NOT NULL, idempotency_key TEXT NOT NULL,\n type TEXT NOT NULL, version INTEGER NOT NULL, payload JSONB NOT NULL,\n source_client_id TEXT NOT NULL, source_client_commit_id TEXT NOT NULL,\n source_commit_seq BIGINT NOT NULL, created_at_ms BIGINT NOT NULL,\n available_at_ms BIGINT NOT NULL, status TEXT NOT NULL,\n attempts INTEGER NOT NULL, max_attempts INTEGER NOT NULL,\n lease_owner TEXT, lease_expires_at_ms BIGINT, completed_at_ms BIGINT,\n last_failure JSONB,\n PRIMARY KEY(partition, idempotency_key),\n CHECK(status IN ('pending', 'leased', 'completed', 'dead-letter'))\n);\nCREATE INDEX IF NOT EXISTS sync_reactions_due\n ON sync_reactions(partition, status, available_at_ms, created_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_lease\n ON sync_reactions(partition, status, lease_expires_at_ms);\nCREATE INDEX IF NOT EXISTS sync_reactions_completed\n ON sync_reactions(partition, status, completed_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_dead_letter\n ON sync_reactions(partition, status, available_at_ms, idempotency_key);\nCREATE TABLE IF NOT EXISTS sync_clients(\n partition TEXT NOT NULL, client_id TEXT NOT NULL, actor_id TEXT NOT NULL,\n wire_version INTEGER NOT NULL DEFAULT 1,\n cursor BIGINT NOT NULL, subscriptions JSONB NOT NULL,\n updated_at_ms BIGINT NOT NULL,\n PRIMARY KEY(partition, client_id)\n);\nALTER TABLE sync_clients\n ADD COLUMN IF NOT EXISTS wire_version INTEGER NOT NULL DEFAULT 1;\nCREATE TABLE IF NOT EXISTS sync_blob_refs(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n blob_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, row_id, blob_id)\n);\nCREATE INDEX IF NOT EXISTS sync_blob_refs_by_blob\n ON sync_blob_refs(partition, blob_id);\nCREATE TABLE IF NOT EXISTS sync_tombstones(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n commit_seq BIGINT NOT NULL,\n PRIMARY KEY(partition, tbl, row_id)\n);\nCREATE TABLE IF NOT EXISTS sync_backfill_checkpoints(\n partition TEXT NOT NULL, name TEXT NOT NULL,\n schema_version INTEGER NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('declared','backfilling','activated')),\n watermark BIGINT NOT NULL DEFAULT 0,\n owner_epoch BIGINT NOT NULL DEFAULT 0,\n observed_rows BIGINT NOT NULL DEFAULT 0,\n updated_at_ms BIGINT NOT NULL,\n PRIMARY KEY(partition, name)\n);\nCREATE TABLE IF NOT EXISTS sync_writer_fence(\n partition TEXT PRIMARY KEY,\n required_writer_version INTEGER NOT NULL\n);\n";
72
+ export declare const POSTGRES_DDL = "\nCREATE TABLE IF NOT EXISTS sync_partitions(\n partition TEXT PRIMARY KEY,\n max_commit_seq BIGINT NOT NULL DEFAULT 0,\n horizon_seq BIGINT NOT NULL DEFAULT 0\n);\nCREATE TABLE IF NOT EXISTS sync_partition_registry(\n partition TEXT PRIMARY KEY,\n log_epoch TEXT NOT NULL,\n epoch_required BOOLEAN NOT NULL DEFAULT FALSE,\n last_authenticated_at_ms BIGINT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS sync_row_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, row_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, row_id)\n);\nCREATE INDEX IF NOT EXISTS sync_row_scopes_by_row\n ON sync_row_scopes(partition, tbl, row_id);\nCREATE TABLE IF NOT EXISTS sync_commits(\n partition TEXT NOT NULL, commit_seq BIGINT NOT NULL,\n client_id TEXT NOT NULL, client_commit_id TEXT NOT NULL,\n actor_id TEXT NOT NULL, created_at_ms BIGINT NOT NULL,\n writer_version BIGINT,\n PRIMARY KEY(partition, commit_seq)\n);\nCREATE INDEX IF NOT EXISTS sync_commits_by_time\n ON sync_commits(partition, created_at_ms);\nCREATE TABLE IF NOT EXISTS sync_changes(\n partition TEXT NOT NULL, commit_seq BIGINT NOT NULL, idx INTEGER NOT NULL,\n tbl TEXT NOT NULL, row_id TEXT NOT NULL, op SMALLINT NOT NULL,\n row_version BIGINT, scopes JSONB NOT NULL, payload BYTEA,\n PRIMARY KEY(partition, commit_seq, idx)\n);\nCREATE INDEX IF NOT EXISTS sync_changes_by_table\n ON sync_changes(partition, commit_seq, tbl, idx);\nCREATE TABLE IF NOT EXISTS sync_change_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, commit_seq BIGINT NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, commit_seq)\n);\nCREATE TABLE IF NOT EXISTS sync_push_results(\n partition TEXT NOT NULL, client_id TEXT NOT NULL,\n client_commit_id TEXT NOT NULL, result JSONB NOT NULL,\n PRIMARY KEY(partition, client_id, client_commit_id)\n);\nCREATE TABLE IF NOT EXISTS sync_reactions(\n partition TEXT NOT NULL, idempotency_key TEXT NOT NULL,\n type TEXT NOT NULL, version INTEGER NOT NULL, payload JSONB NOT NULL,\n source_client_id TEXT NOT NULL, source_client_commit_id TEXT NOT NULL,\n source_commit_seq BIGINT NOT NULL, created_at_ms BIGINT NOT NULL,\n available_at_ms BIGINT NOT NULL, status TEXT NOT NULL,\n attempts INTEGER NOT NULL, max_attempts INTEGER NOT NULL,\n lease_owner TEXT, lease_expires_at_ms BIGINT, completed_at_ms BIGINT,\n last_failure JSONB,\n PRIMARY KEY(partition, idempotency_key),\n CHECK(status IN ('pending', 'leased', 'completed', 'dead-letter'))\n);\nCREATE INDEX IF NOT EXISTS sync_reactions_due\n ON sync_reactions(partition, status, available_at_ms, created_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_lease\n ON sync_reactions(partition, status, lease_expires_at_ms);\nCREATE INDEX IF NOT EXISTS sync_reactions_completed\n ON sync_reactions(partition, status, completed_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_dead_letter\n ON sync_reactions(partition, status, available_at_ms, idempotency_key);\nCREATE TABLE IF NOT EXISTS sync_clients(\n partition TEXT NOT NULL, client_id TEXT NOT NULL, actor_id TEXT NOT NULL,\n wire_version INTEGER NOT NULL DEFAULT 1,\n cursor BIGINT NOT NULL, subscriptions JSONB NOT NULL,\n updated_at_ms BIGINT NOT NULL,\n last_round_at_ms BIGINT, last_error_code TEXT,\n consecutive_failures INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY(partition, client_id)\n);\nALTER TABLE sync_clients\n ADD COLUMN IF NOT EXISTS wire_version INTEGER NOT NULL DEFAULT 1;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS last_round_at_ms BIGINT;\nALTER TABLE sync_clients ADD COLUMN IF NOT EXISTS last_error_code TEXT;\nALTER TABLE sync_clients\n ADD COLUMN IF NOT EXISTS consecutive_failures INTEGER NOT NULL DEFAULT 0;\nCREATE TABLE IF NOT EXISTS sync_blob_refs(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n blob_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, row_id, blob_id)\n);\nCREATE INDEX IF NOT EXISTS sync_blob_refs_by_blob\n ON sync_blob_refs(partition, blob_id);\nCREATE TABLE IF NOT EXISTS sync_tombstones(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n commit_seq BIGINT NOT NULL,\n PRIMARY KEY(partition, tbl, row_id)\n);\nCREATE TABLE IF NOT EXISTS sync_backfill_checkpoints(\n partition TEXT NOT NULL, name TEXT NOT NULL,\n schema_version INTEGER NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('declared','backfilling','activated')),\n watermark BIGINT NOT NULL DEFAULT 0,\n owner_epoch BIGINT NOT NULL DEFAULT 0,\n observed_rows BIGINT NOT NULL DEFAULT 0,\n updated_at_ms BIGINT NOT NULL,\n PRIMARY KEY(partition, name)\n);\nCREATE TABLE IF NOT EXISTS sync_writer_fence(\n partition TEXT PRIMARY KEY,\n required_writer_version INTEGER NOT NULL\n);\n";
73
73
  export declare class PostgresServerStorage implements ServerStorage {
74
74
  #private;
75
75
  constructor(exec: PgExecutor);
@@ -130,6 +130,7 @@ export declare class PostgresServerStorage implements ServerStorage {
130
130
  scanRowsByIndex(partition: string, query: IndexRowScanQuery): Promise<StoredRow[]>;
131
131
  getClientRecord(partition: string, clientId: string): Promise<ClientRecord | undefined>;
132
132
  putClientRecord(partition: string, record: ClientRecord): Promise<void>;
133
+ recordClientRoundFailure(partition: string, clientId: string, actorId: string, errorCode: string, atMs: number): Promise<void>;
133
134
  advanceClientCursor(partition: string, clientId: string, actorId: string, logEpoch: string, cursor: number, updatedAtMs: number): Promise<void>;
134
135
  updateClientCursor(partition: string, clientId: string, cursor: number, updatedAtMs: number): Promise<void>;
135
136
  getActiveClientCursorFloor(partition: string, cutoffMs: number): Promise<number | null>;