@rebasepro/server-postgres 0.9.1-canary.ff338b5 → 0.10.1-canary.0a881d4

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.
Files changed (72) hide show
  1. package/README.md +21 -0
  2. package/dist/PostgresBackendDriver.d.ts +18 -0
  3. package/dist/PostgresBootstrapper.d.ts +11 -1
  4. package/dist/auth/services.d.ts +93 -54
  5. package/dist/backup/backup-logic.d.ts +23 -0
  6. package/dist/backup/backup-service.d.ts +44 -2
  7. package/dist/backup/pg-tools.d.ts +41 -1
  8. package/dist/chunk-DSJWtz9O.js +40 -0
  9. package/dist/cli-helpers.d.ts +33 -1
  10. package/dist/ensure-collection-tables-C9gy4STB.js +304 -0
  11. package/dist/ensure-collection-tables-C9gy4STB.js.map +1 -0
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.es.js +2098 -4749
  14. package/dist/index.es.js.map +1 -1
  15. package/dist/schema/auth-bootstrap-sql.d.ts +1 -1
  16. package/dist/schema/auth-schema.d.ts +194 -24
  17. package/dist/schema/destructive-sql.d.ts +49 -0
  18. package/dist/schema/ensure-collection-tables.d.ts +79 -0
  19. package/dist/schema/generate-postgres-ddl-logic.d.ts +4 -1
  20. package/dist/schema/introspect-db-logic.d.ts +0 -5
  21. package/dist/schema/introspect-db-naming.d.ts +10 -0
  22. package/dist/security/policy-drift.d.ts +24 -0
  23. package/dist/security/rls-enforcement.d.ts +2 -2
  24. package/dist/services/cdc/CdcListener.d.ts +7 -14
  25. package/dist/services/channel-bus/ChannelBus.d.ts +29 -0
  26. package/dist/services/channel-bus/PostgresChannelBus.d.ts +111 -0
  27. package/dist/services/channel-bus/index.d.ts +55 -0
  28. package/dist/services/channel-history.d.ts +129 -0
  29. package/dist/services/channel-presence.d.ts +66 -0
  30. package/dist/services/pg-notify-listener.d.ts +47 -0
  31. package/dist/services/realtimeService.d.ts +183 -8
  32. package/dist/src-CBgtrPhJ.js +336 -0
  33. package/dist/src-CBgtrPhJ.js.map +1 -0
  34. package/dist/src-DG6ZsQQ3.js +4026 -0
  35. package/dist/src-DG6ZsQQ3.js.map +1 -0
  36. package/package.json +9 -34
  37. package/src/PostgresBackendDriver.ts +56 -5
  38. package/src/PostgresBootstrapper.ts +87 -1
  39. package/src/auth/ensure-tables.ts +187 -19
  40. package/src/auth/services.ts +309 -170
  41. package/src/backup/backup-cli.ts +60 -1
  42. package/src/backup/backup-cron.ts +24 -1
  43. package/src/backup/backup-logic.ts +62 -0
  44. package/src/backup/backup-service.ts +132 -13
  45. package/src/backup/pg-tools.ts +70 -2
  46. package/src/cli-helpers.ts +82 -27
  47. package/src/cli.ts +152 -6
  48. package/src/index.ts +4 -0
  49. package/src/schema/auth-bootstrap-sql.ts +7 -1
  50. package/src/schema/auth-schema.ts +53 -15
  51. package/src/schema/destructive-sql.ts +94 -0
  52. package/src/schema/doctor.ts +6 -6
  53. package/src/schema/ensure-collection-tables.test.ts +156 -0
  54. package/src/schema/ensure-collection-tables.ts +297 -0
  55. package/src/schema/generate-drizzle-schema-logic.ts +13 -9
  56. package/src/schema/generate-postgres-ddl-logic.ts +22 -15
  57. package/src/schema/introspect-db-inference.ts +14 -14
  58. package/src/schema/introspect-db-logic.ts +7 -16
  59. package/src/schema/introspect-db-naming.ts +15 -0
  60. package/src/schema/introspect-runtime.ts +1 -1
  61. package/src/security/policy-drift.test.ts +46 -0
  62. package/src/security/policy-drift.ts +70 -4
  63. package/src/security/rls-enforcement.ts +11 -5
  64. package/src/services/cdc/CdcListener.ts +27 -91
  65. package/src/services/channel-bus/ChannelBus.ts +44 -0
  66. package/src/services/channel-bus/PostgresChannelBus.ts +299 -0
  67. package/src/services/channel-bus/index.ts +123 -0
  68. package/src/services/channel-history.ts +378 -0
  69. package/src/services/channel-presence.ts +148 -0
  70. package/src/services/pg-notify-listener.ts +137 -0
  71. package/src/services/realtimeService.ts +581 -24
  72. package/src/websocket.ts +30 -11
@@ -1,4 +1,4 @@
1
- import { humanize } from "./introspect-db-logic";
1
+ import { humanize } from "./introspect-db-naming";
2
2
 
3
3
  export interface InferenceResult {
4
4
  propType?: string; // If the inference changes the base type
@@ -51,10 +51,11 @@ export function inferPropertyFromData(
51
51
  }
52
52
  }
53
53
 
54
- // Currency
55
- if (colNameLower.includes("price") || colNameLower.includes("cost") || colNameLower.includes("amount") || colNameLower.includes("fee") || pgDataType === "money") {
56
- extraLines.push(" ui: {\n currency: true\n }");
57
- }
54
+ // No currency heuristic. `admin.currency` was never a declared option and
55
+ // nothing reads it, so a column called `price` got a block of config that did
56
+ // nothing — invisible because this generator emits *source text*, which no
57
+ // typechecker ever saw. Reinstate it by adding `currency` to
58
+ // AdminNumberOptions first, and something that renders it.
58
59
  }
59
60
 
60
61
  // ── JSON / JSONB Analysis ────────────────────────────────────────────
@@ -169,11 +170,10 @@ export function inferPropertyFromData(
169
170
  if (isPk) extraLines.push(" isId: \"cuid\"");
170
171
  }
171
172
 
172
- // Color Codes
173
- const allColors = validValues.every(v => typeof v === "string" && COLOR_HEX_REGEX.test(v));
174
- if (allColors) {
175
- extraLines.push(" ui: {\n color: true\n }");
176
- }
173
+ // No colour heuristic. `admin.color` was never a declared option and nothing
174
+ // reads it — the same dead branch `currency` was. This generator emits *source
175
+ // text*, so no typechecker ever saw either. Reinstate by adding the option and
176
+ // something that renders it first.
177
177
 
178
178
  // Text Lengths, Multiline & Markdown
179
179
  let maxLength = 0;
@@ -212,9 +212,9 @@ export function inferPropertyFromData(
212
212
  if (allAbsoluteUrls) {
213
213
  const isImage = validValues.some(v => typeof v === "string" && v.match(/\.(jpeg|jpg|gif|png|webp|svg)/i));
214
214
  if (isImage || isMedia) {
215
- extraLines.push(" ui: {\n url: \"image\"\n }");
215
+ extraLines.push(" url: true,\n admin: {\n urlPreview: \"image\"\n }");
216
216
  } else {
217
- extraLines.push(" ui: {\n url: true\n }");
217
+ extraLines.push(" url: true");
218
218
  }
219
219
  } else {
220
220
  const hasFileExtension = validValues.some(v => typeof v === "string" && v.match(/\.[a-zA-Z0-9]+$/));
@@ -225,9 +225,9 @@ export function inferPropertyFromData(
225
225
  extraLines.push(` storage: {\n storagePath: "${inferredStoragePath}"\n }`);
226
226
  } else if (isUrl) {
227
227
  if (isMedia) {
228
- extraLines.push(" ui: {\n url: \"image\"\n }");
228
+ extraLines.push(" url: true,\n admin: {\n urlPreview: \"image\"\n }");
229
229
  } else {
230
- extraLines.push(" ui: {\n url: true\n }");
230
+ extraLines.push(" url: true");
231
231
  }
232
232
  }
233
233
  }
@@ -7,6 +7,7 @@
7
7
  * and consumed directly by tests.
8
8
  */
9
9
  import { inferPropertyFromData } from "./introspect-db-inference";
10
+ import { humanize } from "./introspect-db-naming";
10
11
 
11
12
  // ── Typed interfaces for SQL query results ────────────────────────────
12
13
 
@@ -117,16 +118,6 @@ export function singularize(word: string): string {
117
118
  return word;
118
119
  }
119
120
 
120
- /**
121
- * Convert a snake_case name to a human-readable Title Case label.
122
- * e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
123
- */
124
- export function humanize(snakeName: string): string {
125
- return snakeName
126
- .replace(/_/g, " ")
127
- .replace(/\b\w/g, (c) => c.toUpperCase());
128
- }
129
-
130
121
  /**
131
122
  * Convert a snake_case table name to a camelCase + "Collection" variable name.
132
123
  * e.g. "company_token" -> "companyTokenCollection"
@@ -578,11 +569,11 @@ export function generateCollectionFile(
578
569
  // Date auto-value heuristics
579
570
  if (finalPropType === "date") {
580
571
  if (colNameLower === "created_at" || colNameLower === "createdat") {
581
- extra += "\n autoValue: \"on_create\",\n ui: {\n readOnly: true,\n hideFromCollection: true\n },";
572
+ extra += "\n autoValue: \"on_create\",\n admin: {\n readOnly: true,\n hideFromCollection: true\n },";
582
573
  } else if (colNameLower === "updated_at" || colNameLower === "updatedat") {
583
- extra += "\n autoValue: \"on_update\",\n ui: {\n readOnly: true,\n hideFromCollection: true\n },";
574
+ extra += "\n autoValue: \"on_update\",\n admin: {\n readOnly: true,\n hideFromCollection: true\n },";
584
575
  } else if (col.column_default && (col.column_default.includes("now()") || col.column_default.includes("CURRENT_TIMESTAMP"))) {
585
- extra += "\n autoValue: \"on_create\",\n ui: {\n readOnly: true\n },";
576
+ extra += "\n autoValue: \"on_create\",\n admin: {\n readOnly: true\n },";
586
577
  }
587
578
  }
588
579
 
@@ -613,13 +604,13 @@ export function generateCollectionFile(
613
604
  if (isMedia) {
614
605
  extra += `\n storage: {\n storagePath: "${tableName}/${col.column_name}"\n },`;
615
606
  } else if (isUrl) {
616
- extra += "\n ui: {\n url: true\n },";
607
+ extra += "\n url: true,";
617
608
  } else if (colNameLower === "description" || colNameLower === "summary" || colNameLower === "excerpt") {
618
- extra += "\n multiline: true,";
609
+ extra += "\n admin: {\n multiline: true\n },";
619
610
  } else if (colNameLower === "content" || colNameLower === "body") {
620
611
  extra += "\n multiline: true,\n markdown: true,";
621
612
  } else if (col.data_type === "text") {
622
- extra += "\n multiline: true,";
613
+ extra += "\n admin: {\n multiline: true\n },";
623
614
  }
624
615
  }
625
616
 
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Naming helpers shared by the introspection modules. These live apart from
3
+ * `introspect-db-logic.ts` because the inference pass needs them too, and
4
+ * importing them from there would close a cycle back through this module.
5
+ */
6
+
7
+ /**
8
+ * Convert a snake_case name to a human-readable Title Case label.
9
+ * e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
10
+ */
11
+ export function humanize(snakeName: string): string {
12
+ return snakeName
13
+ .replace(/_/g, " ")
14
+ .replace(/\b\w/g, (c) => c.toUpperCase());
15
+ }
@@ -23,11 +23,11 @@ import {
23
23
  buildTablesMap,
24
24
  buildEnumMap,
25
25
  identifyJoinTables,
26
- humanize,
27
26
  singularize,
28
27
  mapPgType,
29
28
  getIconForTable
30
29
  } from "./introspect-db-logic";
30
+ import { humanize } from "./introspect-db-naming";
31
31
 
32
32
  export interface IntrospectedSchema {
33
33
  tablesMap: Map<string, TableMeta>;
@@ -123,6 +123,52 @@ describe("checkPolicyDrift", () => {
123
123
  expect(hasDrift(drift)).toBe(false);
124
124
  });
125
125
 
126
+ it("flags the pre-fix permissive tautology that every other check misses", async () => {
127
+ // A database pushed before the `policy.authenticated()` fix carries
128
+ // `auth.uid() IS NOT NULL` — true for anonymous visitors. Its name,
129
+ // roles, command and clause presence all match the corrected policy, so
130
+ // this is the only signal that catches it.
131
+ const cols = [collection("posts")];
132
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
133
+ const live = expected.map((p) => liveRow(p, {
134
+ qual: p.hasUsing ? "(auth.uid() IS NOT NULL)" : null
135
+ }));
136
+
137
+ const drift = await checkPolicyDrift(dbWith(live), cols);
138
+
139
+ expect(drift.insecure.length).toBeGreaterThan(0);
140
+ expect(hasDrift(drift)).toBe(true);
141
+ expect(drift.diverged).toHaveLength(0); // nothing else notices
142
+ expect(formatPolicyDrift(drift)).toContain("anonymous");
143
+ expect(formatPolicyDrift(drift)).toContain("db push");
144
+ });
145
+
146
+ it("clears the corrected expression, in either literal spelling", async () => {
147
+ const cols = [collection("posts")];
148
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
149
+ for (const guard of ["<> 'anonymous'::text", "<> 'anonymous'", "!= 'anonymous'"]) {
150
+ const live = expected.map((p) => liveRow(p, {
151
+ qual: p.hasUsing ? `((auth.uid() IS NOT NULL) AND ((auth.uid())::text ${guard}))` : null
152
+ }));
153
+ const drift = await checkPolicyDrift(dbWith(live), cols);
154
+ expect(drift.insecure).toHaveLength(0);
155
+ }
156
+ });
157
+
158
+ it("also flags the tautology in a WITH CHECK clause", async () => {
159
+ const cols = [collection("posts")];
160
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
161
+ const live = expected.map((p) => liveRow(p, {
162
+ with_check: p.hasWithCheck ? "(auth.uid() IS NOT NULL)" : null
163
+ }));
164
+
165
+ const drift = await checkPolicyDrift(dbWith(live), cols);
166
+
167
+ const flagged = drift.insecure.some((i) => /WITH CHECK/.test(i.reason));
168
+ // Only assert when the fixture actually had a WITH CHECK policy to carry it.
169
+ if (expected.some((p) => p.hasWithCheck)) expect(flagged).toBe(true);
170
+ });
171
+
126
172
  it("parses roles when the driver returns the raw {a,b} text form", async () => {
127
173
  const cols = [collection("tags")];
128
174
  const live = [{ schemaname: "public", tablename: "tags", policyname: "test_policy", roles: "{authenticated,anon}", cmd: "ALL", qual: "true", with_check: null }];
@@ -29,6 +29,14 @@ export interface PolicyRef {
29
29
  hasUsing: boolean;
30
30
  /** Whether a WITH CHECK clause is present at all (not what it says). */
31
31
  hasWithCheck: boolean;
32
+ /**
33
+ * The live clause text, when read from `pg_policies`. Present only for live
34
+ * policies (the expected side is parsed from DDL and does not carry it).
35
+ * Used solely for the insecure-tautology scan, not for divergence — Postgres
36
+ * rewrites this text, so it is not safe to diff against expected.
37
+ */
38
+ qual?: string | null;
39
+ withCheck?: string | null;
32
40
  }
33
41
 
34
42
  export interface PolicyDrift {
@@ -38,6 +46,19 @@ export interface PolicyDrift {
38
46
  orphaned: PolicyRef[];
39
47
  /** Same policy name, different roles or command. */
40
48
  diverged: { expected: PolicyRef; actual: PolicyRef; differences: string[] }[];
49
+ /**
50
+ * A live policy whose expression is the known-permissive tautology
51
+ * `auth.uid() IS NOT NULL` — true for anonymous visitors too, because the
52
+ * user path coerces a blank id to the `'anonymous'` sentinel. This is what
53
+ * `policy.authenticated()` used to compile to, so a database pushed before
54
+ * that fix carries it, and neither the name, roles, command nor clause
55
+ * *presence* differs from the corrected policy — the only thing that changed
56
+ * is the expression text, which this checker otherwise (correctly) ignores.
57
+ * So it is the one drift that hides from every other check here.
58
+ *
59
+ * @see reason a sentence naming the clause and what to do.
60
+ */
61
+ insecure: { policy: PolicyRef; reason: string }[];
41
62
  }
42
63
 
43
64
  export interface Queryable {
@@ -122,10 +143,30 @@ async function readLivePolicies(client: Queryable, schemas: string[]): Promise<P
122
143
  // Presence only. Postgres rewrites the text, but it does not invent or
123
144
  // drop a clause: NULL here means the policy genuinely has none.
124
145
  hasUsing: r.qual != null,
125
- hasWithCheck: r.with_check != null
146
+ hasWithCheck: r.with_check != null,
147
+ qual: r.qual,
148
+ withCheck: r.with_check
126
149
  }));
127
150
  }
128
151
 
152
+ /**
153
+ * The permissive tautology `auth.uid() IS NOT NULL`, without the
154
+ * `<> 'anonymous'` guard that makes it mean "signed in".
155
+ *
156
+ * Whitespace varies with Postgres's rewrite, so match on a collapsed form. The
157
+ * guard clause (`<> 'anonymous'`, in any spelling) is what distinguishes the
158
+ * corrected policy from the stale one, so its presence clears the text.
159
+ */
160
+ function isPermissiveAuthTautology(clause: string | null | undefined): boolean {
161
+ if (!clause) return false;
162
+ const flat = clause.toLowerCase().replace(/\s+/g, " ");
163
+ if (!/auth\.uid\(\)\s*is not null/.test(flat)) return false;
164
+ // The fix appends `AND auth.uid() <> 'anonymous'`; Postgres may store the
165
+ // literal as `'anonymous'::text`. Either spelling means it is the corrected
166
+ // policy, not the tautology.
167
+ return !/<>\s*'anonymous'/.test(flat) && !/!=\s*'anonymous'/.test(flat);
168
+ }
169
+
129
170
  const keyOf = (p: PolicyRef) => `${p.schema}.${p.table}.${p.name}`;
130
171
  const sameRoles = (a: string[], b: string[]) =>
131
172
  a.length === b.length && [...a].sort().join(",") === [...b].sort().join(",");
@@ -154,13 +195,31 @@ export async function checkPolicyDrift(
154
195
  const schemas = [...new Set(expected.map((p) => p.schema))];
155
196
  // Nothing expected means nothing to reconcile against; scanning every
156
197
  // schema would report the whole database as orphaned.
157
- if (schemas.length === 0) return { missing: [], orphaned: [], diverged: [] };
198
+ if (schemas.length === 0) return { missing: [], orphaned: [], diverged: [], insecure: [] };
158
199
 
159
200
  const live = await readLivePolicies(client, schemas);
160
201
  const liveByKey = new Map(live.map((p) => [keyOf(p), p]));
161
202
  const expectedByKey = new Map(expected.map((p) => [keyOf(p), p]));
162
203
 
163
- const drift: PolicyDrift = { missing: [], orphaned: [], diverged: [] };
204
+ const drift: PolicyDrift = { missing: [], orphaned: [], diverged: [], insecure: [] };
205
+
206
+ // Scan every live policy for the permissive tautology. This is deliberately
207
+ // independent of the name-keyed diff below: a database pushed before the
208
+ // `authenticated()` fix matches its expected policy on name, roles, command
209
+ // and clause presence, so nothing else here would flag it.
210
+ for (const p of live) {
211
+ const clause = isPermissiveAuthTautology(p.qual)
212
+ ? "USING"
213
+ : isPermissiveAuthTautology(p.withCheck) ? "WITH CHECK" : null;
214
+ if (clause) {
215
+ drift.insecure.push({
216
+ policy: p,
217
+ reason: `${clause} is \`auth.uid() IS NOT NULL\`, which is true for anonymous ` +
218
+ `visitors too — this grants access to signed-out requests. It predates the ` +
219
+ `\`policy.authenticated()\` fix; re-run \`rebase db push\` to tighten it.`
220
+ });
221
+ }
222
+ }
164
223
 
165
224
  for (const [key, want] of expectedByKey) {
166
225
  const got = liveByKey.get(key);
@@ -249,7 +308,7 @@ export async function dropOrphanedPolicies(
249
308
  }
250
309
 
251
310
  export const hasDrift = (d: PolicyDrift): boolean =>
252
- d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0;
311
+ d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0 || d.insecure.length > 0;
253
312
 
254
313
  /** Human-readable report; empty string when the database matches the config. */
255
314
  export function formatPolicyDrift(drift: PolicyDrift): string {
@@ -273,5 +332,12 @@ export function formatPolicyDrift(drift: PolicyDrift): string {
273
332
  for (const diff of d.differences) lines.push(` ${diff}`);
274
333
  }
275
334
  }
335
+ if (drift.insecure.length > 0) {
336
+ lines.push(" Insecure — a live policy grants access it should not:");
337
+ for (const i of drift.insecure) {
338
+ lines.push(` • ${i.policy.schema}.${i.policy.table} → "${i.policy.name}"`);
339
+ lines.push(` ${i.reason}`);
340
+ }
341
+ }
276
342
  return lines.join("\n");
277
343
  }
@@ -59,7 +59,7 @@ export interface ConnectionPosture {
59
59
  }
60
60
 
61
61
  export interface AuthContext {
62
- userId: string;
62
+ uid: string;
63
63
  /** Raw roles as carried on the user (strings or `{ id }` objects). */
64
64
  roles: unknown[];
65
65
  }
@@ -200,7 +200,7 @@ export async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promi
200
200
  * SECURITY: this function is only ever called on the **user** path (the server
201
201
  * context uses the base/owner driver and never calls it). The default policies
202
202
  * treat `auth.uid() IS NULL` as the trusted server context, and `auth.uid()`
203
- * is `NULLIF(current_setting('app.user_id'), '')` — so an EMPTY user id would
203
+ * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would
204
204
  * be read as NULL and silently escalate a user request to server privileges.
205
205
  * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
206
206
  * rather than trusting every caller (e.g. realtime subscription auth) to do it.
@@ -208,15 +208,21 @@ export async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promi
208
208
  * semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
209
209
  */
210
210
  export async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {
211
- const userId = typeof auth.userId === "string" && auth.userId.trim() !== "" ? auth.userId : ANONYMOUS_USER_ID;
211
+ const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
212
212
  const normalizedRoles = auth.roles.map((r: unknown) =>
213
213
  typeof r === "string" ? r : (r as Record<string, unknown>)?.id ?? String(r)
214
214
  );
215
+ // `app.user_id` is the pre-rename spelling, still written because policies
216
+ // are data: a database provisioned before the rename holds rules compiled
217
+ // to `current_setting('app.user_id')`, and those predicates would evaluate
218
+ // to NULL — failing open or locking out — if we stopped setting it. Drop
219
+ // the alias only once no live database carries a legacy policy.
215
220
  await tx.execute(drizzleSql`
216
221
  SELECT
217
- set_config('app.user_id', ${userId}, true),
222
+ set_config('app.uid', ${uid}, true),
223
+ set_config('app.user_id', ${uid}, true),
218
224
  set_config('app.user_roles', ${normalizedRoles.join(",")}, true),
219
- set_config('app.jwt', ${JSON.stringify({ sub: userId, roles: auth.roles })}, true)
225
+ set_config('app.jwt', ${JSON.stringify({ sub: uid, roles: auth.roles })}, true)
220
226
  `);
221
227
  if (userRole) {
222
228
  await tx.execute(drizzleSql.raw(`SET LOCAL ROLE ${quoteIdent(userRole)}`));
@@ -1,6 +1,6 @@
1
- import { Client as PgClient } from "pg";
2
1
  import { logger } from "@rebasepro/server";
3
2
  import { CDC_CHANNEL } from "./trigger-cdc";
3
+ import { PgNotifyListener } from "../pg-notify-listener";
4
4
 
5
5
  /**
6
6
  * A single database change captured by the CDC triggers and delivered over the
@@ -54,22 +54,30 @@ export function parseCdcPayload(payload: string): CdcChangeEvent | null {
54
54
  /**
55
55
  * Dedicated Postgres LISTEN client for database-level CDC.
56
56
  *
57
- * Mirrors the resilience of the RealtimeService cross-instance LISTEN client: a
58
- * standalone `pg.Client` (outside the Drizzle pool) that stays connected, and
59
- * transparently reconnects on error/disconnect. Each backend instance runs one,
60
- * so every instance observes every committed change regardless of which
61
- * instance (or external process) made the write.
57
+ * A {@link PgNotifyListener} — a connection outside the Drizzle pool that stays
58
+ * open and repairs itself — plus the parsing that turns a `rebase_cdc` payload
59
+ * into a change event. Each backend instance runs one, so every instance
60
+ * observes every committed change regardless of which instance (or external
61
+ * process) made the write.
62
62
  */
63
63
  export class CdcListener {
64
- private client?: PgClient;
65
- private running = false;
66
- private reconnectTimer?: ReturnType<typeof setTimeout>;
67
- private static readonly RECONNECT_DELAY_MS = 3000;
68
-
69
- constructor(
70
- private readonly connectionString: string,
71
- private readonly onEvent: (event: CdcChangeEvent) => void | Promise<void>
72
- ) {}
64
+ private readonly listener: PgNotifyListener;
65
+
66
+ constructor(connectionString: string, onEvent: (event: CdcChangeEvent) => void | Promise<void>) {
67
+ this.listener = new PgNotifyListener({
68
+ connectionString,
69
+ channel: CDC_CHANNEL,
70
+ logLabel: "[CDC]",
71
+ onPayload: (payload) => {
72
+ const event = parseCdcPayload(payload);
73
+ if (!event) {
74
+ logger.warn("⚠️ [CDC] Dropping unparseable change notification.");
75
+ return;
76
+ }
77
+ return onEvent(event);
78
+ }
79
+ });
80
+ }
73
81
 
74
82
  /**
75
83
  * Connect and begin listening. Idempotent.
@@ -78,90 +86,18 @@ export class CdcListener {
78
86
  * established (or `LISTEN` is refused), this rejects so callers — notably
79
87
  * `REALTIME_CDC=auto` — can detect an unusable connection and fall back to
80
88
  * app-level realtime. Once the initial connection succeeds, later drops
81
- * self-heal via {@link scheduleReconnect}.
89
+ * self-heal in the background.
82
90
  */
83
91
  async start(): Promise<void> {
84
- if (this.running) {
92
+ if (this.listener.active) {
85
93
  logger.warn("⚠️ [CDC] CdcListener.start() called but already running. Ignoring.");
86
94
  return;
87
95
  }
88
- this.running = true;
89
- try {
90
- await this.connect({ initial: true });
91
- } catch (err) {
92
- this.running = false;
93
- throw err;
94
- }
96
+ await this.listener.start();
95
97
  }
96
98
 
97
99
  /** Stop listening and release the connection. */
98
100
  async stop(): Promise<void> {
99
- this.running = false;
100
- if (this.reconnectTimer) {
101
- clearTimeout(this.reconnectTimer);
102
- this.reconnectTimer = undefined;
103
- }
104
- if (this.client) {
105
- try {
106
- await this.client.end();
107
- } catch { /* ignore close errors */ }
108
- this.client = undefined;
109
- }
110
- }
111
-
112
- private async connect({ initial = false }: { initial?: boolean } = {}): Promise<void> {
113
- try {
114
- const client = new PgClient({ connectionString: this.connectionString });
115
-
116
- client.on("error", (err) => {
117
- logger.error("❌ [CDC] LISTEN client error", { detail: err.message });
118
- this.scheduleReconnect();
119
- });
120
-
121
- client.on("end", () => {
122
- if (this.running) {
123
- logger.warn("⚠️ [CDC] LISTEN client disconnected unexpectedly.");
124
- this.scheduleReconnect();
125
- }
126
- });
127
-
128
- client.on("notification", (msg) => {
129
- if (!msg.payload) return;
130
- const event = parseCdcPayload(msg.payload);
131
- if (!event) {
132
- logger.warn("⚠️ [CDC] Dropping unparseable change notification.");
133
- return;
134
- }
135
- // Never let a handler rejection escape into the pg client.
136
- Promise.resolve(this.onEvent(event)).catch((err) =>
137
- logger.error("❌ [CDC] Error handling change event", { error: err })
138
- );
139
- });
140
-
141
- await client.connect();
142
- await client.query(`LISTEN ${CDC_CHANNEL}`);
143
- this.client = client;
144
- logger.info(`📡 [CDC] Listening for database changes on channel "${CDC_CHANNEL}".`);
145
- } catch (err) {
146
- // Surface the initial failure so callers can choose to fall back;
147
- // for reconnects, keep retrying quietly in the background.
148
- if (initial) throw err;
149
- logger.error("❌ [CDC] Failed to connect LISTEN client", { error: err });
150
- this.scheduleReconnect();
151
- }
152
- }
153
-
154
- private scheduleReconnect(): void {
155
- if (!this.running || this.reconnectTimer) return;
156
-
157
- this.reconnectTimer = setTimeout(async () => {
158
- this.reconnectTimer = undefined;
159
- if (!this.running) return;
160
- if (this.client) {
161
- try { await this.client.end(); } catch { /* ignore */ }
162
- this.client = undefined;
163
- }
164
- await this.connect();
165
- }, CdcListener.RECONNECT_DELAY_MS);
101
+ await this.listener.stop();
166
102
  }
167
103
  }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Runtime pieces of the channel bus that are not the contract itself.
3
+ *
4
+ * The interface, the frame shape and the implementer's contract live in
5
+ * `@rebasepro/types` (`types/channel_bus.ts`), so a transport shipped as its own
6
+ * package — a Redis one, say — depends on the contract and not on this database
7
+ * adapter. They are re-exported here for convenience: code already importing
8
+ * from the adapter should not have to know where the types are declared.
9
+ */
10
+
11
+ import type { ChannelBusFrame } from "@rebasepro/types";
12
+
13
+ export type {
14
+ ChannelBus,
15
+ ChannelBusFrame,
16
+ ChannelBusHandler,
17
+ ChannelBusConfig,
18
+ ChannelBusSetting
19
+ } from "@rebasepro/types";
20
+ export { isChannelBusInstance } from "@rebasepro/types";
21
+
22
+ /**
23
+ * The default: no cross-instance delivery at all.
24
+ *
25
+ * This is what every deployment ran before the bus existed, and what a
26
+ * single-instance deployment should keep running — `publish` resolves without
27
+ * touching the network, so the broadcast path is the same handful of `ws.send`
28
+ * calls it always was.
29
+ */
30
+ export class MemoryChannelBus {
31
+ readonly kind = "memory" as const;
32
+ readonly maxFrameBytes = Infinity;
33
+
34
+ async start(): Promise<void> { /* nothing to connect */ }
35
+
36
+ async publish(): Promise<void> { /* nowhere to publish to */ }
37
+
38
+ async stop(): Promise<void> { /* nothing to release */ }
39
+ }
40
+
41
+ /** Encoded size of a frame, for a transport's size check. */
42
+ export function frameByteLength(frame: ChannelBusFrame): number {
43
+ return Buffer.byteLength(JSON.stringify(frame), "utf8");
44
+ }