@rebasepro/server-postgres 0.24.0 → 0.24.1-canary.g56af4a4

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 (162) hide show
  1. package/dist/{BranchService-BRt78gfa.js → BranchService-Bsn2wfaj.js} +3 -2
  2. package/dist/{BranchService-BRt78gfa.js.map → BranchService-Bsn2wfaj.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +83 -2
  4. package/dist/auth/ensure-tables.d.ts +12 -0
  5. package/dist/auth/services.d.ts +6 -0
  6. package/dist/backup/backup-cli.d.ts +14 -0
  7. package/dist/backup/backup-service.d.ts +2 -2
  8. package/dist/backup/pg-binary.d.ts +5 -0
  9. package/dist/{backup-cli-DW5p9_zv.js → backup-cli-aUfRv16h.js} +37 -29
  10. package/dist/backup-cli-aUfRv16h.js.map +1 -0
  11. package/dist/{backup-service-EwcDVG-8.js → backup-service-BTBB7RXn.js} +55 -21
  12. package/dist/backup-service-BTBB7RXn.js.map +1 -0
  13. package/dist/boot-ddl-DVpsFN6r.js +105 -0
  14. package/dist/boot-ddl-DVpsFN6r.js.map +1 -0
  15. package/dist/cli-errors-CaI4ntyD.js +1919 -0
  16. package/dist/cli-errors-CaI4ntyD.js.map +1 -0
  17. package/dist/cli-errors.d.ts +51 -5
  18. package/dist/{cli-flags-BglvpjHv.js → cli-flags-B-Dawocl.js} +5 -2
  19. package/dist/cli-flags-B-Dawocl.js.map +1 -0
  20. package/dist/cli-helpers.d.ts +40 -0
  21. package/dist/cli-output.d.ts +16 -28
  22. package/dist/cli-push.d.ts +87 -0
  23. package/dist/cli.js +563 -182
  24. package/dist/cli.js.map +1 -1
  25. package/dist/{column-plan-helpers-1-LQD0yI.js → column-plan-helpers-drZIsSNf.js} +10 -4
  26. package/dist/{column-plan-helpers-1-LQD0yI.js.map → column-plan-helpers-drZIsSNf.js.map} +1 -1
  27. package/dist/{databasePoolManager-Bj5FbeAs.js → connection-BPoNILnD.js} +19 -110
  28. package/dist/connection-BPoNILnD.js.map +1 -0
  29. package/dist/connection.d.ts +9 -1
  30. package/dist/databasePoolManager-BkEy2w18.js +119 -0
  31. package/dist/databasePoolManager-BkEy2w18.js.map +1 -0
  32. package/dist/{ensure-collection-tables-kkkHk8oo.js → deferred-index-build-DP1_SNFo.js} +484 -346
  33. package/dist/deferred-index-build-DP1_SNFo.js.map +1 -0
  34. package/dist/{doctor-C-sYWbmt.js → doctor-C4WiftHm.js} +63 -52
  35. package/dist/doctor-C4WiftHm.js.map +1 -0
  36. package/dist/ensure-collection-policies-CXpbeNag.js +541 -0
  37. package/dist/ensure-collection-policies-CXpbeNag.js.map +1 -0
  38. package/dist/ensure-collection-tables-BhsU6qUE.js +532 -0
  39. package/dist/ensure-collection-tables-BhsU6qUE.js.map +1 -0
  40. package/dist/{ensure-tables-BmI_tRxc.js → ensure-tables-CHsgyLqg.js} +172 -76
  41. package/dist/ensure-tables-CHsgyLqg.js.map +1 -0
  42. package/dist/enum-labels-kept-D8fI1MoX.js +56 -0
  43. package/dist/enum-labels-kept-D8fI1MoX.js.map +1 -0
  44. package/dist/generate-drizzle-schema-Bz52jH2h.js +57 -0
  45. package/dist/generate-drizzle-schema-Bz52jH2h.js.map +1 -0
  46. package/dist/{generate-drizzle-schema-logic-sSFDp6LR.js → generate-drizzle-schema-logic-B74WN37S.js} +5 -5
  47. package/dist/generate-drizzle-schema-logic-B74WN37S.js.map +1 -0
  48. package/dist/generate-files-CdEckX6c.js +199 -0
  49. package/dist/generate-files-CdEckX6c.js.map +1 -0
  50. package/dist/{generate-postgres-ddl-logic-BJsLaVNX.js → generate-postgres-ddl-logic-B64O2oZF.js} +3 -3
  51. package/dist/{generate-postgres-ddl-logic-BJsLaVNX.js.map → generate-postgres-ddl-logic-B64O2oZF.js.map} +1 -1
  52. package/dist/generated-sql.d.ts +8 -2
  53. package/dist/history/HistoryService.d.ts +38 -6
  54. package/dist/history/ensure-history-table.d.ts +42 -4
  55. package/dist/index.es.js +2922 -7475
  56. package/dist/index.es.js.map +1 -1
  57. package/dist/{introspect-db-logic-kCETE8TY.js → introspect-db-logic-C-Di8dA9.js} +44 -6
  58. package/dist/introspect-db-logic-C-Di8dA9.js.map +1 -0
  59. package/dist/{introspect-db-queries-C_Q5VgQw.js → introspect-db-queries-D6kAqReI.js} +23 -1
  60. package/dist/introspect-db-queries-D6kAqReI.js.map +1 -0
  61. package/dist/pg-error-utils-vJezlXdI.js +388 -0
  62. package/dist/pg-error-utils-vJezlXdI.js.map +1 -0
  63. package/dist/{plan-schema-DU9exq6C.js → plan-schema-B1YF_tYq.js} +151 -41
  64. package/dist/plan-schema-B1YF_tYq.js.map +1 -0
  65. package/dist/{policy-drift-B-J2hhm0.js → policy-drift-Dm8i-s1J.js} +23 -6
  66. package/dist/policy-drift-Dm8i-s1J.js.map +1 -0
  67. package/dist/push-index-prebuild-Db4AQF4i.js +45 -0
  68. package/dist/push-index-prebuild-Db4AQF4i.js.map +1 -0
  69. package/dist/push-legacy-renames-BK6ilQq2.js +34 -0
  70. package/dist/push-legacy-renames-BK6ilQq2.js.map +1 -0
  71. package/dist/{render-ddl-Ds2t_d9V.js → render-ddl-CtC3y9Ol.js} +8 -4
  72. package/dist/render-ddl-CtC3y9Ol.js.map +1 -0
  73. package/dist/{rls-bootstrap-sql-_KNnjanK.js → rls-bootstrap-sql-RQUljnJ1.js} +125 -1270
  74. package/dist/rls-bootstrap-sql-RQUljnJ1.js.map +1 -0
  75. package/dist/{rls-enforcement-CfXOJJaW.js → rls-enforcement-DvzqlaL1.js} +129 -17
  76. package/dist/rls-enforcement-DvzqlaL1.js.map +1 -0
  77. package/dist/schema/auth-schema.d.ts +2 -2
  78. package/dist/schema/boot-ddl.d.ts +47 -0
  79. package/dist/schema/collection-index.d.ts +45 -0
  80. package/dist/schema/column-plan-helpers.d.ts +5 -0
  81. package/dist/schema/deferred-index-build.d.ts +131 -0
  82. package/dist/schema/destructive-sql.d.ts +7 -0
  83. package/dist/schema/doctor-cli.js +110 -6
  84. package/dist/schema/doctor-cli.js.map +1 -1
  85. package/dist/schema/doctor-search-scale.d.ts +45 -0
  86. package/dist/schema/doctor.d.ts +20 -1
  87. package/dist/schema/ensure-collection-policies.d.ts +73 -35
  88. package/dist/schema/ensure-collection-tables.d.ts +56 -3
  89. package/dist/schema/enum-labels-kept.d.ts +26 -0
  90. package/dist/schema/generate-drizzle-schema.js +1 -1
  91. package/dist/schema/generate-files.d.ts +44 -0
  92. package/dist/schema/generate-next-step.d.ts +0 -13
  93. package/dist/schema/generate-postgres-ddl.js +10 -81
  94. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  95. package/dist/schema/introspect-db-logic.d.ts +12 -0
  96. package/dist/schema/introspect-db-queries.d.ts +11 -1
  97. package/dist/schema/introspect-db-structure.d.ts +10 -0
  98. package/dist/schema/introspect-db.js +4 -5
  99. package/dist/schema/introspect-db.js.map +1 -1
  100. package/dist/schema/migration-post-process.d.ts +34 -0
  101. package/dist/schema/plan/diff-plan.d.ts +126 -0
  102. package/dist/schema/plan/types.d.ts +8 -0
  103. package/dist/schema/push-index-prebuild.d.ts +25 -0
  104. package/dist/schema/push-legacy-renames.d.ts +20 -0
  105. package/dist/schema/rls-bootstrap-sql.d.ts +15 -0
  106. package/dist/security/rls-enforcement.d.ts +32 -4
  107. package/dist/services/FetchService.d.ts +58 -8
  108. package/dist/services/PersistService.d.ts +15 -0
  109. package/dist/services/RelationService.d.ts +88 -3
  110. package/dist/services/cdc/CdcListener.d.ts +17 -6
  111. package/dist/services/cdc/trigger-cdc.d.ts +151 -27
  112. package/dist/services/channel-history.d.ts +15 -4
  113. package/dist/services/collection-helpers.d.ts +15 -0
  114. package/dist/services/field-viewer.d.ts +15 -1
  115. package/dist/services/pg-notify-listener.d.ts +7 -0
  116. package/dist/services/realtimeService.d.ts +314 -14
  117. package/dist/services/row-pipeline.d.ts +16 -9
  118. package/dist/services/socket-liveness.d.ts +42 -2
  119. package/dist/services/sql-script.d.ts +207 -3
  120. package/dist/services/vector-iterative-scan.d.ts +40 -0
  121. package/dist/services/write-depth.d.ts +6 -0
  122. package/dist/services/write-transaction-scope.d.ts +9 -0
  123. package/dist/socket-liveness-D3UD5_BW.js +7570 -0
  124. package/dist/socket-liveness-D3UD5_BW.js.map +1 -0
  125. package/dist/socket-opt-ins.d.ts +64 -0
  126. package/dist/source-DBDbBTL4.js +811 -0
  127. package/dist/source-DBDbBTL4.js.map +1 -0
  128. package/dist/tsx-loader.d.ts +14 -0
  129. package/dist/utils/drizzle-conditions.d.ts +21 -1
  130. package/dist/utils/error-cause.d.ts +7 -0
  131. package/dist/utils/pg-error-utils.d.ts +2 -4
  132. package/dist/utils/result-rows.d.ts +10 -0
  133. package/dist/websocket.d.ts +13 -0
  134. package/package.json +7 -7
  135. package/dist/backup-cli-DW5p9_zv.js.map +0 -1
  136. package/dist/backup-service-EwcDVG-8.js.map +0 -1
  137. package/dist/cli-errors-DsA-K9uP.js +0 -893
  138. package/dist/cli-errors-DsA-K9uP.js.map +0 -1
  139. package/dist/cli-flags-BglvpjHv.js.map +0 -1
  140. package/dist/cli-output-CNdMql-L.js +0 -47
  141. package/dist/cli-output-CNdMql-L.js.map +0 -1
  142. package/dist/collection-index-DdnsxiJ_.js +0 -286
  143. package/dist/collection-index-DdnsxiJ_.js.map +0 -1
  144. package/dist/databasePoolManager-Bj5FbeAs.js.map +0 -1
  145. package/dist/doctor-C-sYWbmt.js.map +0 -1
  146. package/dist/ensure-collection-policies-B1ureSIV.js +0 -160
  147. package/dist/ensure-collection-policies-B1ureSIV.js.map +0 -1
  148. package/dist/ensure-collection-tables-kkkHk8oo.js.map +0 -1
  149. package/dist/ensure-tables-BmI_tRxc.js.map +0 -1
  150. package/dist/generate-drizzle-schema-93M0lUxK.js +0 -123
  151. package/dist/generate-drizzle-schema-93M0lUxK.js.map +0 -1
  152. package/dist/generate-drizzle-schema-logic-sSFDp6LR.js.map +0 -1
  153. package/dist/introspect-db-logic-kCETE8TY.js.map +0 -1
  154. package/dist/introspect-db-queries-C_Q5VgQw.js.map +0 -1
  155. package/dist/plan-schema-DU9exq6C.js.map +0 -1
  156. package/dist/policy-drift-B-J2hhm0.js.map +0 -1
  157. package/dist/render-ddl-Ds2t_d9V.js.map +0 -1
  158. package/dist/rls-bootstrap-sql-_KNnjanK.js.map +0 -1
  159. package/dist/rls-enforcement-CfXOJJaW.js.map +0 -1
  160. package/dist/source-Br7L7GOI.js +0 -410
  161. package/dist/source-Br7L7GOI.js.map +0 -1
  162. package/dist/utils/sql-redaction.d.ts +0 -21
@@ -1,9 +1,10 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { r as __exportAll } from "./__vite-browser-external-BnuHet1e.js";
4
- import { A as resolveLocalBin, B as forLibpq, z as execa } from "./rls-bootstrap-sql-_KNnjanK.js";
5
- import fs from "fs";
4
+ import { F as resolveLocalBin } from "./cli-errors-CaI4ntyD.js";
5
+ import { o as execa, s as forLibpq } from "./rls-bootstrap-sql-RQUljnJ1.js";
6
6
  import path from "path";
7
+ import fs from "fs";
7
8
  import os from "os";
8
9
  //#region src/backup/pg-tools.ts
9
10
  /**
@@ -320,6 +321,29 @@ function selectBackupsToPrune(backups, options) {
320
321
  return toDelete.map((b) => b.key);
321
322
  }
322
323
  //#endregion
324
+ //#region src/backup/pg-binary.ts
325
+ /**
326
+ * Where the PostgreSQL client tools are, without spawning them.
327
+ *
328
+ * Kept apart from `backup-service.ts`, which pulls in `execa` (ESM-only), so
329
+ * `createBackupCron` can check for the tools when it is registered.
330
+ */
331
+ var OVERRIDE_VARIABLE = {
332
+ pg_dump: "PG_DUMP_PATH",
333
+ pg_restore: "PG_RESTORE_PATH",
334
+ pg_dumpall: "PG_DUMPALL_PATH"
335
+ };
336
+ /** The variable that points at `tool` when it is not on the PATH. */
337
+ function pgToolVariable(tool) {
338
+ return OVERRIDE_VARIABLE[tool];
339
+ }
340
+ /** Locate `pg_dump` / `pg_restore` / `pg_dumpall`, honouring an env override. */
341
+ function resolvePgBinary(tool, env = process.env) {
342
+ const override = env[OVERRIDE_VARIABLE[tool]];
343
+ if (override && fs.existsSync(override)) return override;
344
+ return resolveLocalBin(tool);
345
+ }
346
+ //#endregion
323
347
  //#region src/backup/backup-logic.ts
324
348
  /**
325
349
  * Pure-ish orchestration for the backup/restore paths, kept free of `execa`
@@ -438,12 +462,6 @@ var BackupToolError = class extends Error {
438
462
  this.name = "BackupToolError";
439
463
  }
440
464
  };
441
- /** Locate `pg_dump` / `pg_restore` / `pg_dumpall`, honouring an env override. */
442
- function resolvePgBinary(tool, env = process.env) {
443
- const overrideVar = tool === "pg_dump" ? env.PG_DUMP_PATH : tool === "pg_restore" ? env.PG_RESTORE_PATH : env.PG_DUMPALL_PATH;
444
- if (overrideVar && fs.existsSync(overrideVar)) return overrideVar;
445
- return resolveLocalBin(tool);
446
- }
447
465
  /** Run `<bin> --version` and extract the major version. */
448
466
  async function detectToolMajor(bin) {
449
467
  try {
@@ -655,8 +673,7 @@ async function ensureDatabaseExists(adminConnectionString, dbName) {
655
673
  async function uploadBackup(storage, localFile, dest) {
656
674
  const fileName = path.basename(localFile);
657
675
  const key = joinStorageKey(dest.prefix, fileName);
658
- const buffer = fs.readFileSync(localFile);
659
- const file = new File([buffer], fileName, { type: "application/octet-stream" });
676
+ const file = new File([await fs.openAsBlob(localFile)], fileName, { type: "application/octet-stream" });
660
677
  return {
661
678
  key,
662
679
  storageUrl: (await storage.putObject({
@@ -664,8 +681,23 @@ async function uploadBackup(storage, localFile, dest) {
664
681
  key,
665
682
  bucket: dest.bucket,
666
683
  metadata: { "rebase-backup": "1" }
667
- })).storageUrl
684
+ }, { uploadLimits: false })).storageUrl
685
+ };
686
+ }
687
+ /** Stats in flight at once while listing a local backup folder. */
688
+ var LOCAL_STAT_CONCURRENCY = 32;
689
+ /** `fn` over `items`, at most `limit` at a time; results in input order. */
690
+ async function mapBounded(items, limit, fn) {
691
+ const results = new Array(items.length);
692
+ let next = 0;
693
+ const worker = async () => {
694
+ while (next < items.length) {
695
+ const i = next++;
696
+ results[i] = await fn(items[i]);
697
+ }
668
698
  };
699
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
700
+ return results;
669
701
  }
670
702
  /**
671
703
  * List existing backups at a destination. For local destinations reads the
@@ -673,15 +705,17 @@ async function uploadBackup(storage, localFile, dest) {
673
705
  */
674
706
  async function listBackups(dest, storage) {
675
707
  if (dest.kind === "local") {
676
- if (!fs.existsSync(dest.path)) return [];
677
- const dir = fs.statSync(dest.path).isDirectory() ? dest.path : path.dirname(dest.path);
678
- return fs.readdirSync(dir).filter((f) => f.endsWith(".dump")).map((f) => {
679
- const full = path.join(dir, f);
680
- const stats = fs.statSync(full);
708
+ const stat = await fs.promises.stat(dest.path).catch(() => null);
709
+ if (!stat) return [];
710
+ const dir = stat.isDirectory() ? dest.path : path.dirname(dest.path);
711
+ const dumps = (await fs.promises.readdir(dir)).filter((f) => f.endsWith(".dump"));
712
+ const stats = await mapBounded(dumps, LOCAL_STAT_CONCURRENCY, (f) => fs.promises.stat(path.join(dir, f)));
713
+ return dumps.map((f, i) => {
714
+ const createdAt = parseBackupTimestamp(f) ?? stats[i].mtime;
681
715
  return {
682
- key: full,
683
- createdAt: parseBackupTimestamp(f) ?? stats.mtime,
684
- sizeBytes: stats.size
716
+ key: path.join(dir, f),
717
+ createdAt,
718
+ sizeBytes: stats[i].size
685
719
  };
686
720
  }).sort((a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0));
687
721
  }
@@ -708,6 +742,6 @@ async function pruneBackups(dest, options, storage) {
708
742
  return toDelete;
709
743
  }
710
744
  //#endregion
711
- export { parsePgToolMajor as A, checkToolServerCompatibility as C, parseBackupDestination as D, joinStorageKey as E, serverVersionNumToMajor as M, splitGlobalsStatements as N, parseBackupTimestamp as O, withDatabaseName as P, buildRowSecurityPgOptions as S, globalsFileForDump as T, buildBackupFilename as _, detectToolMajor as a, buildPgRestoreArgs as b, getServerVersionMajor as c, pruneBackups as d, resolvePgBinary as f, selectBackupsToPrune as g, validateDump as h, createDump as i, resolveConnectionString as j, parseDbNameFromUrl as k, listBackups as l, uploadBackup as m, applyGlobals as n, discardPartialDump as o, restoreDump as p, backup_service_exports as r, ensureDatabaseExists as s, BackupToolError as t, preflight as u, buildPgDumpArgs as v, diagnoseRowSecurityDumpFailure as w, buildPgRestoreListArgs as x, buildPgDumpallGlobalsArgs as y };
745
+ export { parseDbNameFromUrl as A, buildRowSecurityPgOptions as C, joinStorageKey as D, globalsFileForDump as E, withDatabaseName as F, resolveConnectionString as M, serverVersionNumToMajor as N, parseBackupDestination as O, splitGlobalsStatements as P, buildPgRestoreListArgs as S, diagnoseRowSecurityDumpFailure as T, selectBackupsToPrune as _, detectToolMajor as a, buildPgDumpallGlobalsArgs as b, getServerVersionMajor as c, pruneBackups as d, restoreDump as f, resolvePgBinary as g, pgToolVariable as h, createDump as i, parsePgToolMajor as j, parseBackupTimestamp as k, listBackups as l, validateDump as m, applyGlobals as n, discardPartialDump as o, uploadBackup as p, backup_service_exports as r, ensureDatabaseExists as s, BackupToolError as t, preflight as u, buildBackupFilename as v, checkToolServerCompatibility as w, buildPgRestoreArgs as x, buildPgDumpArgs as y };
712
746
 
713
- //# sourceMappingURL=backup-service-EwcDVG-8.js.map
747
+ //# sourceMappingURL=backup-service-BTBB7RXn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backup-service-BTBB7RXn.js","names":[],"sources":["../src/backup/pg-tools.ts","../src/backup/retention.ts","../src/backup/pg-binary.ts","../src/backup/backup-logic.ts","../src/backup/backup-service.ts"],"sourcesContent":["/**\n * Pure helpers for the backup/restore commands.\n *\n * Everything in this file is side-effect free so it can be unit-tested\n * without a live Postgres server, matching the constraint that CI must\n * not require a database.\n */\n\nimport { forLibpq } from \"../utils/connection-string\";\n\n/**\n * A parsed backup destination. `--out` (and the scheduled-backup config)\n * accepts either a local filesystem path or an object-storage URL.\n */\nexport type BackupDestination =\n | { kind: \"local\"; path: string }\n | { kind: \"s3\"; bucket: string; prefix: string }\n | { kind: \"gcs\"; bucket: string; prefix: string };\n\n/**\n * Extract the database name from a Postgres connection string.\n * Returns `null` when the URL has no database path (e.g. bare host).\n */\nexport function parseDbNameFromUrl(connectionString: string): string | null {\n try {\n const parsed = new URL(connectionString);\n const name = parsed.pathname.replace(/^\\//, \"\").trim();\n return name.length > 0 ? name : null;\n } catch {\n // Fall back to a permissive regex for non-URL DSNs.\n const match = connectionString.match(/\\/([^/?]+)(\\?|$)/);\n return match && match[1] ? match[1] : null;\n }\n}\n\n/**\n * Swap the database name in a connection string, preserving credentials,\n * host, port and query params. Used by `--target-db` / `--create-db` so a\n * restore can target a fresh database instead of clobbering the live one.\n */\nexport function withDatabaseName(connectionString: string, dbName: string): string {\n try {\n const parsed = new URL(connectionString);\n parsed.pathname = `/${dbName}`;\n return parsed.toString();\n } catch {\n return connectionString.replace(/\\/([^/?]+)(\\?|$)/, `/${dbName}$2`);\n }\n}\n\n/**\n * Parse the major version out of `pg_dump --version` / `pg_restore --version`\n * output, e.g. `\"pg_dump (PostgreSQL) 16.2\"` → `16`. Handles the pre-10\n * `9.6.x` scheme (returns `9`) and beta strings like `\"17beta1\"`.\n */\nexport function parsePgToolMajor(versionOutput: string): number | null {\n const match = versionOutput.match(/(\\d+)(?:\\.(\\d+))?/);\n if (!match) return null;\n const major = Number(match[1]);\n if (!Number.isFinite(major)) return null;\n // Postgres 9.x used the first two numbers as the major (9.6, 9.4…).\n if (major === 9 && match[2] !== undefined) {\n return 9;\n }\n return major;\n}\n\n/**\n * Convert `SELECT current_setting('server_version_num')` (e.g. `160002`)\n * into a major version (`16`). Also accepts pre-10 encodings like `90603`\n * → `9`.\n */\nexport function serverVersionNumToMajor(versionNum: number | string): number | null {\n const num = typeof versionNum === \"string\" ? Number(versionNum) : versionNum;\n if (!Number.isFinite(num) || num <= 0) return null;\n if (num < 100000) {\n // 9.x scheme: 90603 = 9.6.3\n return Math.floor(num / 10000);\n }\n return Math.floor(num / 10000);\n}\n\nexport interface VersionCompatibility {\n compatible: boolean;\n reason?: string;\n}\n\n/**\n * pg_dump / pg_restore must be **at least** as new as the server they talk\n * to. A newer client against an older server is supported; an older client\n * against a newer server is not and produces corrupt or rejected output.\n */\nexport function checkToolServerCompatibility(\n toolMajor: number | null,\n serverMajor: number | null\n): VersionCompatibility {\n if (toolMajor === null) {\n return { compatible: false, reason: \"Could not determine the client tool version.\" };\n }\n if (serverMajor === null) {\n return { compatible: false, reason: \"Could not determine the Postgres server version.\" };\n }\n if (toolMajor < serverMajor) {\n return {\n compatible: false,\n reason:\n `Client tool is Postgres ${toolMajor} but the server is Postgres ${serverMajor}. ` +\n `pg_dump/pg_restore must be the same major version as the server or newer. ` +\n `Install Postgres ${serverMajor} client tools.`\n };\n }\n return { compatible: true };\n}\n\n/**\n * Build a deterministic, sortable backup file name:\n * `rebase-<db>-<YYYYMMDD>T<HHMMSS>Z.dump`\n *\n * The UTC timestamp is embedded so retention pruning can recover the\n * creation time from the object key alone, without extra metadata.\n */\nexport function buildBackupFilename(dbName: string, date: Date = new Date()): string {\n const iso = date.toISOString(); // 2026-07-14T09:12:03.123Z\n const stamp = iso.replace(/\\.\\d+Z$/, \"Z\").replace(/[-:]/g, \"\");\n const safeDb = dbName.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n return `rebase-${safeDb}-${stamp}.dump`;\n}\n\n/**\n * Recover the creation timestamp encoded in a backup file name by\n * {@link buildBackupFilename}. Returns `null` for names that don't match,\n * so foreign objects in a shared prefix are never pruned.\n */\nexport function parseBackupTimestamp(fileName: string): Date | null {\n const base = fileName.split(\"/\").pop() ?? fileName;\n const match = base.match(/-(\\d{8})T(\\d{6})Z\\.dump$/);\n if (!match) return null;\n const [, ymd, hms] = match;\n const iso =\n `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}` +\n `T${hms.slice(0, 2)}:${hms.slice(2, 4)}:${hms.slice(4, 6)}Z`;\n const date = new Date(iso);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/**\n * Parse a destination string into a structured {@link BackupDestination}.\n * `s3://bucket/prefix` and `gs://bucket/prefix` map to object storage;\n * anything else is treated as a local path.\n */\nexport function parseBackupDestination(out: string): BackupDestination {\n const s3 = out.match(/^s3:\\/\\/([^/]+)\\/?(.*)$/);\n if (s3) {\n return { kind: \"s3\", bucket: s3[1], prefix: stripTrailingSlash(s3[2]) };\n }\n const gcs = out.match(/^gs:\\/\\/([^/]+)\\/?(.*)$/);\n if (gcs) {\n return { kind: \"gcs\", bucket: gcs[1], prefix: stripTrailingSlash(gcs[2]) };\n }\n return { kind: \"local\", path: out };\n}\n\nfunction stripTrailingSlash(s: string): string {\n return s.replace(/\\/+$/, \"\");\n}\n\n/**\n * Join a storage prefix and a file name without producing a leading or\n * doubled slash.\n */\nexport function joinStorageKey(prefix: string, fileName: string): string {\n const clean = prefix.replace(/^\\/+|\\/+$/g, \"\");\n return clean.length > 0 ? `${clean}/${fileName}` : fileName;\n}\n\n/**\n * The identity `pg_dump` reads rows as, when row security is left on.\n *\n * Not optional, and that is the whole design. `pg_dump --enable-row-security`\n * on its own is the dangerous command in this file: it turns the \"query would\n * be affected by row-level security policy\" *error* into a dump that exits 0\n * and is silently missing every row the dumping role's policies exclude. A\n * backup that looks fine and restores most of your data is worse than one that\n * refused to run.\n *\n * So the flag is unreachable without a subject to evaluate the policies\n * against. Rebase's generated policies read `app.uid` and `app.user_roles`;\n * supplying an admin role satisfies the `admin_full_access` rule and the dump\n * sees everything that rule sees.\n */\nexport interface RowSecurityIdentity {\n /** Written to `app.uid`. Any non-empty value — it is only an audit trail. */\n uid: string;\n /** Written to `app.user_roles`. Must include a role the policies admit. */\n roles: string[];\n}\n\n/**\n * `PGOPTIONS` carrying an identity, for a libpq tool that has no other way to\n * set a GUC.\n *\n * A backslash escape rather than quoting, which is what libpq's `-c` parsing\n * takes: a space inside a value ends the option otherwise, so a role list is\n * comma-joined and never spaced.\n */\nexport function buildRowSecurityPgOptions(identity: RowSecurityIdentity): string {\n const escape = (value: string) => value.replace(/([\\\\ ])/g, \"\\\\$1\");\n return [\n `-c app.uid=${escape(identity.uid)}`,\n `-c app.user_id=${escape(identity.uid)}`,\n `-c app.user_roles=${escape(identity.roles.join(\",\"))}`\n ].join(\" \");\n}\n\n/**\n * Assemble the `pg_dump` argument vector. Uses the custom format (`-Fc`),\n * which is compressed and restorable selectively via `pg_restore`.\n */\nexport function buildPgDumpArgs(opts: {\n connectionString: string;\n outFile: string;\n /** Extra schemas/tables to exclude, e.g. Atlas revision tables. */\n excludeSchemas?: string[];\n /** Number of parallel jobs (directory format only; ignored for -Fc). */\n noOwner?: boolean;\n /**\n * Dump with row security on, as this identity. Omit — which is the default\n * — and `pg_dump` errors rather than skipping rows it cannot see.\n */\n rowSecurity?: RowSecurityIdentity;\n}): string[] {\n const args = [\"--format=custom\", \"--no-password\", `--file=${opts.outFile}`];\n if (opts.noOwner) {\n args.push(\"--no-owner\");\n }\n if (opts.rowSecurity) {\n args.push(\"--enable-row-security\");\n }\n for (const schema of opts.excludeSchemas ?? []) {\n args.push(`--exclude-schema=${schema}`);\n }\n args.push(forLibpq(opts.connectionString));\n return args;\n}\n\n/**\n * Whether a `pg_dump` failure is the row-security one, and what to do about it.\n *\n * The error text names the table and nothing else, so the first read of it is\n * \"why would a backup be affected by RLS at all?\" — the answer being that the\n * dumping role is not the tables' owner and has no `BYPASSRLS`, which is the\n * normal state of the `postgres` user on Cloud SQL, RDS and every other managed\n * Postgres. Nothing about that is visible from the message.\n *\n * Returns `null` for any other failure, so the caller reports it unchanged.\n */\nexport function diagnoseRowSecurityDumpFailure(error: unknown): string | null {\n const text = [\n (error as { stderr?: unknown })?.stderr,\n (error as { message?: unknown })?.message\n ].map(part => (typeof part === \"string\" ? part : \"\")).join(\"\\n\");\n\n if (!/row-level security policy/i.test(text)) return null;\n\n const table = text.match(/for table \"([^\"]+)\"/)?.[1];\n\n return [\n `pg_dump cannot read ${table ? `\"${table}\"` : \"one of the tables\"} because row-level security applies to it.`,\n \"\",\n \" The dumping role is neither the table's owner nor `BYPASSRLS`, which is the normal\",\n \" state of the `postgres` user on Cloud SQL, RDS and other managed Postgres — there is\",\n \" no superuser to hand out.\",\n \"\",\n \" Two ways out:\",\n \"\",\n \" • Grant the dumping role BYPASSRLS, or make it the owner, and run this again. The\",\n \" dump then contains every row, which is what a backup should mean.\",\n \"\",\n \" • Re-run with --enable-row-security to dump as an admin subject instead. Rebase\",\n \" sets `app.uid`/`app.user_roles` so the generated `admin_full_access` policy\",\n \" admits the dump. Read the warning it prints: the result contains exactly the\",\n \" rows those policies admit, and any table whose policies do not include an\",\n \" admin rule comes out short — with no error.\",\n \"\",\n \" Do not reach for a bare `pg_dump --enable-row-security` by hand. Without the\",\n \" settings above it succeeds and silently omits rows.\"\n ].join(\"\\n\");\n}\n\n/**\n * Assemble the `pg_restore` argument vector for a custom-format dump.\n */\nexport function buildPgRestoreArgs(opts: {\n connectionString: string;\n inputFile: string;\n /** Drop objects before recreating them (destructive but idempotent). */\n clean?: boolean;\n /**\n * Abort on the first error instead of logging and continuing. Defaults\n * ON: a restore that silently skips failed GRANT/RLS statements (because\n * a role is missing) \"succeeds\" with RLS un-enforced — a security hole.\n * Fail loudly instead so the operator knows the restore is incomplete.\n */\n exitOnError?: boolean;\n noOwner?: boolean;\n}): string[] {\n const args = [\"--format=custom\", \"--no-password\", `--dbname=${forLibpq(opts.connectionString)}`];\n if (opts.clean) {\n args.push(\"--clean\", \"--if-exists\");\n }\n if (opts.noOwner) {\n args.push(\"--no-owner\");\n }\n // Default to --exit-on-error unless explicitly disabled.\n if (opts.exitOnError !== false) {\n args.push(\"--exit-on-error\");\n }\n args.push(opts.inputFile);\n return args;\n}\n\n/**\n * Assemble the `pg_restore --list` argument vector. Reading a dump's table\n * of contents parses the whole archive without touching a database, so it is\n * a cheap integrity check that the file isn't truncated or corrupt.\n */\nexport function buildPgRestoreListArgs(inputFile: string): string[] {\n return [\"--list\", inputFile];\n}\n\n/**\n * Assemble the `pg_dumpall --globals-only` argument vector. Roles (and other\n * cluster-wide objects) live outside any single database, so a per-database\n * `pg_dump` omits them. Without the `rebase_user` role the RLS GRANT\n * statements in the main dump fail on restore and RLS is silently lost — so\n * every backup captures the globals into a sidecar `.globals.sql`.\n *\n * `--no-role-passwords` keeps role secrets out of the artifact (backups may\n * be shipped off-box); roles are recreated password-less and re-secured by\n * the operator.\n */\nexport function buildPgDumpallGlobalsArgs(opts: {\n connectionString: string;\n outFile: string;\n}): string[] {\n return [\n \"--globals-only\",\n \"--no-role-passwords\",\n \"--no-password\",\n `--file=${opts.outFile}`,\n `--dbname=${forLibpq(opts.connectionString)}`\n ];\n}\n\n/**\n * Derive the globals sidecar path/key for a given `.dump` file. Keeps the\n * two artifacts adjacent so listing, uploading and pruning can find one from\n * the other. A name that doesn't end in `.dump` is returned unchanged with a\n * `.globals.sql` suffix appended.\n */\nexport function globalsFileForDump(dumpPath: string): string {\n return dumpPath.endsWith(\".dump\")\n ? dumpPath.slice(0, -\".dump\".length) + \".globals.sql\"\n : dumpPath + \".globals.sql\";\n}\n\n/**\n * Split a `pg_dumpall --globals-only` script into individual statements.\n * Used when replaying globals on restore so each `CREATE ROLE` / `GRANT`\n * can run independently and a benign \"role already exists\" on one doesn't\n * abort the rest. Drops `--` comment lines and blank statements.\n */\nexport function splitGlobalsStatements(sql: string): string[] {\n const withoutComments = sql\n .split(\"\\n\")\n // `--` comments, and psql meta-commands. pg_dumpall 15+ wraps its output\n // in `\\restrict <token>` / `\\unrestrict <token>`, which are instructions\n // to psql, not SQL. This replay sends statements over a connection\n // instead, so they arrived at the server as `\\restrict …` and came back\n // as `syntax error at or near \"\\\"` — reported to the user as two skipped\n // globals per restore, which reads like roles failed to apply when\n // nothing did. They carry no state worth replaying: dropping them is\n // exactly what a SQL-level consumer should do.\n .filter((line) => {\n const trimmed = line.trim();\n return !trimmed.startsWith(\"--\") && !trimmed.startsWith(\"\\\\\");\n })\n .join(\"\\n\");\n return withoutComments\n .split(\";\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n}\n\n/**\n * Resolve the Postgres connection string the backup commands should use,\n * mirroring the precedence the branch command already relies on.\n */\nexport function resolveConnectionString(\n env: Record<string, string | undefined>\n): string | null {\n return env.DATABASE_URL || env.ADMIN_CONNECTION_STRING || null;\n}\n","/**\n * Retention pruning for scheduled backups. Pure logic — no I/O — so it can\n * be exhaustively unit-tested without touching a storage backend.\n */\nimport { parseBackupTimestamp } from \"./pg-tools\";\n\nexport interface BackupObject {\n /** Storage key / file name. */\n key: string;\n /**\n * Creation time. Optional — when absent it is recovered from the\n * timestamp encoded in the key by `buildBackupFilename`.\n */\n createdAt?: Date;\n /**\n * Size on disk, when the lister knows it (local destinations always do).\n *\n * Reported so an empty artifact cannot masquerade as a backup in\n * `rebase db backups list`. Deliberately NOT consulted by\n * {@link selectBackupsToPrune}: retention decides by age, and a rule that\n * silently skipped small files would make a genuinely tiny dump immortal.\n * Visibility is the fix here; the artifacts themselves are now removed at\n * the point of failure by `discardPartialDump`.\n */\n sizeBytes?: number;\n}\n\nexport interface RetentionOptions {\n /** Delete backups older than this many days. `0`/negative disables age pruning. */\n retentionDays?: number;\n /**\n * Always keep at least this many of the most recent backups, even if\n * they are older than `retentionDays`. Guards against wiping every\n * backup after a long outage. Default: 0 (no minimum).\n */\n keepMinimum?: number;\n /** Reference \"now\" — injectable for deterministic tests. */\n now?: Date;\n}\n\n/**\n * Decide which backups to delete under the given retention policy.\n *\n * Rules, applied in order:\n * 1. Objects whose key isn't a recognised rebase backup (no parseable\n * timestamp and no `createdAt`) are never selected — foreign files in a\n * shared bucket are left untouched.\n * 2. The `keepMinimum` newest backups are always retained.\n * 3. Of the remainder, any older than `retentionDays` are selected for\n * deletion.\n *\n * Returns the keys to delete, oldest first.\n */\nexport function selectBackupsToPrune(\n backups: BackupObject[],\n options: RetentionOptions\n): string[] {\n const retentionDays = options.retentionDays ?? 0;\n const keepMinimum = Math.max(0, options.keepMinimum ?? 0);\n const now = options.now ?? new Date();\n\n if (retentionDays <= 0) {\n return [];\n }\n\n // Resolve a timestamp for every object; drop the ones we can't date.\n const dated = backups\n .map((b) => {\n const createdAt = b.createdAt ?? parseBackupTimestamp(b.key);\n return createdAt ? { key: b.key, createdAt } : null;\n })\n .filter((b): b is { key: string; createdAt: Date } => b !== null);\n\n // Newest first so the first `keepMinimum` are the protected ones.\n dated.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n\n const cutoff = now.getTime() - retentionDays * 24 * 60 * 60 * 1000;\n\n const toDelete = dated\n .slice(keepMinimum)\n .filter((b) => b.createdAt.getTime() < cutoff);\n\n // Return oldest first for predictable, readable logs.\n toDelete.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n return toDelete.map((b) => b.key);\n}\n","/**\n * Where the PostgreSQL client tools are, without spawning them.\n *\n * Kept apart from `backup-service.ts`, which pulls in `execa` (ESM-only), so\n * `createBackupCron` can check for the tools when it is registered.\n */\nimport fs from \"fs\";\nimport { resolveLocalBin } from \"../cli-helpers\";\n\nexport type PgTool = \"pg_dump\" | \"pg_restore\" | \"pg_dumpall\";\n\nconst OVERRIDE_VARIABLE: Record<PgTool, string> = {\n pg_dump: \"PG_DUMP_PATH\",\n pg_restore: \"PG_RESTORE_PATH\",\n pg_dumpall: \"PG_DUMPALL_PATH\"\n};\n\n/** The variable that points at `tool` when it is not on the PATH. */\nexport function pgToolVariable(tool: PgTool): string {\n return OVERRIDE_VARIABLE[tool];\n}\n\n/** Locate `pg_dump` / `pg_restore` / `pg_dumpall`, honouring an env override. */\nexport function resolvePgBinary(\n tool: PgTool,\n env: Record<string, string | undefined> = process.env\n): string | null {\n const override = env[OVERRIDE_VARIABLE[tool]];\n if (override && fs.existsSync(override)) return override;\n return resolveLocalBin(tool);\n}\n","/**\n * Pure-ish orchestration for the backup/restore paths, kept free of `execa`\n * and `pg` value imports so it can be unit-tested under jest (the impure\n * edges — spawning processes, opening connections — live in\n * `backup-service.ts`, which is vitest/runtime only).\n *\n * The functions here take their side-effecting dependency as an argument\n * (a statement runner, an object deleter) so tests can inject fakes.\n */\nimport { globalsFileForDump, splitGlobalsStatements } from \"./pg-tools\";\n\n/**\n * Replay a `pg_dumpall --globals-only` script one statement at a time,\n * tolerating per-statement failures. On a same-cluster restore the roles\n * usually already exist (`CREATE ROLE` → \"already exists\") and on a managed\n * provider an `ALTER ROLE <superuser>` may be refused; neither should abort\n * recreation of the roles that *are* missing. Returns how many statements\n * applied vs were skipped.\n *\n * `runStatement` executes one SQL statement and rejects on error.\n */\nexport async function applyGlobalsWith(\n runStatement: (sql: string) => Promise<void>,\n globalsSql: string,\n log: (message: string) => void = () => {}\n): Promise<{ applied: number; skipped: number }> {\n let applied = 0;\n let skipped = 0;\n for (const statement of splitGlobalsStatements(globalsSql)) {\n try {\n await runStatement(statement);\n applied++;\n } catch (err) {\n skipped++;\n const firstLine = statement.split(\"\\n\")[0].slice(0, 80);\n log(` • Skipped global: ${firstLine} (${err instanceof Error ? err.message : String(err)})`);\n }\n }\n return { applied, skipped };\n}\n\n/**\n * Delete each pruned dump together with its `.globals.sql` roles sidecar, so\n * pruning never orphans the roles file. The sidecar is best-effort — older\n * backups predate it, so a missing-sidecar failure is swallowed while a\n * failure deleting the dump itself propagates.\n *\n * `deleteObject` removes one key and rejects if it cannot (e.g. not found).\n */\nexport async function pruneWith(\n keys: string[],\n deleteObject: (key: string) => Promise<void>\n): Promise<void> {\n for (const key of keys) {\n await deleteObject(key);\n try {\n await deleteObject(globalsFileForDump(key));\n } catch {\n // Sidecar may not exist for older backups — ignore.\n }\n }\n}\n\n/**\n * Remove a dump artifact abandoned by a failed tool run.\n *\n * `pg_dump` creates its `--file=` target before it finishes connecting, so any\n * failure — a URL libpq rejects, a dropped connection, a full disk — leaves a\n * 0-byte file behind. That corpse is not inert: `rebase db backups list` used\n * to show it as an ordinary entry, and `selectBackupsToPrune` ranks by\n * timestamp alone, so it occupies a protected `keepMinimum` slot and can push\n * a real backup out of retention.\n *\n * Best-effort on purpose: the caller is already throwing, and a failed unlink\n * must not replace the real diagnosis with an ENOENT/EPERM from the cleanup.\n *\n * Lives here rather than in `backup-service.ts` for the reason at the top of\n * this file — that module's top-level `execa` import makes it unloadable under\n * jest, so anything placed there cannot be unit-tested.\n *\n * `remove` deletes one file and throws if it cannot; `exists` reports presence.\n */\nexport function discardPartialDumpWith(\n exists: (file: string) => boolean,\n remove: (file: string) => void,\n file: string\n): void {\n try {\n if (exists(file)) remove(file);\n } catch {\n // Ignored: see above.\n }\n}\n","/**\n * Backup / restore orchestration: thin, well-typed wrappers around\n * `pg_dump` and `pg_restore`, plus binary detection, version pre-flight,\n * and upload/prune against a storage backend.\n *\n * The pure argument- and policy-logic lives in `pg-tools.ts` and\n * `retention.ts`; this module is the impure edge (spawns processes, talks\n * to Postgres and storage) and is intentionally kept small.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport type { StorageController } from \"@rebasepro/server\";\nimport { resolvePgBinary } from \"./pg-binary\";\nimport {\n BackupDestination,\n buildBackupFilename,\n buildPgDumpArgs,\n buildPgDumpallGlobalsArgs,\n buildRowSecurityPgOptions,\n diagnoseRowSecurityDumpFailure,\n type RowSecurityIdentity,\n buildPgRestoreArgs,\n buildPgRestoreListArgs,\n checkToolServerCompatibility,\n globalsFileForDump,\n joinStorageKey,\n parsePgToolMajor,\n parseBackupTimestamp,\n serverVersionNumToMajor,\n VersionCompatibility\n} from \"./pg-tools\";\nimport { BackupObject, RetentionOptions, selectBackupsToPrune } from \"./retention\";\nimport { applyGlobalsWith, discardPartialDumpWith, pruneWith } from \"./backup-logic\";\n\n/**\n * Remove a dump artifact abandoned by a failed tool run. See\n * {@link discardPartialDumpWith} for why this exists and why the logic lives\n * in the execa-free module.\n */\nexport function discardPartialDump(file: string): void {\n discardPartialDumpWith(\n (f) => fs.existsSync(f),\n (f) => fs.unlinkSync(f),\n file\n );\n}\n\nexport class BackupToolError extends Error {\n constructor(message: string, readonly hint?: string) {\n super(message);\n this.name = \"BackupToolError\";\n }\n}\n\nexport { resolvePgBinary };\n\n/** Run `<bin> --version` and extract the major version. */\nexport async function detectToolMajor(bin: string): Promise<number | null> {\n try {\n const { stdout } = await execa(bin, [\"--version\"]);\n return parsePgToolMajor(stdout);\n } catch {\n return null;\n }\n}\n\n/** Query the server for its major version via `server_version_num`. */\nexport async function getServerVersionMajor(connectionString: string): Promise<number | null> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString });\n await client.connect();\n try {\n const res = await client.query(\"SHOW server_version_num\");\n const raw = res.rows?.[0]?.server_version_num;\n return serverVersionNumToMajor(raw);\n } finally {\n await client.end();\n }\n}\n\nexport interface PreflightResult extends VersionCompatibility {\n bin: string;\n toolMajor: number | null;\n serverMajor: number | null;\n}\n\n/**\n * Verify the requested client tool exists and its major version is\n * compatible with the live server. Throws {@link BackupToolError} — with a\n * doctor-style hint — when the binary is missing.\n */\nexport async function preflight(\n tool: \"pg_dump\" | \"pg_restore\",\n connectionString: string,\n env: Record<string, string | undefined> = process.env\n): Promise<PreflightResult> {\n const bin = resolvePgBinary(tool, env);\n if (!bin) {\n throw new BackupToolError(\n `Could not find the '${tool}' binary.`,\n `Install the PostgreSQL client tools (e.g. 'brew install libpq' or 'apt-get install postgresql-client'), ` +\n `or set ${tool === \"pg_dump\" ? \"PG_DUMP_PATH\" : \"PG_RESTORE_PATH\"} to its full path.`\n );\n }\n const [toolMajor, serverMajor] = await Promise.all([\n detectToolMajor(bin),\n getServerVersionMajor(connectionString)\n ]);\n const compat = checkToolServerCompatibility(toolMajor, serverMajor);\n return { bin, toolMajor, serverMajor, ...compat };\n}\n\nexport interface BackupResult {\n /** Absolute path of the produced dump file on local disk. */\n localFile: string;\n fileName: string;\n sizeBytes: number;\n /**\n * Absolute path of the `.globals.sql` sidecar holding cluster-wide roles\n * (present unless globals capture was disabled or unavailable).\n */\n globalsFile?: string;\n globalsSizeBytes?: number;\n}\n\n/**\n * Produce a custom-format dump on local disk. When `outDir` is omitted the\n * file is written to the OS temp directory (used by the upload path, which\n * cleans it up afterwards).\n *\n * Alongside the `-Fc` dump it writes a `<name>.globals.sql` sidecar via\n * `pg_dumpall --globals-only` so the roles the dump's GRANT/RLS statements\n * depend on can be recreated on restore. Set `includeGlobals: false` to skip\n * it (e.g. when the caller has no privilege to read cluster globals).\n */\nexport async function createDump(opts: {\n connectionString: string;\n dbName: string;\n outDir?: string;\n fileName?: string;\n excludeSchemas?: string[];\n noOwner?: boolean;\n inheritStdio?: boolean;\n includeGlobals?: boolean;\n env?: Record<string, string | undefined>;\n /**\n * Dump with row security left on, reading as this identity.\n *\n * The escape hatch for a managed Postgres, where the dumping role owns\n * nothing and has no `BYPASSRLS`. Off by default, and deliberately so: with\n * row security on, `pg_dump` stops erroring on rows it cannot see and\n * simply omits them. See {@link RowSecurityIdentity}.\n */\n rowSecurity?: RowSecurityIdentity;\n}): Promise<BackupResult> {\n const env = opts.env ?? process.env;\n const bin = resolvePgBinary(\"pg_dump\", env);\n if (!bin) {\n throw new BackupToolError(\n \"Could not find the 'pg_dump' binary.\",\n \"Install the PostgreSQL client tools or set PG_DUMP_PATH.\"\n );\n }\n\n const fileName = opts.fileName ?? buildBackupFilename(opts.dbName);\n const outDir = opts.outDir ?? fs.mkdtempSync(path.join(os.tmpdir(), \"rebase-backup-\"));\n fs.mkdirSync(outDir, { recursive: true });\n const localFile = path.join(outDir, fileName);\n\n const args = buildPgDumpArgs({\n connectionString: opts.connectionString,\n outFile: localFile,\n excludeSchemas: opts.excludeSchemas,\n noOwner: opts.noOwner,\n rowSecurity: opts.rowSecurity\n });\n\n // `PGOPTIONS` is the only way to set a GUC on a tool that takes no SQL.\n // Built from the same object that added `--enable-row-security`, so the\n // flag cannot travel without the identity that makes it safe.\n const dumpEnv: Record<string, string> = { ...(env as Record<string, string>) };\n if (opts.rowSecurity) {\n dumpEnv.PGOPTIONS = [env.PGOPTIONS, buildRowSecurityPgOptions(opts.rowSecurity)]\n .filter(Boolean).join(\" \");\n }\n\n try {\n await execa(bin, args, {\n stdio: opts.inheritStdio ? \"inherit\" : \"pipe\",\n env: dumpEnv\n });\n } catch (error) {\n // pg_dump creates its `--file=` target before it finishes connecting,\n // so any failure here — a URL libpq rejects, a dropped connection, a\n // full disk — leaves a 0-byte file behind that nothing else removed.\n // That corpse is not inert: `rebase db backups list` shows it as an\n // ordinary entry, and `selectBackupsToPrune` ranks by timestamp alone,\n // so it occupies a protected `keepMinimum` slot and can push a real\n // backup out of retention. A missing backup is honest; an empty file\n // that reads as a backup is not.\n discardPartialDump(localFile);\n // The RLS failure names a table and no cause. Replace it with the\n // cause and the two ways out; anything else is re-thrown untouched.\n const diagnosis = diagnoseRowSecurityDumpFailure(error);\n if (!diagnosis) throw error;\n throw new BackupToolError(\n diagnosis,\n \"Run `rebase db backup --help` for the flag, and read what it says about partial dumps.\"\n );\n }\n\n const sizeBytes = fs.existsSync(localFile) ? fs.statSync(localFile).size : 0;\n\n const result: BackupResult = { localFile, fileName, sizeBytes };\n\n if (opts.includeGlobals !== false) {\n const dumpallBin = resolvePgBinary(\"pg_dumpall\", env);\n if (!dumpallBin) {\n throw new BackupToolError(\n \"Could not find the 'pg_dumpall' binary needed to capture cluster roles.\",\n \"Install the PostgreSQL client tools or set PG_DUMPALL_PATH. \" +\n \"To take a role-incomplete backup anyway, pass includeGlobals: false.\"\n );\n }\n const globalsFile = globalsFileForDump(localFile);\n try {\n await execa(\n dumpallBin,\n buildPgDumpallGlobalsArgs({ connectionString: opts.connectionString, outFile: globalsFile }),\n { stdio: opts.inheritStdio ? \"inherit\" : \"pipe\", env: { ...(env as Record<string, string>) } }\n );\n } catch (error) {\n // Same reasoning as the pg_dump catch above, and the dump goes with\n // it: the pair is uploaded and pruned together, so a dump whose\n // roles sidecar is missing restores without the roles its GRANT and\n // RLS statements need — the exact failure the sidecar exists to\n // prevent. Leaving half a pair on disk would look like a backup.\n discardPartialDump(globalsFile);\n discardPartialDump(localFile);\n throw error;\n }\n result.globalsFile = globalsFile;\n result.globalsSizeBytes = fs.existsSync(globalsFile) ? fs.statSync(globalsFile).size : 0;\n }\n\n return result;\n}\n\n/**\n * Cheap integrity check on a freshly written dump: it must be non-empty and\n * `pg_restore --list` must parse its table of contents without error. Used\n * before pruning older backups so a corrupt-but-exit-0 dump never becomes\n * the reason the last good backup is deleted.\n */\nexport async function validateDump(\n localFile: string,\n env: Record<string, string | undefined> = process.env\n): Promise<{ ok: boolean; reason?: string }> {\n if (!fs.existsSync(localFile)) {\n return { ok: false, reason: `Dump file does not exist: ${localFile}` };\n }\n if (fs.statSync(localFile).size === 0) {\n return { ok: false, reason: \"Dump file is empty (0 bytes).\" };\n }\n const bin = resolvePgBinary(\"pg_restore\", env);\n if (!bin) {\n // Can't verify without pg_restore; treat as inconclusive-but-fail so\n // pruning doesn't proceed on an unverified dump.\n return { ok: false, reason: \"Could not find 'pg_restore' to verify the dump.\" };\n }\n try {\n await execa(bin, buildPgRestoreListArgs(localFile), {\n stdio: \"pipe\",\n env: { ...(env as Record<string, string>) }\n });\n return { ok: true };\n } catch (err) {\n return { ok: false, reason: `pg_restore --list failed: ${err instanceof Error ? err.message : String(err)}` };\n }\n}\n\n/**\n * Replay a `pg_dumpall --globals-only` script to recreate cluster roles\n * before a restore, so the dump's GRANT/RLS statements (which reference\n * `rebase_user` and any owner roles) actually apply. Runs statement by\n * statement and tolerates per-statement failures — on a same-cluster restore\n * the roles usually already exist (`CREATE ROLE` → \"already exists\"), and on\n * a managed provider an `ALTER ROLE <superuser>` may be refused; neither\n * should abort role recreation. Returns how many statements applied vs were\n * skipped.\n */\nexport async function applyGlobals(\n connectionString: string,\n globalsSql: string,\n log: (message: string) => void = () => {}\n): Promise<{ applied: number; skipped: number }> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString });\n await client.connect();\n try {\n return await applyGlobalsWith(\n async (sql) => { await client.query(sql); },\n globalsSql,\n log\n );\n } finally {\n await client.end();\n }\n}\n\n/**\n * Restore a custom-format dump into the database named by\n * `connectionString`. Destructive when `clean` is set (drops objects\n * first). Never called automatically — the CLI gates it behind explicit\n * confirmation.\n *\n * Runs with `--exit-on-error` by default: a restore that logs-and-continues\n * past a failed GRANT (because a role was missing) reports success with RLS\n * un-enforced. Callers should recreate roles first (see {@link applyGlobals})\n * and only set `exitOnError: false` deliberately.\n */\nexport async function restoreDump(opts: {\n connectionString: string;\n inputFile: string;\n clean?: boolean;\n noOwner?: boolean;\n exitOnError?: boolean;\n inheritStdio?: boolean;\n env?: Record<string, string | undefined>;\n}): Promise<void> {\n const env = opts.env ?? process.env;\n const bin = resolvePgBinary(\"pg_restore\", env);\n if (!bin) {\n throw new BackupToolError(\n \"Could not find the 'pg_restore' binary.\",\n \"Install the PostgreSQL client tools or set PG_RESTORE_PATH.\"\n );\n }\n const args = buildPgRestoreArgs({\n connectionString: opts.connectionString,\n inputFile: opts.inputFile,\n clean: opts.clean,\n noOwner: opts.noOwner,\n exitOnError: opts.exitOnError\n });\n await execa(bin, args, {\n stdio: opts.inheritStdio ? \"inherit\" : \"pipe\",\n env: { ...(env as Record<string, string>) }\n });\n}\n\n/**\n * Create a database (if absent) by connecting to the maintenance\n * `postgres` database. Used by `restore --create-db`.\n */\nexport async function ensureDatabaseExists(\n adminConnectionString: string,\n dbName: string\n): Promise<boolean> {\n const { Client } = await import(\"pg\");\n const parsed = new URL(adminConnectionString);\n parsed.pathname = \"/postgres\";\n const client = new Client({ connectionString: parsed.toString() });\n await client.connect();\n try {\n const existing = await client.query(\"SELECT 1 FROM pg_database WHERE datname = $1\", [dbName]);\n if (existing.rowCount && existing.rowCount > 0) {\n return false;\n }\n // Identifier can't be parameterised; guard against injection.\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(dbName)) {\n throw new BackupToolError(`Invalid database name: \"${dbName}\"`);\n }\n await client.query(`CREATE DATABASE \"${dbName}\"`);\n return true;\n } finally {\n await client.end();\n }\n}\n\n/**\n * Upload a local dump to object storage under the destination's prefix.\n * Backups may contain secrets/PII, so the object is written with a\n * private/octet-stream content type; bucket-level ACLs must stay private.\n */\nexport async function uploadBackup(\n storage: StorageController,\n localFile: string,\n dest: Extract<BackupDestination, { kind: \"s3\" | \"gcs\" }>\n): Promise<{ key: string; storageUrl: string }> {\n const fileName = path.basename(localFile);\n const key = joinStorageKey(dest.prefix, fileName);\n // Backed by the dump on disk, not read into memory: the built-in\n // controllers write it a chunk (S3: a multipart part) at a time. Read with\n // `readFileSync` and copied into a `File`, a dump was held three or four\n // times over in the process running the cron, and one over 2 GiB could\n // not be read at all (`ERR_FS_FILE_TOO_LARGE`), so it never uploaded.\n const file = new File([await fs.openAsBlob(localFile)], fileName, { type: \"application/octet-stream\" });\n // Not held to the controller's upload limits: `maxFileSize` (50 MB unless\n // set) and `allowedMimeTypes` say what a user may upload, and the CLI and\n // the documented cron build their controller without either. Held to\n // them, every dump over 50 MB failed with PAYLOAD_TOO_LARGE.\n const result = await storage.putObject({\n file,\n key,\n bucket: dest.bucket,\n metadata: { \"rebase-backup\": \"1\" }\n }, { uploadLimits: false });\n return { key, storageUrl: result.storageUrl };\n}\n\n/** Stats in flight at once while listing a local backup folder. */\nconst LOCAL_STAT_CONCURRENCY = 32;\n\n/** `fn` over `items`, at most `limit` at a time; results in input order. */\nasync function mapBounded<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n const worker = async () => {\n while (next < items.length) {\n const i = next++;\n results[i] = await fn(items[i]);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return results;\n}\n\n/**\n * List existing backups at a destination. For local destinations reads the\n * directory; for object storage lists the prefix via the controller.\n */\nexport async function listBackups(\n dest: BackupDestination,\n storage?: StorageController\n): Promise<BackupObject[]> {\n if (dest.kind === \"local\") {\n // Asynchronous throughout, a few stats at a time: retention lists the\n // folder after every scheduled backup, inside the server process, and\n // a year of hourly backups is 8,760 dumps stat'ed one by one.\n const stat = await fs.promises.stat(dest.path).catch(() => null);\n if (!stat) return [];\n const dir = stat.isDirectory() ? dest.path : path.dirname(dest.path);\n const dumps = (await fs.promises.readdir(dir)).filter((f) => f.endsWith(\".dump\"));\n const stats = await mapBounded(dumps, LOCAL_STAT_CONCURRENCY, (f) => fs.promises.stat(path.join(dir, f)));\n return dumps\n .map((f, i) => {\n const createdAt = parseBackupTimestamp(f) ?? stats[i].mtime;\n return { key: path.join(dir, f), createdAt, sizeBytes: stats[i].size };\n })\n .sort((a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0));\n }\n\n if (!storage) {\n throw new BackupToolError(\n `Listing ${dest.kind} backups requires a configured storage backend.`\n );\n }\n // The server's lister, not a second copy of it: a listing is paged, in\n // ascending key order, and this one read a single page of 1,000 — the\n // OLDEST backups — so `rebase db backups list` stopped showing new ones,\n // and retention ranked a page that held none of the newest. The two copies\n // had already drifted apart once (over the roles sidecar).\n const { listBackupObjects } = await import(\"@rebasepro/server\");\n const listed = await listBackupObjects(dest, storage);\n return listed.map((info) => ({\n key: info.key,\n createdAt: info.createdAt ? new Date(info.createdAt) : undefined\n }));\n}\n\n/**\n * Apply a retention policy to a destination, deleting the backups selected\n * by {@link selectBackupsToPrune}. Returns the keys that were removed.\n */\nexport async function pruneBackups(\n dest: BackupDestination,\n options: RetentionOptions,\n storage?: StorageController\n): Promise<string[]> {\n const backups = await listBackups(dest, storage);\n const toDelete = selectBackupsToPrune(backups, options);\n\n // Delete each dump together with its `.globals.sql` sidecar (pruneWith\n // handles the pairing + best-effort sidecar). The deleter rejects on a\n // missing key so pruneWith can swallow an absent sidecar.\n const deleteObject =\n dest.kind === \"local\"\n ? async (key: string) => {\n if (!fs.existsSync(key)) throw new Error(`not found: ${key}`);\n fs.unlinkSync(key);\n }\n : async (key: string) => {\n if (!storage) throw new BackupToolError(\"Storage backend required to prune object backups.\");\n await storage.deleteObject(key, dest.bucket);\n };\n\n await pruneWith(toDel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;EACxG,OAAO,MACF,KAAK,GAAG,MAAM;GACX,MAAM,YAAY,qBAAqB,CAAC,KAAK,MAAM,EAAE,CAAC;GACtD,OAAO;IAAE,KAAK,KAAK,KAAK,KAAK,CAAC;IAAG;IAAW,WAAW,MAAM,EAAE,CAAC;GAAK;EACzE,CAAC,CAAC,CACD,MAAM,GAAG,OAAO,EAAE,WAAW,QAAQ,KAAK,MAAM,EAAE,WAAW,QAAQ,KAAK,EAAE;CACrF;CAEA,IAAI,CAAC,SACD,MAAM,IAAI,gBACN,WAAW,KAAK,KAAK,gDACzB;CAOJ,MAAM,EAAE,sBAAsB,MAAM,OAAO;CAE3C,QAAO,MADc,kBAAkB,MAAM,OAAO,EAAA,CACtC,KAAK,UAAU;EACzB,KAAK,KAAK;EACV,WAAW,KAAK,YAAY,IAAI,KAAK,KAAK,SAAS,IAAI,KAAA;CAC3D,EAAE;AACN;;;;;AAMA,eAAsB,aAClB,MACA,SACA,SACiB;CAEjB,MAAM,WAAW,qBAAqB,MADhB,YAAY,MAAM,OAAO,GACA,OAAO;CAgBtD,MAAM,UAAU,UAVZ,KAAK,SAAS,UACR,OAAO,QAAgB;EACrB,IAAI,CAAC,GAAG,WAAW,GAAG,GAAG,MAAM,IAAI,MAAM,cAAc,KAAK;EAC5D,GAAG,WAAW,GAAG;CACrB,IACE,OAAO,QAAgB;EACrB,IAAI,CAAC,SAAS,MAAM,IAAI,gBAAgB,mDAAmD;EAC3F,MAAM,QAAQ,aAAa,KAAK,KAAK,MAAM;CAC/C,CAE8B;CACtC,OAAO;AACX"}
@@ -0,0 +1,105 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ import { r as __exportAll } from "./__vite-browser-external-BnuHet1e.js";
4
+ import { n as extractPgError } from "./pg-error-utils-vJezlXdI.js";
5
+ //#region src/schema/boot-ddl.ts
6
+ /**
7
+ * How boot DDL waits for a table lock, and how it applies several statements as
8
+ * one.
9
+ *
10
+ * ## Why boot DDL has a lock budget at all
11
+ *
12
+ * Every statement that changes a table — `ALTER TABLE`, `CREATE`/`DROP POLICY`,
13
+ * `DROP TRIGGER` — needs a lock that conflicts with readers. While it *waits*
14
+ * for that lock it sits in the table's lock queue, and every query that arrives
15
+ * after it queues behind it, however short. A boot that happened to start while
16
+ * a report, a long transaction or a `pg_dump` held a table stalled every live
17
+ * read of that table for as long as it waited — up to the pool's
18
+ * `statement_timeout` (30 s), per statement, one table after another.
19
+ *
20
+ * `lock_timeout` turns that wait into a short, bounded attempt. Measured on
21
+ * Postgres 18: a reader holding one table for 5 s held a live `SELECT
22
+ * count(*)` behind the boot for 4.4 s; with the budget below it is held for at
23
+ * most {@link BOOT_LOCK_TIMEOUT_MS}, and the queue drains between attempts.
24
+ *
25
+ * ## The budget
26
+ *
27
+ * 1 s per attempt. An uncontended `ACCESS EXCLUSIVE` on a healthy table is
28
+ * granted in well under a millisecond — the wait is for the statements already
29
+ * running on it to finish — so a second is three orders of magnitude of
30
+ * headroom and never fires on a database that is merely busy. It fires only
31
+ * when something holds the table for longer than any interactive query should,
32
+ * and then the cost to live traffic is one second, which sits inside every
33
+ * client timeout this framework ships with. Longer budgets buy nothing a retry
34
+ * does not buy better: the queue behind a waiting lock grows for as long as it
35
+ * waits, and drains as soon as it gives up.
36
+ *
37
+ * ## Applying several statements as one
38
+ *
39
+ * {@link atomicBatch} joins statements into one simple-protocol query string.
40
+ * Postgres runs a multi-statement query as a single implicit transaction: every
41
+ * statement commits or none does, the `SET LOCAL` applies to that transaction
42
+ * only, and a failure rolls it back on its own — the connection goes back to the
43
+ * pool clean, which an explicit `BEGIN` in the string would not guarantee. It is
44
+ * one round trip and one commit instead of one of each per statement.
45
+ *
46
+ * A handle that speaks only the extended protocol (PGlite in-process, used by
47
+ * tests) refuses the string before running any of it; {@link
48
+ * isMultiStatementRefusal} recognises that so the caller can fall back to one
49
+ * statement at a time.
50
+ */
51
+ var boot_ddl_exports = /* @__PURE__ */ __exportAll({
52
+ BOOT_LOCK_ATTEMPTS: () => 3,
53
+ BOOT_LOCK_RETRY_BUDGET_MS: () => BOOT_LOCK_RETRY_BUDGET_MS,
54
+ BOOT_LOCK_TIMEOUT_MS: () => BOOT_LOCK_TIMEOUT_MS,
55
+ atomicBatch: () => atomicBatch,
56
+ isLockTimeout: () => isLockTimeout,
57
+ isMultiStatementRefusal: () => isMultiStatementRefusal,
58
+ joinStatements: () => joinStatements,
59
+ resolveBootLockOptions: () => resolveBootLockOptions,
60
+ sleep: () => sleep
61
+ });
62
+ /** `lock_timeout` for each attempt at a boot DDL statement or batch. See the module comment. */
63
+ var BOOT_LOCK_TIMEOUT_MS = 1e3;
64
+ /**
65
+ * The most lock waiting one boot step spends on *retries*, in total.
66
+ *
67
+ * Without a cap, a holder that covers the whole database — a `pg_dump` takes
68
+ * `ACCESS SHARE` on every table it dumps, for as long as it runs — costs
69
+ * tables × attempts × timeout: four minutes at 240 tables. Retrying is for the
70
+ * holder that is about to finish (a report, a transaction), and ten seconds is
71
+ * plenty to wait that out; past it, waiting longer only delays the boot.
72
+ */
73
+ var BOOT_LOCK_RETRY_BUDGET_MS = 1e4;
74
+ var resolveBootLockOptions = (options = {}) => ({
75
+ lockTimeoutMs: options.lockTimeoutMs ?? 1e3,
76
+ attempts: Math.max(1, options.attempts ?? 3),
77
+ retryBudgetMs: options.retryBudgetMs ?? 1e4,
78
+ backoffMs: options.backoffMs ?? ((round) => 500 * round * (1 + Math.random()))
79
+ });
80
+ /** `55P03 lock_not_available` — what `lock_timeout` raises. */
81
+ var isLockTimeout = (err) => extractPgError(err)?.code === "55P03";
82
+ /**
83
+ * `42601` "cannot insert multiple commands into a prepared statement": the
84
+ * handle runs every query over the extended protocol, which carries exactly one
85
+ * statement. Raised before anything runs, so nothing needs undoing.
86
+ */
87
+ var isMultiStatementRefusal = (err) => {
88
+ const pg = extractPgError(err);
89
+ return pg?.code === "42601" && /multiple commands/i.test(pg.message ?? "");
90
+ };
91
+ /**
92
+ * `SET LOCAL lock_timeout`, then the statements: one string, one implicit
93
+ * transaction. See the module comment for why this and not `BEGIN … COMMIT`.
94
+ */
95
+ var atomicBatch = (statements, lockTimeoutMs) => `SET LOCAL lock_timeout = '${Math.max(1, Math.round(lockTimeoutMs))}ms';\n${joinStatements(statements)}`;
96
+ /** Statements as one multi-statement string — one implicit transaction — each `;`-terminated. */
97
+ var joinStatements = (statements) => statements.map((statement) => {
98
+ const trimmed = statement.trim();
99
+ return trimmed.endsWith(";") ? trimmed : `${trimmed};`;
100
+ }).join("\n");
101
+ var sleep = (ms) => ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
102
+ //#endregion
103
+ export { isLockTimeout as a, resolveBootLockOptions as c, boot_ddl_exports as i, sleep as l, BOOT_LOCK_TIMEOUT_MS as n, isMultiStatementRefusal as o, atomicBatch as r, joinStatements as s, BOOT_LOCK_RETRY_BUDGET_MS as t };
104
+
105
+ //# sourceMappingURL=boot-ddl-DVpsFN6r.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"boot-ddl-DVpsFN6r.js","names":[],"sources":["../src/schema/boot-ddl.ts"],"sourcesContent":["/**\n * How boot DDL waits for a table lock, and how it applies several statements as\n * one.\n *\n * ## Why boot DDL has a lock budget at all\n *\n * Every statement that changes a table — `ALTER TABLE`, `CREATE`/`DROP POLICY`,\n * `DROP TRIGGER` — needs a lock that conflicts with readers. While it *waits*\n * for that lock it sits in the table's lock queue, and every query that arrives\n * after it queues behind it, however short. A boot that happened to start while\n * a report, a long transaction or a `pg_dump` held a table stalled every live\n * read of that table for as long as it waited — up to the pool's\n * `statement_timeout` (30 s), per statement, one table after another.\n *\n * `lock_timeout` turns that wait into a short, bounded attempt. Measured on\n * Postgres 18: a reader holding one table for 5 s held a live `SELECT\n * count(*)` behind the boot for 4.4 s; with the budget below it is held for at\n * most {@link BOOT_LOCK_TIMEOUT_MS}, and the queue drains between attempts.\n *\n * ## The budget\n *\n * 1 s per attempt. An uncontended `ACCESS EXCLUSIVE` on a healthy table is\n * granted in well under a millisecond — the wait is for the statements already\n * running on it to finish — so a second is three orders of magnitude of\n * headroom and never fires on a database that is merely busy. It fires only\n * when something holds the table for longer than any interactive query should,\n * and then the cost to live traffic is one second, which sits inside every\n * client timeout this framework ships with. Longer budgets buy nothing a retry\n * does not buy better: the queue behind a waiting lock grows for as long as it\n * waits, and drains as soon as it gives up.\n *\n * ## Applying several statements as one\n *\n * {@link atomicBatch} joins statements into one simple-protocol query string.\n * Postgres runs a multi-statement query as a single implicit transaction: every\n * statement commits or none does, the `SET LOCAL` applies to that transaction\n * only, and a failure rolls it back on its own — the connection goes back to the\n * pool clean, which an explicit `BEGIN` in the string would not guarantee. It is\n * one round trip and one commit instead of one of each per statement.\n *\n * A handle that speaks only the extended protocol (PGlite in-process, used by\n * tests) refuses the string before running any of it; {@link\n * isMultiStatementRefusal} recognises that so the caller can fall back to one\n * statement at a time.\n */\nimport { extractPgError } from \"../utils/pg-error-utils\";\n\n/** `lock_timeout` for each attempt at a boot DDL statement or batch. See the module comment. */\nexport const BOOT_LOCK_TIMEOUT_MS = 1_000;\n\n/** Attempts per table, including the first, before a contended table is given up on. */\nexport const BOOT_LOCK_ATTEMPTS = 3;\n\n/**\n * The most lock waiting one boot step spends on *retries*, in total.\n *\n * Without a cap, a holder that covers the whole database — a `pg_dump` takes\n * `ACCESS SHARE` on every table it dumps, for as long as it runs — costs\n * tables × attempts × timeout: four minutes at 240 tables. Retrying is for the\n * holder that is about to finish (a report, a transaction), and ten seconds is\n * plenty to wait that out; past it, waiting longer only delays the boot.\n */\nexport const BOOT_LOCK_RETRY_BUDGET_MS = 10_000;\n\nexport interface BootLockOptions {\n /** Per-attempt `lock_timeout`, ms. Default {@link BOOT_LOCK_TIMEOUT_MS}. */\n lockTimeoutMs?: number;\n /** Attempts per table, including the first. Default {@link BOOT_LOCK_ATTEMPTS}. */\n attempts?: number;\n /** Total retry waiting per step, ms. Default {@link BOOT_LOCK_RETRY_BUDGET_MS}. */\n retryBudgetMs?: number;\n /** Pause before retry round `round` (1-based), ms. Default: jittered, growing. */\n backoffMs?: (round: number) => number;\n}\n\nexport interface ResolvedBootLockOptions {\n lockTimeoutMs: number;\n attempts: number;\n retryBudgetMs: number;\n backoffMs: (round: number) => number;\n}\n\nexport const resolveBootLockOptions = (options: BootLockOptions = {}): ResolvedBootLockOptions => ({\n lockTimeoutMs: options.lockTimeoutMs ?? BOOT_LOCK_TIMEOUT_MS,\n attempts: Math.max(1, options.attempts ?? BOOT_LOCK_ATTEMPTS),\n retryBudgetMs: options.retryBudgetMs ?? BOOT_LOCK_RETRY_BUDGET_MS,\n // Jittered so two replicas booting together do not retry in lockstep.\n backoffMs: options.backoffMs ?? (round => 500 * round * (1 + Math.random()))\n});\n\n/** `55P03 lock_not_available` — what `lock_timeout` raises. */\nexport const isLockTimeout = (err: unknown): boolean => extractPgError(err)?.code === \"55P03\";\n\n/**\n * `42601` \"cannot insert multiple commands into a prepared statement\": the\n * handle runs every query over the extended protocol, which carries exactly one\n * statement. Raised before anything runs, so nothing needs undoing.\n */\nexport const isMultiStatementRefusal = (err: unknown): boolean => {\n const pg = extractPgError(err);\n return pg?.code === \"42601\" && /multiple commands/i.test(pg.message ?? \"\");\n};\n\n/**\n * `SET LOCAL lock_timeout`, then the statements: one string, one implicit\n * transaction. See the module comment for why this and not `BEGIN … COMMIT`.\n */\nexport const atomicBatch = (statements: readonly string[], lockTimeoutMs: number): string =>\n `SET LOCAL lock_timeout = '${Math.max(1, Math.round(lockTimeoutMs))}ms';\\n${joinStatements(statements)}`;\n\n/** Statements as one multi-statement string — one implicit transaction — each `;`-terminated. */\nexport const joinStatements = (statements: readonly string[]): string =>\n statements\n .map(statement => {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n })\n .join(\"\\n\");\n\nexport const sleep = (ms: number): Promise<void> =>\n ms > 0 ? new Promise(resolve => setTimeout(resolve, ms)) : Promise.resolve();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,uBAAuB;;;;;;;;;;AAcpC,IAAa,4BAA4B;AAoBzC,IAAa,0BAA0B,UAA2B,CAAC,OAAgC;CAC/F,eAAe,QAAQ,iBAAA;CACvB,UAAU,KAAK,IAAI,GAAG,QAAQ,YAAA,CAA8B;CAC5D,eAAe,QAAQ,iBAAA;CAEvB,WAAW,QAAQ,eAAc,UAAS,MAAM,SAAS,IAAI,KAAK,OAAO;AAC7E;;AAGA,IAAa,iBAAiB,QAA0B,eAAe,GAAG,CAAC,EAAE,SAAS;;;;;;AAOtF,IAAa,2BAA2B,QAA0B;CAC9D,MAAM,KAAK,eAAe,GAAG;CAC7B,OAAO,IAAI,SAAS,WAAW,qBAAqB,KAAK,GAAG,WAAW,EAAE;AAC7E;;;;;AAMA,IAAa,eAAe,YAA+B,kBACvD,6BAA6B,KAAK,IAAI,GAAG,KAAK,MAAM,aAAa,CAAC,EAAE,QAAQ,eAAe,UAAU;;AAGzG,IAAa,kBAAkB,eAC3B,WACK,KAAI,cAAa;CACd,MAAM,UAAU,UAAU,KAAK;CAC/B,OAAO,QAAQ,SAAS,GAAG,IAAI,UAAU,GAAG,QAAQ;AACxD,CAAC,CAAC,CACD,KAAK,IAAI;AAElB,IAAa,SAAS,OAClB,KAAK,IAAI,IAAI,SAAQ,YAAW,WAAW,SAAS,EAAE,CAAC,IAAI,QAAQ,QAAQ"}