@rebasepro/server-postgres 0.31.0-canary.g902a0ce → 0.32.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.
Files changed (69) hide show
  1. package/dist/{BranchService-USp1AvZB.js → BranchService-C8LtpMho.js} +3 -3
  2. package/dist/{BranchService-USp1AvZB.js.map → BranchService-C8LtpMho.js.map} +1 -1
  3. package/dist/{backup-cli-DbKyEj6c.js → backup-cli-DtV6n3oB.js} +3 -3
  4. package/dist/{backup-cli-DbKyEj6c.js.map → backup-cli-DtV6n3oB.js.map} +1 -1
  5. package/dist/{boot-ddl-5H2bL_80.js → boot-ddl-CSYhSSZD.js} +2 -2
  6. package/dist/{boot-ddl-5H2bL_80.js.map → boot-ddl-CSYhSSZD.js.map} +1 -1
  7. package/dist/{cli-console-DsRgGSBR.js → cli-console-Cu1DzqvR.js} +4 -4
  8. package/dist/{cli-console-DsRgGSBR.js.map → cli-console-Cu1DzqvR.js.map} +1 -1
  9. package/dist/{cli-schema-dir-CiN0ephV.js → cli-schema-dir-DuZIsF2e.js} +5 -5
  10. package/dist/{cli-schema-dir-CiN0ephV.js.map → cli-schema-dir-DuZIsF2e.js.map} +1 -1
  11. package/dist/cli.js +124 -36
  12. package/dist/cli.js.map +1 -1
  13. package/dist/{database-preflight-bfnIBnjM.js → database-preflight-CyTCWlfc.js} +2 -2
  14. package/dist/{database-preflight-bfnIBnjM.js.map → database-preflight-CyTCWlfc.js.map} +1 -1
  15. package/dist/{deferred-index-build-CcSDA7wE.js → deferred-index-build-ueYVUBZc.js} +4 -4
  16. package/dist/{deferred-index-build-CcSDA7wE.js.map → deferred-index-build-ueYVUBZc.js.map} +1 -1
  17. package/dist/{ensure-policies-rRmXb5bt.js → ensure-policies-13mHWjBs.js} +7 -7
  18. package/dist/{ensure-policies-rRmXb5bt.js.map → ensure-policies-13mHWjBs.js.map} +1 -1
  19. package/dist/{ensure-tables-Bvm-F2wW.js → ensure-tables-B3Kh2RwT.js} +7 -7
  20. package/dist/{ensure-tables-Bvm-F2wW.js.map → ensure-tables-B3Kh2RwT.js.map} +1 -1
  21. package/dist/{ensure-tables-CC8p_AK3.js → ensure-tables-DM1U9AZK.js} +3 -3
  22. package/dist/{ensure-tables-CC8p_AK3.js.map → ensure-tables-DM1U9AZK.js.map} +1 -1
  23. package/dist/{enum-labels-kept-FlX9SHdf.js → enum-labels-kept-CJDVtX14.js} +2 -2
  24. package/dist/{enum-labels-kept-FlX9SHdf.js.map → enum-labels-kept-CJDVtX14.js.map} +1 -1
  25. package/dist/{generate-drizzle-schema-SJMXxzPI.js → generate-drizzle-schema-B-Mkf8UI.js} +2 -2
  26. package/dist/{generate-drizzle-schema-SJMXxzPI.js.map → generate-drizzle-schema-B-Mkf8UI.js.map} +1 -1
  27. package/dist/{generate-files-tlJ9_lGI.js → generate-files-8MUP8UHC.js} +2 -2
  28. package/dist/{generate-files-tlJ9_lGI.js.map → generate-files-8MUP8UHC.js.map} +1 -1
  29. package/dist/{generate-postgres-ddl-logic-B8huc03c.js → generate-postgres-ddl-logic-CQof4iFH.js} +89 -45
  30. package/dist/generate-postgres-ddl-logic-CQof4iFH.js.map +1 -0
  31. package/dist/index.d.ts +7 -0
  32. package/dist/index.es.js +14 -14
  33. package/dist/{migrate-baseline-DZmekgpD.js → migrate-baseline-DnMlSDup.js} +9 -2
  34. package/dist/{migrate-baseline-DZmekgpD.js.map → migrate-baseline-DnMlSDup.js.map} +1 -1
  35. package/dist/{migrate-policy-stamps-B_acrUQB.js → migrate-policy-stamps-BpHyEFkk.js} +5 -5
  36. package/dist/{migrate-policy-stamps-B_acrUQB.js.map → migrate-policy-stamps-BpHyEFkk.js.map} +1 -1
  37. package/dist/{open-rebase-4kisUF_k.js → open-rebase-B2mAA7UE.js} +175 -38
  38. package/dist/open-rebase-B2mAA7UE.js.map +1 -0
  39. package/dist/{pg-error-utils-BT5NzGFZ.js → pg-error-utils-CpUiBkp-.js} +2 -2
  40. package/dist/{pg-error-utils-BT5NzGFZ.js.map → pg-error-utils-CpUiBkp-.js.map} +1 -1
  41. package/dist/{policy-drift-BVMyqHSa.js → policy-drift-C9xRcbsU.js} +4 -4
  42. package/dist/{policy-drift-BVMyqHSa.js.map → policy-drift-C9xRcbsU.js.map} +1 -1
  43. package/dist/{push-index-adoption-hpHTyXMR.js → push-index-adoption-D-ph6kBc.js} +2 -2
  44. package/dist/{push-index-adoption-hpHTyXMR.js.map → push-index-adoption-D-ph6kBc.js.map} +1 -1
  45. package/dist/{push-index-prebuild-Bty9F7bD.js → push-index-prebuild-DUKtH87s.js} +3 -3
  46. package/dist/{push-index-prebuild-Bty9F7bD.js.map → push-index-prebuild-DUKtH87s.js.map} +1 -1
  47. package/dist/{push-legacy-renames-bB4bM6br.js → push-legacy-renames-wLSsAg80.js} +3 -3
  48. package/dist/{push-legacy-renames-bB4bM6br.js.map → push-legacy-renames-wLSsAg80.js.map} +1 -1
  49. package/dist/{push-policy-plan-BI8U4BOD.js → push-policy-plan-I9RNoP_-.js} +3 -3
  50. package/dist/{push-policy-plan-BI8U4BOD.js.map → push-policy-plan-I9RNoP_-.js.map} +1 -1
  51. package/dist/{request-role-cli-BdRzdE87.js → request-role-cli-D9yWoeSl.js} +8 -8
  52. package/dist/{request-role-cli-BdRzdE87.js.map → request-role-cli-D9yWoeSl.js.map} +1 -1
  53. package/dist/{request-role-migration-C8aq_TO3.js → request-role-migration-DQLiYJ4c.js} +2 -2
  54. package/dist/{request-role-migration-C8aq_TO3.js.map → request-role-migration-DQLiYJ4c.js.map} +1 -1
  55. package/dist/{rls-enforcement-DB5HHj96.js → rls-enforcement-Cwh5SJRx.js} +2 -2
  56. package/dist/{rls-enforcement-DB5HHj96.js.map → rls-enforcement-Cwh5SJRx.js.map} +1 -1
  57. package/dist/schema/doctor-cli.js +5 -5
  58. package/dist/schema/generate-drizzle-schema.js +1 -1
  59. package/dist/schema/generate-postgres-ddl-logic.d.ts +51 -8
  60. package/dist/schema/generate-postgres-ddl.js +1 -1
  61. package/dist/schema/introspect-db.js +1 -1
  62. package/dist/services/cdc/capture-consumers.d.ts +65 -0
  63. package/dist/services/cdc/wal-cdc.d.ts +13 -0
  64. package/dist/services/realtimeService.d.ts +18 -2
  65. package/dist/{websocket-BevXvwfo.js → websocket-CSVNOYHC.js} +3 -3
  66. package/dist/{websocket-BevXvwfo.js.map → websocket-CSVNOYHC.js.map} +1 -1
  67. package/package.json +7 -7
  68. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +0 -1
  69. package/dist/open-rebase-4kisUF_k.js.map +0 -1
@@ -1,12 +1,12 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { u as pinSearchPath } from "./connection-C1zXTPJq.js";
4
- import { G as withAppClient } from "./cli-schema-dir-CiN0ephV.js";
4
+ import { G as withAppClient } from "./cli-schema-dir-DuZIsF2e.js";
5
5
  import { a as outWarn, r as out, t as chalk } from "./source-VxbrQojV.js";
6
- import { u as planTablePolicies } from "./generate-postgres-ddl-logic-B8huc03c.js";
6
+ import { d as planTablePolicies } from "./generate-postgres-ddl-logic-CQof4iFH.js";
7
7
  import { r as loadTables } from "./load-tables-B1Re74ng.js";
8
- import { ensureTablePolicies, policyStampSql, probeRenderedPolicies, readPolicyStamps } from "./ensure-policies-rRmXb5bt.js";
9
- import { underSearchPath } from "./push-policy-plan-BI8U4BOD.js";
8
+ import { ensureTablePolicies, policyStampSql, probeRenderedPolicies, readPolicyStamps } from "./ensure-policies-13mHWjBs.js";
9
+ import { underSearchPath } from "./push-policy-plan-I9RNoP_-.js";
10
10
  //#region src/schema/migrate-policy-stamps.ts
11
11
  /**
12
12
  * The stamps `rebase db migrate` leaves on the policies it applied.
@@ -114,4 +114,4 @@ async function moveMigratedAdminPoliciesToPublic(client, compiledTables, log) {
114
114
  //#endregion
115
115
  export { moveMigratedAdminPoliciesToPublic, stampMigratedPolicies };
116
116
 
117
- //# sourceMappingURL=migrate-policy-stamps-B_acrUQB.js.map
117
+ //# sourceMappingURL=migrate-policy-stamps-BpHyEFkk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-policy-stamps-B_acrUQB.js","names":[],"sources":["../src/schema/migrate-policy-stamps.ts"],"sourcesContent":["/**\n * The stamps `rebase db migrate` leaves on the policies it applied.\n *\n * A boot leaves a table's policies alone only when each carries the stamp a\n * boot or a push writes (`COMMENT ON POLICY … IS 'rebase:<hash>'`, see\n * `policyStampSql`). `db push` stamps what `policies.sql` just created. A\n * migration runs the same statements — `db generate` appends `policies.sql` to\n * it — and stamped nothing, so the first boot after every migrate dropped and\n * re-created every policy once, an ACCESS EXCLUSIVE lock per table: 44 on the\n * blog scaffold.\n *\n * Migrate cannot stamp what the files hold, the way push stamps what it just\n * ran: a migration was written from the tables of its day, and the\n * database may hold something a later one, or a hand, made since. A stamp\n * there would tell the boot a policy is what the rule makes when it is not, and\n * the boot would never put it right. So each declared policy without a current\n * stamp is asked of Postgres instead, as `db push --dry-run` asks it\n * (`probeRenderedPolicies`): made again from its rule under a probe name, in a\n * transaction that is rolled back, and compared. Only a policy whose stored\n * definition is exactly what its rule makes is stamped. Any other keeps no\n * stamp, and the boot re-applies its table, as before.\n */\nimport chalk from \"chalk\";\nimport type { CompiledTable } from \"@rebasepro/types\";\nimport type { Queryable } from \"../security/policy-drift\";\nimport { withAppClient } from \"../cli-helpers\";\nimport { out, outWarn } from \"../cli-output\";\nimport { pinSearchPath } from \"../connection\";\nimport { planTablePolicies } from \"./generate-postgres-ddl-logic\";\nimport { ensureTablePolicies, policyStampSql, probeRenderedPolicies, readPolicyStamps } from \"./ensure-policies\";\nimport { underSearchPath } from \"./push-policy-plan\";\nimport { loadTables } from \"./load-tables\";\n\n/**\n * `rebase db migrate`'s last step: stamp what the migration left as its rules\n * make it, on this process's connection. Never fatal — a policy left\n * unstamped costs the next boot a re-apply of its table, which is what every\n * boot after a migrate did before this.\n */\nexport async function stampMigratedPolicies(databaseUrl: string, schemaDir: string, adminRoleAvailable = true): Promise<void> {\n try {\n const compiledTables = await loadTables(schemaDir);\n // The rule the boot's connections follow: `search_path=public` unless\n // the URL pins one of its own, in which case this connection has it too.\n const searchPath = pinSearchPath(databaseUrl) === databaseUrl ? undefined : \"public\";\n const { stamped } = await withAppClient(databaseUrl, client => stampPoliciesStoredAsRendered(\n { query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) },\n compiledTables,\n { searchPath, adminRoleAvailable }\n ));\n if (stamped > 0) {\n out(chalk.gray(` ✓ Stamped ${stamped} RLS ${stamped === 1 ? \"policy\" : \"policies\"} as their rules make them, so the next boot leaves ${stamped === 1 ? \"it\" : \"them\"} alone.`));\n }\n } catch (err) {\n outWarn(chalk.yellow(` ⚠️ The policies could not be stamped (${err instanceof Error ? err.message : String(err)}); the next boot applies them again.`));\n }\n}\n\n/**\n * Stamp every declared policy whose stored definition its rule would store\n * as it is, and none other.\n *\n * @param options.searchPath the `search_path` a boot reads policies under,\n * when the connection's own differs — the stamp hashes `pg_get_expr`,\n * whose spelling depends on it. See `PolicyStamping.searchPath`.\n * @returns how many policies were stamped.\n */\nexport async function stampPoliciesStoredAsRendered(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n options: { searchPath?: string; adminRoleAvailable?: boolean } = {}\n): Promise<{ stamped: number }> {\n const { adminRoleAvailable } = options;\n const plans = planTablePolicies(compiledTables, { adminRoleAvailable });\n if (plans.length === 0) return { stamped: 0 };\n\n const states = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, compiledTables, { adminRoleAvailable }));\n const unsure: { schema: string; table: string; name: string }[] = [];\n for (const plan of plans) {\n for (const [name, state] of states.get(plan.qualified) ?? []) {\n if (state !== \"current\") unsure.push({ schema: plan.schema, table: plan.table, name });\n }\n }\n if (unsure.length === 0) return { stamped: 0 };\n\n const confirmed = await probeRenderedPolicies(client, compiledTables, unsure, { searchPath: options.searchPath, adminRoleAvailable });\n const statements: string[] = [];\n let stamped = 0;\n for (const plan of plans) {\n const names = new Set(unsure\n .filter(p => p.schema === plan.schema && p.table === plan.table\n && confirmed.get(`${p.schema}.${p.table}.${p.name}`) === true)\n .map(p => p.name));\n const statement = names.size > 0 ? policyStampSql(plan, names) : undefined;\n if (!statement) continue;\n statements.push(statement);\n stamped += names.size;\n }\n if (statements.length === 0) return { stamped: 0 };\n\n await underSearchPath(client, options.searchPath, async () => {\n for (const statement of statements) await client.query(statement);\n });\n return { stamped };\n}\n\n/**\n * Where the admin switch is not live, move the server-or-admin policies a\n * migration just wrote `TO rebase_admin` back `TO public`, as `db push` and a\n * provisioning boot write them.\n *\n * A migration replays `policies.sql` as `db generate` wrote it, and that cannot\n * know the database it will run on. Left `TO rebase_admin` while admin requests\n * still run as the request role, those policies refuse every admin caller —\n * `dataAsAdmin` in crons, jobs and functions included — and a boot with\n * `REBASE_PROVISION=false` never puts them right.\n *\n * This is the boot's own ensure under the fallback plan, so a table whose\n * policies are already what that plan makes is left alone.\n *\n * @returns how many policies were written again.\n */\nexport async function moveMigratedAdminPoliciesToPublic(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n log?: (message: string) => void\n): Promise<number> {\n if (!planTablePolicies(compiledTables).some(plan => plan.policies.some(policy => policy.adminTarget))) return 0;\n const outcome = await ensureTablePolicies(client, compiledTables, log, { adminRoleAvailable: false });\n if (outcome.failures.length > 0) {\n throw new Error(outcome.failures.map(f => `${f.table}: ${f.error}`).join(\"; \"));\n }\n return outcome.policiesApplied;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,eAAsB,sBAAsB,aAAqB,WAAmB,qBAAqB,MAAqB;CAC1H,IAAI;EACA,MAAM,iBAAiB,MAAM,WAAW,SAAS;EAGjD,MAAM,aAAa,cAAc,WAAW,MAAM,cAAc,KAAA,IAAY;EAC5E,MAAM,EAAE,YAAY,MAAM,cAAc,cAAa,WAAU,8BAC3D,EAAE,OAAO,OAAO,MAAM,YAAY,EAAE,OAAO,MAAM,OAAO,MAAM,MAAM,MAAM,EAAA,CAAG,KAAK,GAAG,GACrF,gBACA;GAAE;GAAY;EAAmB,CACrC,CAAC;EACD,IAAI,UAAU,GACV,IAAI,MAAM,KAAK,eAAe,QAAQ,OAAO,YAAY,IAAI,WAAW,WAAW,qDAAqD,YAAY,IAAI,OAAO,OAAO,QAAQ,CAAC;CAEvL,SAAS,KAAK;EACV,QAAQ,MAAM,OAAO,4CAA4C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE,qCAAqC,CAAC;CAC5J;AACJ;;;;;;;;;;AAWA,eAAsB,8BAClB,QACA,gBACA,UAAiE,CAAC,GACtC;CAC5B,MAAM,EAAE,uBAAuB;CAC/B,MAAM,QAAQ,kBAAkB,gBAAgB,EAAE,mBAAmB,CAAC;CACtE,IAAI,MAAM,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAE5C,MAAM,SAAS,MAAM,gBAAgB,QAAQ,QAAQ,kBAAkB,iBAAiB,QAAQ,gBAAgB,EAAE,mBAAmB,CAAC,CAAC;CACvI,MAAM,SAA4D,CAAC;CACnE,KAAK,MAAM,QAAQ,OACf,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,IAAI,KAAK,SAAS,KAAK,CAAC,GACvD,IAAI,UAAU,WAAW,OAAO,KAAK;EAAE,QAAQ,KAAK;EAAQ,OAAO,KAAK;EAAO;CAAK,CAAC;CAG7F,IAAI,OAAO,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAE7C,MAAM,YAAY,MAAM,sBAAsB,QAAQ,gBAAgB,QAAQ;EAAE,YAAY,QAAQ;EAAY;CAAmB,CAAC;CACpI,MAAM,aAAuB,CAAC;CAC9B,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,OAAO;EACtB,MAAM,QAAQ,IAAI,IAAI,OACjB,QAAO,MAAK,EAAE,WAAW,KAAK,UAAU,EAAE,UAAU,KAAK,SACnD,UAAU,IAAI,GAAG,EAAE,OAAO,GAAG,EAAE,MAAM,GAAG,EAAE,MAAM,MAAM,IAAI,CAAC,CACjE,KAAI,MAAK,EAAE,IAAI,CAAC;EACrB,MAAM,YAAY,MAAM,OAAO,IAAI,eAAe,MAAM,KAAK,IAAI,KAAA;EACjE,IAAI,CAAC,WAAW;EAChB,WAAW,KAAK,SAAS;EACzB,WAAW,MAAM;CACrB;CACA,IAAI,WAAW,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAEjD,MAAM,gBAAgB,QAAQ,QAAQ,YAAY,YAAY;EAC1D,KAAK,MAAM,aAAa,YAAY,MAAM,OAAO,MAAM,SAAS;CACpE,CAAC;CACD,OAAO,EAAE,QAAQ;AACrB;;;;;;;;;;;;;;;;;AAkBA,eAAsB,kCAClB,QACA,gBACA,KACe;CACf,IAAI,CAAC,kBAAkB,cAAc,CAAC,CAAC,MAAK,SAAQ,KAAK,SAAS,MAAK,WAAU,OAAO,WAAW,CAAC,GAAG,OAAO;CAC9G,MAAM,UAAU,MAAM,oBAAoB,QAAQ,gBAAgB,KAAK,EAAE,oBAAoB,MAAM,CAAC;CACpG,IAAI,QAAQ,SAAS,SAAS,GAC1B,MAAM,IAAI,MAAM,QAAQ,SAAS,KAAI,MAAK,GAAG,EAAE,MAAM,IAAI,EAAE,OAAO,CAAC,CAAC,KAAK,IAAI,CAAC;CAElF,OAAO,QAAQ;AACnB"}
1
+ {"version":3,"file":"migrate-policy-stamps-BpHyEFkk.js","names":[],"sources":["../src/schema/migrate-policy-stamps.ts"],"sourcesContent":["/**\n * The stamps `rebase db migrate` leaves on the policies it applied.\n *\n * A boot leaves a table's policies alone only when each carries the stamp a\n * boot or a push writes (`COMMENT ON POLICY … IS 'rebase:<hash>'`, see\n * `policyStampSql`). `db push` stamps what `policies.sql` just created. A\n * migration runs the same statements — `db generate` appends `policies.sql` to\n * it — and stamped nothing, so the first boot after every migrate dropped and\n * re-created every policy once, an ACCESS EXCLUSIVE lock per table: 44 on the\n * blog scaffold.\n *\n * Migrate cannot stamp what the files hold, the way push stamps what it just\n * ran: a migration was written from the tables of its day, and the\n * database may hold something a later one, or a hand, made since. A stamp\n * there would tell the boot a policy is what the rule makes when it is not, and\n * the boot would never put it right. So each declared policy without a current\n * stamp is asked of Postgres instead, as `db push --dry-run` asks it\n * (`probeRenderedPolicies`): made again from its rule under a probe name, in a\n * transaction that is rolled back, and compared. Only a policy whose stored\n * definition is exactly what its rule makes is stamped. Any other keeps no\n * stamp, and the boot re-applies its table, as before.\n */\nimport chalk from \"chalk\";\nimport type { CompiledTable } from \"@rebasepro/types\";\nimport type { Queryable } from \"../security/policy-drift\";\nimport { withAppClient } from \"../cli-helpers\";\nimport { out, outWarn } from \"../cli-output\";\nimport { pinSearchPath } from \"../connection\";\nimport { planTablePolicies } from \"./generate-postgres-ddl-logic\";\nimport { ensureTablePolicies, policyStampSql, probeRenderedPolicies, readPolicyStamps } from \"./ensure-policies\";\nimport { underSearchPath } from \"./push-policy-plan\";\nimport { loadTables } from \"./load-tables\";\n\n/**\n * `rebase db migrate`'s last step: stamp what the migration left as its rules\n * make it, on this process's connection. Never fatal — a policy left\n * unstamped costs the next boot a re-apply of its table, which is what every\n * boot after a migrate did before this.\n */\nexport async function stampMigratedPolicies(databaseUrl: string, schemaDir: string, adminRoleAvailable = true): Promise<void> {\n try {\n const compiledTables = await loadTables(schemaDir);\n // The rule the boot's connections follow: `search_path=public` unless\n // the URL pins one of its own, in which case this connection has it too.\n const searchPath = pinSearchPath(databaseUrl) === databaseUrl ? undefined : \"public\";\n const { stamped } = await withAppClient(databaseUrl, client => stampPoliciesStoredAsRendered(\n { query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) },\n compiledTables,\n { searchPath, adminRoleAvailable }\n ));\n if (stamped > 0) {\n out(chalk.gray(` ✓ Stamped ${stamped} RLS ${stamped === 1 ? \"policy\" : \"policies\"} as their rules make them, so the next boot leaves ${stamped === 1 ? \"it\" : \"them\"} alone.`));\n }\n } catch (err) {\n outWarn(chalk.yellow(` ⚠️ The policies could not be stamped (${err instanceof Error ? err.message : String(err)}); the next boot applies them again.`));\n }\n}\n\n/**\n * Stamp every declared policy whose stored definition its rule would store\n * as it is, and none other.\n *\n * @param options.searchPath the `search_path` a boot reads policies under,\n * when the connection's own differs — the stamp hashes `pg_get_expr`,\n * whose spelling depends on it. See `PolicyStamping.searchPath`.\n * @returns how many policies were stamped.\n */\nexport async function stampPoliciesStoredAsRendered(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n options: { searchPath?: string; adminRoleAvailable?: boolean } = {}\n): Promise<{ stamped: number }> {\n const { adminRoleAvailable } = options;\n const plans = planTablePolicies(compiledTables, { adminRoleAvailable });\n if (plans.length === 0) return { stamped: 0 };\n\n const states = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, compiledTables, { adminRoleAvailable }));\n const unsure: { schema: string; table: string; name: string }[] = [];\n for (const plan of plans) {\n for (const [name, state] of states.get(plan.qualified) ?? []) {\n if (state !== \"current\") unsure.push({ schema: plan.schema, table: plan.table, name });\n }\n }\n if (unsure.length === 0) return { stamped: 0 };\n\n const confirmed = await probeRenderedPolicies(client, compiledTables, unsure, { searchPath: options.searchPath, adminRoleAvailable });\n const statements: string[] = [];\n let stamped = 0;\n for (const plan of plans) {\n const names = new Set(unsure\n .filter(p => p.schema === plan.schema && p.table === plan.table\n && confirmed.get(`${p.schema}.${p.table}.${p.name}`) === true)\n .map(p => p.name));\n const statement = names.size > 0 ? policyStampSql(plan, names) : undefined;\n if (!statement) continue;\n statements.push(statement);\n stamped += names.size;\n }\n if (statements.length === 0) return { stamped: 0 };\n\n await underSearchPath(client, options.searchPath, async () => {\n for (const statement of statements) await client.query(statement);\n });\n return { stamped };\n}\n\n/**\n * Where the admin switch is not live, move the server-or-admin policies a\n * migration just wrote `TO rebase_admin` back `TO public`, as `db push` and a\n * provisioning boot write them.\n *\n * A migration replays `policies.sql` as `db generate` wrote it, and that cannot\n * know the database it will run on. Left `TO rebase_admin` while admin requests\n * still run as the request role, those policies refuse every admin caller —\n * `dataAsAdmin` in crons, jobs and functions included — and a boot with\n * `REBASE_PROVISION=false` never puts them right.\n *\n * This is the boot's own ensure under the fallback plan, so a table whose\n * policies are already what that plan makes is left alone.\n *\n * @returns how many policies were written again.\n */\nexport async function moveMigratedAdminPoliciesToPublic(\n client: Queryable,\n compiledTables: readonly CompiledTable[],\n log?: (message: string) => void\n): Promise<number> {\n if (!planTablePolicies(compiledTables).some(plan => plan.policies.some(policy => policy.adminTarget))) return 0;\n const outcome = await ensureTablePolicies(client, compiledTables, log, { adminRoleAvailable: false });\n if (outcome.failures.length > 0) {\n throw new Error(outcome.failures.map(f => `${f.table}: ${f.error}`).join(\"; \"));\n }\n return outcome.policiesApplied;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,eAAsB,sBAAsB,aAAqB,WAAmB,qBAAqB,MAAqB;CAC1H,IAAI;EACA,MAAM,iBAAiB,MAAM,WAAW,SAAS;EAGjD,MAAM,aAAa,cAAc,WAAW,MAAM,cAAc,KAAA,IAAY;EAC5E,MAAM,EAAE,YAAY,MAAM,cAAc,cAAa,WAAU,8BAC3D,EAAE,OAAO,OAAO,MAAM,YAAY,EAAE,OAAO,MAAM,OAAO,MAAM,MAAM,MAAM,EAAA,CAAG,KAAK,GAAG,GACrF,gBACA;GAAE;GAAY;EAAmB,CACrC,CAAC;EACD,IAAI,UAAU,GACV,IAAI,MAAM,KAAK,eAAe,QAAQ,OAAO,YAAY,IAAI,WAAW,WAAW,qDAAqD,YAAY,IAAI,OAAO,OAAO,QAAQ,CAAC;CAEvL,SAAS,KAAK;EACV,QAAQ,MAAM,OAAO,4CAA4C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE,qCAAqC,CAAC;CAC5J;AACJ;;;;;;;;;;AAWA,eAAsB,8BAClB,QACA,gBACA,UAAiE,CAAC,GACtC;CAC5B,MAAM,EAAE,uBAAuB;CAC/B,MAAM,QAAQ,kBAAkB,gBAAgB,EAAE,mBAAmB,CAAC;CACtE,IAAI,MAAM,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAE5C,MAAM,SAAS,MAAM,gBAAgB,QAAQ,QAAQ,kBAAkB,iBAAiB,QAAQ,gBAAgB,EAAE,mBAAmB,CAAC,CAAC;CACvI,MAAM,SAA4D,CAAC;CACnE,KAAK,MAAM,QAAQ,OACf,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,IAAI,KAAK,SAAS,KAAK,CAAC,GACvD,IAAI,UAAU,WAAW,OAAO,KAAK;EAAE,QAAQ,KAAK;EAAQ,OAAO,KAAK;EAAO;CAAK,CAAC;CAG7F,IAAI,OAAO,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAE7C,MAAM,YAAY,MAAM,sBAAsB,QAAQ,gBAAgB,QAAQ;EAAE,YAAY,QAAQ;EAAY;CAAmB,CAAC;CACpI,MAAM,aAAuB,CAAC;CAC9B,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,OAAO;EACtB,MAAM,QAAQ,IAAI,IAAI,OACjB,QAAO,MAAK,EAAE,WAAW,KAAK,UAAU,EAAE,UAAU,KAAK,SACnD,UAAU,IAAI,GAAG,EAAE,OAAO,GAAG,EAAE,MAAM,GAAG,EAAE,MAAM,MAAM,IAAI,CAAC,CACjE,KAAI,MAAK,EAAE,IAAI,CAAC;EACrB,MAAM,YAAY,MAAM,OAAO,IAAI,eAAe,MAAM,KAAK,IAAI,KAAA;EACjE,IAAI,CAAC,WAAW;EAChB,WAAW,KAAK,SAAS;EACzB,WAAW,MAAM;CACrB;CACA,IAAI,WAAW,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAEjD,MAAM,gBAAgB,QAAQ,QAAQ,YAAY,YAAY;EAC1D,KAAK,MAAM,aAAa,YAAY,MAAM,OAAO,MAAM,SAAS;CACpE,CAAC;CACD,OAAO,EAAE,QAAQ;AACrB;;;;;;;;;;;;;;;;;AAkBA,eAAsB,kCAClB,QACA,gBACA,KACe;CACf,IAAI,CAAC,kBAAkB,cAAc,CAAC,CAAC,MAAK,SAAQ,KAAK,SAAS,MAAK,WAAU,OAAO,WAAW,CAAC,GAAG,OAAO;CAC9G,MAAM,UAAU,MAAM,oBAAoB,QAAQ,gBAAgB,KAAK,EAAE,oBAAoB,MAAM,CAAC;CACpG,IAAI,QAAQ,SAAS,SAAS,GAC1B,MAAM,IAAI,MAAM,QAAQ,SAAS,KAAI,MAAK,GAAG,EAAE,MAAM,IAAI,EAAE,OAAO,CAAC,CAAC,KAAK,IAAI,CAAC;CAElF,OAAO,QAAQ;AACnB"}
@@ -3,23 +3,23 @@ __createRequire(import.meta.url);
3
3
  import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, h as transactionSettingsStatements, l as isPooledPool, m as transactionSettingsConfig, n as closeWithPool, p as searchPathList } from "./connection-C1zXTPJq.js";
4
4
  import { i as buildTableSearchColumnSpec, o as isSearchIndexColumn, r as SEARCH_UNACCENT_FN } from "./search-column-BO-WND-B.js";
5
5
  import { r as viewRowsName, t as DEFAULT_VIEW_ROLES } from "./view-names-Dscp6--B.js";
6
- import { a as closedDatabaseName, c as diagnoseDbError, ct as extractCauseMessage, d as isEconnrefused, o as deepestErrorMessage, p as parseHostInfo } from "./cli-schema-dir-CiN0ephV.js";
7
- import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-BT5NzGFZ.js";
8
- import { t as BranchService } from "./BranchService-USp1AvZB.js";
6
+ import { a as closedDatabaseName, c as diagnoseDbError, ct as extractCauseMessage, d as isEconnrefused, o as deepestErrorMessage, p as parseHostInfo } from "./cli-schema-dir-DuZIsF2e.js";
7
+ import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-CpUiBkp-.js";
8
+ import { t as BranchService } from "./BranchService-C8LtpMho.js";
9
9
  import { i as rlsHandoverNotes, n as resolveRlsSettings, r as rlsConfigFromEnv } from "./rls-settings-CmGK2U0a.js";
10
- import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles, T as warnOnRoleSchemaCollision, _ as recordRequestRoles, a as assertRecordedRequestRoles, b as roleHoldsTableGrants, c as ensureAppRole, d as findExposedInternalTables, f as findOtherRoleMembers, g as readRecordedRequestRoles, h as proveRoleSwitch, i as assertAppRoleRestricted, l as ensureAppRoleGrants, o as authContextStatement, p as findUngrantableTables, r as applyAuthContext, s as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as ensureConnectionInheritsAdminRole, v as revokeUserRoleSql, w as warnOnLegacyRlsFunctions, x as settleAdminSwitch } from "./rls-enforcement-DB5HHj96.js";
10
+ import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles, T as warnOnRoleSchemaCollision, _ as recordRequestRoles, a as assertRecordedRequestRoles, b as roleHoldsTableGrants, c as ensureAppRole, d as findExposedInternalTables, f as findOtherRoleMembers, g as readRecordedRequestRoles, h as proveRoleSwitch, i as assertAppRoleRestricted, l as ensureAppRoleGrants, o as authContextStatement, p as findUngrantableTables, r as applyAuthContext, s as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as ensureConnectionInheritsAdminRole, v as revokeUserRoleSql, w as warnOnLegacyRlsFunctions, x as settleAdminSwitch } from "./rls-enforcement-Cwh5SJRx.js";
11
11
  import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-BpfgbkxZ.js";
12
12
  import { i as plannedColumnEntries, n as planSchema, r as quoteSqlLiteral } from "./plan-schema-Hbtjhge3.js";
13
13
  import { t as generateSchema } from "./generate-drizzle-schema-logic-DL7R1rAF.js";
14
14
  import { i as renderPgType } from "./render-ddl-D4n86NHz.js";
15
- import { u as planTablePolicies } from "./generate-postgres-ddl-logic-B8huc03c.js";
16
- import { d as typesAgree, s as diffPlanAgainstCatalogue } from "./deferred-index-build-CcSDA7wE.js";
17
- import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-5H2bL_80.js";
18
- import { a as readSchemaFactsFor, r as planTableSchemaEnsure } from "./ensure-tables-Bvm-F2wW.js";
15
+ import { d as planTablePolicies } from "./generate-postgres-ddl-logic-CQof4iFH.js";
16
+ import { d as typesAgree, s as diffPlanAgainstCatalogue } from "./deferred-index-build-ueYVUBZc.js";
17
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-CSYhSSZD.js";
18
+ import { a as readSchemaFactsFor, r as planTableSchemaEnsure } from "./ensure-tables-B3Kh2RwT.js";
19
19
  import { n as introspectTables, t as describeUnmappedTables } from "./introspect-tables-Cw_A-kk4.js";
20
20
  import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
21
21
  import { t as DatabasePoolManager } from "./databasePoolManager-DIjzlTK4.js";
22
- import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-CC8p_AK3.js";
22
+ import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-DM1U9AZK.js";
23
23
  import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as compileIntrospectedTables } from "./generated-schema-diff-DoT2dYDe.js";
24
24
  import pg, { Client, DatabaseError, Pool } from "pg";
25
25
  import { NodePgDatabase, NodePgSession, NodePgTransaction, drizzle } from "drizzle-orm/node-postgres";
@@ -15568,6 +15568,24 @@ async function walCaptureBlocker(run) {
15568
15568
  if (version > 0 && version < 1e5) return `Postgres ${Math.floor(version / 1e4)} has no pgoutput (10 or later is needed)`;
15569
15569
  if (walLevel !== "logical") return `wal_level is "${walLevel || "unknown"}", and logical decoding needs wal_level=logical (a server restart)`;
15570
15570
  }
15571
+ /**
15572
+ * What a boot says when it tried WAL capture and could not use it, before it
15573
+ * falls back to the capture triggers.
15574
+ *
15575
+ * `REALTIME_CDC=wal` asked for the WAL, so not getting it is a warning.
15576
+ * `auto` — the default — tries the WAL wherever it might work, and most
15577
+ * databases are not set up for logical decoding: there, falling back is the
15578
+ * expected outcome and an info line.
15579
+ */
15580
+ function walFallbackNotice(mode) {
15581
+ return mode === "wal" ? {
15582
+ level: "warn",
15583
+ message: "⚠️ [CDC] REALTIME_CDC=wal, but changes cannot be streamed from the WAL — using trigger-based capture instead."
15584
+ } : {
15585
+ level: "info",
15586
+ message: "ℹ️ [CDC] Changes cannot be streamed from the WAL here — using trigger-based capture (REALTIME_CDC=auto)."
15587
+ };
15588
+ }
15571
15589
  async function readTableStates(run, tables) {
15572
15590
  const states = /* @__PURE__ */ new Map();
15573
15591
  if (tables.length === 0) return states;
@@ -15658,6 +15676,61 @@ function reportUnpublishedTables(result) {
15658
15676
  for (const table of result.skipped) logger.warn(`⚠️ [CDC] "${table.schema}.${table.table}" is not captured from the WAL — ${table.reason}.`);
15659
15677
  }
15660
15678
  //#endregion
15679
+ //#region src/services/cdc/capture-consumers.ts
15680
+ /** How every realtime LISTEN connection's `application_name` starts. */
15681
+ var REALTIME_LISTENER_APPLICATION_PREFIX = "rebase-realtime:";
15682
+ /** The `application_name` of one of an instance's realtime connections. */
15683
+ function realtimeListenerApplicationName(instanceName, role) {
15684
+ return `${instanceName}:${role}`;
15685
+ }
15686
+ /**
15687
+ * Whether a session may be hearing changes through the capture triggers.
15688
+ *
15689
+ * @param ownInstanceName This process's `rebase-realtime:<instance id>`; its
15690
+ * own connections never count.
15691
+ */
15692
+ function isTriggerCaptureConsumer(session, ownInstanceName) {
15693
+ const name = session.applicationName;
15694
+ if (!name || !name.startsWith("rebase-realtime:")) return false;
15695
+ if (name === ownInstanceName || name.startsWith(`${ownInstanceName}:`)) return false;
15696
+ if (session.backendType === "walsender") return false;
15697
+ const rest = name.slice(16);
15698
+ const role = rest.includes(":") ? rest.slice(rest.lastIndexOf(":") + 1) : void 0;
15699
+ if (role === "entity" || role === "wal") return false;
15700
+ return true;
15701
+ }
15702
+ /**
15703
+ * How many other sessions on this database may depend on the capture
15704
+ * triggers. A failed query answers `undefined` — the caller keeps the triggers.
15705
+ */
15706
+ async function countTriggerCaptureConsumers(run, ownInstanceName) {
15707
+ try {
15708
+ return (await run(`SELECT application_name, backend_type FROM pg_stat_activity WHERE datname = current_database() AND starts_with(application_name, '${REALTIME_LISTENER_APPLICATION_PREFIX}')`)).map((row) => ({
15709
+ applicationName: typeof row.application_name === "string" ? row.application_name : null,
15710
+ backendType: typeof row.backend_type === "string" ? row.backend_type : null
15711
+ })).filter((session) => isTriggerCaptureConsumer(session, ownInstanceName)).length;
15712
+ } catch {
15713
+ return;
15714
+ }
15715
+ }
15716
+ /** How often a WAL-streaming instance that kept the triggers for another one checks whether it is gone. */
15717
+ var TRIGGER_RETIREMENT_INTERVAL_MS = 300 * 1e3;
15718
+ /**
15719
+ * Take the capture triggers off the tables — unless another session may still
15720
+ * be hearing changes through them ({@link countTriggerCaptureConsumers}).
15721
+ *
15722
+ * For a process that streams changes from the WAL: it does not need them, and
15723
+ * every write pays a trigger and a NOTIFY while they stay.
15724
+ */
15725
+ async function retireTriggerCaptureIfUnused(run, ownInstanceName) {
15726
+ const consumers = await countTriggerCaptureConsumers(run, ownInstanceName);
15727
+ if (consumers === void 0 || consumers > 0) return {
15728
+ kept: true,
15729
+ consumers
15730
+ };
15731
+ return { removed: await removeTriggerCdc(run) };
15732
+ }
15733
+ //#endregion
15661
15734
  //#region src/services/socket-liveness.ts
15662
15735
  /**
15663
15736
  * Letting go of client sockets the server can no longer reach.
@@ -16670,12 +16743,6 @@ function createChannelBus(setting, deps) {
16670
16743
  /** Channel name used for Postgres LISTEN/NOTIFY cross-instance realtime. */
16671
16744
  var PG_NOTIFY_CHANNEL = "rebase_entity_changes";
16672
16745
  /**
16673
- * How every realtime LISTEN connection names itself (`application_name`,
16674
- * followed by the instance id), so an instance can count the others serving
16675
- * realtime on the same database.
16676
- */
16677
- var REALTIME_LISTENER_APPLICATION_PREFIX = "rebase-realtime:";
16678
- /**
16679
16746
  * The id of a change that names no row — a `TRUNCATE`, a key too large to
16680
16747
  * notify, a table with no key. Every list on the path refetches, and so does
16681
16748
  * every single-row subscription on it: the change may be to any row.
@@ -17037,8 +17104,16 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17037
17104
  driver;
17038
17105
  /** Unique identifier for this process instance, used to skip own notifications. */
17039
17106
  instanceId = `inst_${randomUUID().slice(0, 8)}`;
17040
- /** What this instance's LISTEN connections report in `pg_stat_activity`. */
17041
- listenerApplicationName = `${REALTIME_LISTENER_APPLICATION_PREFIX}${this.instanceId}`;
17107
+ /**
17108
+ * The name this instance's realtime connections report in
17109
+ * `pg_stat_activity` (`application_name`), each followed by what the
17110
+ * connection is for — see {@link realtimeListenerApplicationName}. Other
17111
+ * instances count these, and a WAL-streaming one reads them to tell
17112
+ * whether anybody still LISTENs on the capture triggers.
17113
+ */
17114
+ listenerInstanceName = `${REALTIME_LISTENER_APPLICATION_PREFIX}${this.instanceId}`;
17115
+ /** While the capture triggers are kept for another instance, the timer that retires them once it is gone. */
17116
+ triggerRetirementTimer;
17042
17117
  /** The LISTEN connection on {@link PG_NOTIFY_CHANNEL}, outside the Drizzle pool. */
17043
17118
  crossInstanceListener;
17044
17119
  /** Whether cross-instance broadcasting is active. */
@@ -18577,7 +18652,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
18577
18652
  SELECT count(*)::int AS n FROM pg_stat_activity
18578
18653
  WHERE datname = current_database()
18579
18654
  AND starts_with(application_name, ${REALTIME_LISTENER_APPLICATION_PREFIX})
18580
- AND application_name <> ${this.listenerApplicationName}`);
18655
+ AND NOT starts_with(application_name, ${this.listenerInstanceName})`);
18581
18656
  if (Number((result.rows?.[0])?.n ?? 0) > 0) {
18582
18657
  this.foreignInstanceSeen = true;
18583
18658
  this.warnIfMemoryBusOnMultiplePods();
@@ -19304,7 +19379,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19304
19379
  * (bypass PgBouncer — LISTEN needs a session connection).
19305
19380
  */
19306
19381
  async enableCdc(connectionString) {
19307
- await this.activateCdc(() => new CdcListener(connectionString, (events) => this.handleCdcEvents(events), () => this.resyncSubscriptions(), this.listenerApplicationName));
19382
+ await this.activateCdc(() => new CdcListener(connectionString, (events) => this.handleCdcEvents(events), () => this.resyncSubscriptions(), realtimeListenerApplicationName(this.listenerInstanceName, "cdc")));
19308
19383
  }
19309
19384
  /**
19310
19385
  * Enable change capture read from the write-ahead log instead of NOTIFY —
@@ -19325,7 +19400,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19325
19400
  onEvents: (events) => this.handleCdcEvents(events),
19326
19401
  onReconnect: () => this.resyncSubscriptions(),
19327
19402
  identityColumns: (schema, table) => identity.get(`${schema}.${table}`),
19328
- applicationName: this.listenerApplicationName
19403
+ applicationName: realtimeListenerApplicationName(this.listenerInstanceName, "wal")
19329
19404
  }));
19330
19405
  }
19331
19406
  async activateCdc(create) {
@@ -19373,8 +19448,34 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19373
19448
  this.cdcTableMap = this.buildCdcTableMap();
19374
19449
  this.junctionLinkMap = buildJunctionLinkMap(this.registry);
19375
19450
  }
19451
+ /**
19452
+ * Try `retire` every `intervalMs` until it answers true — how a
19453
+ * WAL-streaming instance takes the capture triggers off once the last
19454
+ * instance still listening on them is gone. Replaces any earlier schedule;
19455
+ * stopped with the CDC listener.
19456
+ */
19457
+ scheduleTriggerCaptureRetirement(retire, intervalMs) {
19458
+ this.cancelTriggerCaptureRetirement();
19459
+ let running = false;
19460
+ const timer = setInterval(() => {
19461
+ if (running) return;
19462
+ running = true;
19463
+ retire().then((done) => {
19464
+ if (done && this.triggerRetirementTimer === timer) this.cancelTriggerCaptureRetirement();
19465
+ }).catch((error) => this.debugLog("[CDC] Retiring the capture triggers failed; trying again later", error)).finally(() => {
19466
+ running = false;
19467
+ });
19468
+ }, intervalMs);
19469
+ unref(timer);
19470
+ this.triggerRetirementTimer = timer;
19471
+ }
19472
+ cancelTriggerCaptureRetirement() {
19473
+ if (this.triggerRetirementTimer) clearInterval(this.triggerRetirementTimer);
19474
+ this.triggerRetirementTimer = void 0;
19475
+ }
19376
19476
  /** Stop the CDC listener and clear its state. */
19377
19477
  async stopCdc() {
19478
+ this.cancelTriggerCaptureRetirement();
19378
19479
  this.cdcActive = false;
19379
19480
  if (this.cdcListener) {
19380
19481
  await this.cdcListener.stop();
@@ -19592,7 +19693,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19592
19693
  onPayload: (payload) => this.handleCrossInstanceNotification(payload),
19593
19694
  onReconnect: () => this.resyncSubscriptions(),
19594
19695
  retryInitialConnect: true,
19595
- applicationName: this.listenerApplicationName
19696
+ applicationName: realtimeListenerApplicationName(this.listenerInstanceName, "entity")
19596
19697
  });
19597
19698
  await this.crossInstanceListener.start();
19598
19699
  logger.info(`📡 [RealtimeService] Cross-instance realtime enabled (instanceId: ${this.instanceId})`);
@@ -23594,27 +23695,52 @@ async function openPostgresDriver(pgConfig, config) {
23594
23695
  });
23595
23696
  }
23596
23697
  let walActive = false;
23597
- if (cdcMode === "wal") try {
23698
+ if (cdcMode === "wal" || cdcMode === "auto") try {
23598
23699
  const blocker = await walCaptureBlocker(cdcRunSql);
23599
23700
  if (blocker) throw new Error(blocker);
23600
23701
  if (realtimeProvisions) reportUnpublishedTables(await provisionWalPublication(cdcRunSql, cdcTables));
23601
23702
  if (realtimeSubscribes) await realtimeService.enableWalCdc(directUrl, cdcTables);
23602
23703
  walActive = true;
23603
23704
  } catch (err) {
23604
- logger.warn("⚠️ [CDC] REALTIME_CDC=wal, but changes cannot be streamed from the WAL — using trigger-based capture instead.", { detail: err instanceof Error ? err.message : String(err) });
23705
+ const notice = walFallbackNotice(cdcMode);
23706
+ logger[notice.level](notice.message, { detail: err instanceof Error ? err.message : String(err) });
23605
23707
  }
23606
23708
  if (walActive) {
23607
23709
  cdcEnabled = true;
23608
23710
  if (realtimeProvisions && realtimeSubscribes) {
23711
+ const ownName = realtimeService.listenerInstanceName;
23712
+ let triggersKept = false;
23609
23713
  try {
23610
- const removed = await removeTriggerCdc(cdcRunSql);
23611
- cdcFunctionCurrent = true;
23612
- if (removed > 0) logger.info(`ℹ️ [CDC] Removed ${removed} change-capture trigger(s): this process streams changes from the WAL instead.`);
23714
+ const retirement = await retireTriggerCaptureIfUnused(cdcRunSql, ownName);
23715
+ if ("removed" in retirement) {
23716
+ cdcFunctionCurrent = true;
23717
+ if (retirement.removed > 0) logger.info(`ℹ️ [CDC] Removed ${retirement.removed} change-capture trigger(s): this process streams changes from the WAL instead.`);
23718
+ } else {
23719
+ triggersKept = true;
23720
+ logger.info("ℹ️ [CDC] Keeping the change-capture triggers: " + (retirement.consumers === void 0 ? "could not tell whether another instance still listens on them." : `${retirement.consumers} other realtime connection(s) may still listen on them.`) + " They come off once none does.");
23721
+ }
23613
23722
  } catch (err) {
23614
- logger.warn("⚠️ [CDC] Could not remove the change-capture triggers, so every write still runs one and a NOTIFY. The next boot tries again.", { detail: err instanceof Error ? err.message : String(err) });
23723
+ triggersKept = true;
23724
+ logger.warn("⚠️ [CDC] Could not remove the change-capture triggers, so every write still runs one and a NOTIFY. This process tries again.", { detail: err instanceof Error ? err.message : String(err) });
23725
+ }
23726
+ if (triggersKept) {
23727
+ try {
23728
+ await provisionTriggerCdc(cdcRunSql, cdcTables);
23729
+ cdcFunctionCurrent = true;
23730
+ } catch (err) {
23731
+ logger.warn("⚠️ [CDC] Could not bring the kept change-capture triggers up to date.", { detail: err instanceof Error ? err.message : String(err) });
23732
+ }
23733
+ realtimeService.scheduleTriggerCaptureRetirement(async () => {
23734
+ const retirement = await retireTriggerCaptureIfUnused(cdcRunSql, ownName);
23735
+ if (!("removed" in retirement)) return false;
23736
+ triggersKept = false;
23737
+ if (retirement.removed > 0) logger.info(`ℹ️ [CDC] Removed ${retirement.removed} change-capture trigger(s): no other instance listens on them any more.`);
23738
+ return true;
23739
+ }, TRIGGER_RETIREMENT_INTERVAL_MS);
23615
23740
  }
23616
23741
  provisionCdcForTables = async (tables) => {
23617
23742
  reportUnpublishedTables(await provisionWalPublication(cdcRunSql, tables));
23743
+ if (triggersKept) await provisionTriggerCdc(cdcRunSql, tables);
23618
23744
  };
23619
23745
  } else if (realtimeProvisions) {
23620
23746
  try {
@@ -23630,11 +23756,22 @@ async function openPostgresDriver(pgConfig, config) {
23630
23756
  }
23631
23757
  logger.info("📡 [CDC] Realtime source = database-level change capture (mode: wal). All writes now emit realtime events regardless of origin." + (realtimeSubscribes ? "" : " This process sets up the capture but does not consume it."));
23632
23758
  } else try {
23759
+ let listenError;
23760
+ if (realtimeSubscribes) try {
23761
+ await realtimeService.enableCdc(directUrl);
23762
+ } catch (err) {
23763
+ listenError = err;
23764
+ }
23633
23765
  if (realtimeProvisions) {
23634
- await provisionTriggerCdc(cdcRunSql, cdcTables);
23766
+ try {
23767
+ await provisionTriggerCdc(cdcRunSql, cdcTables);
23768
+ } catch (err) {
23769
+ if (realtimeSubscribes && listenError === void 0) await realtimeService.stopCdc().catch(() => void 0);
23770
+ throw err;
23771
+ }
23635
23772
  cdcFunctionCurrent = true;
23636
23773
  }
23637
- if (realtimeSubscribes) await realtimeService.enableCdc(directUrl);
23774
+ if (listenError !== void 0) throw listenError;
23638
23775
  cdcEnabled = true;
23639
23776
  if (realtimeProvisions) provisionCdcForTables = async (tables) => {
23640
23777
  await provisionTriggerCdc(cdcRunSql, tables);
@@ -23887,7 +24024,7 @@ function createPostgresBootstrapper(pgConfig) {
23887
24024
  const openIndexBuildSession = (driverResult) => async () => {
23888
24025
  const db = requireProvisioningDb(driverResult);
23889
24026
  const pool = "$client" in db ? db.$client : void 0;
23890
- const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-CcSDA7wE.js").then((n) => n.r);
24027
+ const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-ueYVUBZc.js").then((n) => n.r);
23891
24028
  const config = effectiveConfig();
23892
24029
  if (isPooledPool(pool) || config.pooled) {
23893
24030
  if (!config.directConnectionString) throw pooledWithoutDirectUrlError(DEFAULT_DATA_SOURCE_KEY);
@@ -24030,11 +24167,11 @@ function createPostgresBootstrapper(pgConfig) {
24030
24167
  unavailable: historyUnavailableReason(state, { requireTransaction: false })
24031
24168
  }) };
24032
24169
  }
24033
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-5H2bL_80.js").then((n) => n.i);
24170
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CSYhSSZD.js").then((n) => n.i);
24034
24171
  const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
24035
24172
  const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
24036
24173
  if (historyIndexes.length > 0) {
24037
- const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-CcSDA7wE.js").then((n) => n.r);
24174
+ const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-ueYVUBZc.js").then((n) => n.r);
24038
24175
  const indexOptions = {
24039
24176
  log: (message) => logger.info(`[history] ${message}`),
24040
24177
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
@@ -24090,9 +24227,9 @@ function createPostgresBootstrapper(pgConfig) {
24090
24227
  * proved it can bootstrap with.
24091
24228
  */
24092
24229
  async ensureTableSchema(tables, driverResult, log) {
24093
- const { ensureTables } = await import("./ensure-tables-Bvm-F2wW.js").then((n) => n.n);
24230
+ const { ensureTables } = await import("./ensure-tables-B3Kh2RwT.js").then((n) => n.n);
24094
24231
  const queryable = provisioningQueryable(driverResult);
24095
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-5H2bL_80.js").then((n) => n.i);
24232
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CSYhSSZD.js").then((n) => n.i);
24096
24233
  const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
24097
24234
  const plan = await ensureTables(queryable, tables, log, {
24098
24235
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
@@ -24104,7 +24241,7 @@ function createPostgresBootstrapper(pgConfig) {
24104
24241
  pendingIndexBuild?.cancel();
24105
24242
  pendingIndexBuild = void 0;
24106
24243
  if (!provisionOnly && plan.deferredIndexes.length > 0) {
24107
- const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-CcSDA7wE.js").then((n) => n.r);
24244
+ const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-ueYVUBZc.js").then((n) => n.r);
24108
24245
  logger.info(`[schema] ${plan.deferredIndexes.length} index(es) are missing, or were left INVALID, on tables that already exist. They are built in the background once the server is serving, one at a time, without blocking reads or writes.`);
24109
24246
  pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
24110
24247
  log: (message) => logger.info(`[schema] ${message}`),
@@ -24144,7 +24281,7 @@ function createPostgresBootstrapper(pgConfig) {
24144
24281
  await provisionRlsRuntime(driverResult);
24145
24282
  },
24146
24283
  async ensureTablePolicies(tables, driverResult, log) {
24147
- const { ensureTablePolicies, describeRulesDropped } = await import("./ensure-policies-rRmXb5bt.js");
24284
+ const { ensureTablePolicies, describeRulesDropped } = await import("./ensure-policies-13mHWjBs.js");
24148
24285
  const queryable = provisioningQueryable(driverResult);
24149
24286
  const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
24150
24287
  if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
@@ -24280,7 +24417,7 @@ function createPostgresBootstrapper(pgConfig) {
24280
24417
  return driverResult.internals.driver.admin;
24281
24418
  },
24282
24419
  async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
24283
- const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-BevXvwfo.js").then((n) => n.c);
24420
+ const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-CSVNOYHC.js").then((n) => n.c);
24284
24421
  if (!isSocketRealtimeService(realtimeService)) throw new Error(`The realtime service handed to the Postgres socket cannot serve it — it has no ${socketRealtimeMissing(realtimeService).join(", ")}. Every socket would fail on its first frame.`);
24285
24422
  const realtimeConfig = effectiveConfig().realtime;
24286
24423
  const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
@@ -24441,4 +24578,4 @@ async function openRebase(options) {
24441
24578
  //#endregion
24442
24579
  export { PostgresBackendDriver as $, reapSilentSockets as A, passwordResetTokens as B, PostgresChannelBus as C, frameByteLength as D, MemoryChannelBus as E, magicLinkTokensRelations as F, refreshTokensRelations as G, recoveryCodes as H, mfaChallenges as I, users as J, userIdentities as K, mfaChallengesRelations as L, appConfig as M, createAuthSchema as N, isChannelBusInstance$1 as O, magicLinkTokens as P, CONNECTION_OWNER as Q, mfaFactors as R, PG_NOTIFY_MAX_PAYLOAD_BYTES as S, parseChannelBusPayload as T, recoveryCodesRelations as U, passwordResetTokensRelations as V, refreshTokens as W, usersSchema as X, usersRelations as Y, AuthenticatedPostgresBackendDriver as Z, refetchConcurrencyFor as _, openPostgresDriver as a, SQL_RESULT_BYTE_BUDGET as at, CHANNEL_BUS_NOTIFY_CHANNEL as b, PostgresTableRegistry as c, resolveNestedPath as ct, PostgresRealtimeProvider as d, PostgresConditionBuilder as dt, RoleSwitchUnavailableError as et, RealtimeService as f, configureUnknownFilterFields as ft, parseRealtimeTuning as g, listedColumnKeys as gt, parseMaxSubscriptionsPerSocket as h, joinColumn as ht, isScaffoldedLocalDatabase as i, sqlRoleRanAs as it, terminateIfBacklogged as j, budgetSendBuffers as k, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as l, assertReadRequestReadable as lt, parseMaxSocketsPerUser as m, getUnknownFilterFieldsMode as mt, createPostgresBootstrapper as n, effectiveSqlRole as nt, postgresDriverConfigFromEnv as o, SqlResultTooLargeError as ot, packEntityChanges as p, escapeLikePattern as pt, userIdentitiesRelations as q, describeSchemaDriftCause as r, isRoleSwitchingOptedOut as rt, resolveSourceUrls as s, isNestedPath as st, openRebase as t, branchParentDatabase as tt, DEFAULT_RECOUNT_MIN_ROWS as u, DrizzleConditionBuilder as ut, createChannelBus as v, parseChannelBusFrame as w, DEFAULT_BATCH_WINDOW_MS as x, resolveChannelBusSetting as y, mfaFactorsRelations as z };
24443
24580
 
24444
- //# sourceMappingURL=open-rebase-4kisUF_k.js.map
24581
+ //# sourceMappingURL=open-rebase-B2mAA7UE.js.map