@rebasepro/server-postgres 0.25.0-canary.g70dad01 → 0.25.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 (48) hide show
  1. package/dist/{BranchService-DO_3_CXt.js → BranchService-iXXZeVYD.js} +133 -20
  2. package/dist/BranchService-iXXZeVYD.js.map +1 -0
  3. package/dist/backup/backup-service.d.ts +8 -3
  4. package/dist/backup/pg-tools.d.ts +13 -1
  5. package/dist/{backup-cli-Ap2WX2uW.js → backup-cli-B2CAn9fR.js} +3 -3
  6. package/dist/{backup-cli-Ap2WX2uW.js.map → backup-cli-B2CAn9fR.js.map} +1 -1
  7. package/dist/{backup-service-DytMimsL.js → backup-service-Bb39plam.js} +67 -10
  8. package/dist/backup-service-Bb39plam.js.map +1 -0
  9. package/dist/{boot-ddl-D1lMCZLd.js → boot-ddl-s_3Hkz94.js} +2 -2
  10. package/dist/{boot-ddl-D1lMCZLd.js.map → boot-ddl-s_3Hkz94.js.map} +1 -1
  11. package/dist/{cli-console-CQGsBzSY.js → cli-console-DQ_K-sdM.js} +4 -4
  12. package/dist/{cli-console-CQGsBzSY.js.map → cli-console-DQ_K-sdM.js.map} +1 -1
  13. package/dist/{cli-errors-CJTKAKax.js → cli-errors-DwQnNATs.js} +52 -2
  14. package/dist/{cli-errors-CJTKAKax.js.map → cli-errors-DwQnNATs.js.map} +1 -1
  15. package/dist/cli-errors.d.ts +10 -0
  16. package/dist/cli.js +29 -24
  17. package/dist/cli.js.map +1 -1
  18. package/dist/{deferred-index-build-BiTqxqdl.js → deferred-index-build-Cis_HoGn.js} +3 -3
  19. package/dist/{deferred-index-build-BiTqxqdl.js.map → deferred-index-build-Cis_HoGn.js.map} +1 -1
  20. package/dist/{doctor-N3J88BN_.js → doctor-DvJH-IQG.js} +2 -2
  21. package/dist/{doctor-N3J88BN_.js.map → doctor-DvJH-IQG.js.map} +1 -1
  22. package/dist/{ensure-collection-policies-CVP6kIPT.js → ensure-collection-policies-CCqayoUz.js} +4 -4
  23. package/dist/{ensure-collection-policies-CVP6kIPT.js.map → ensure-collection-policies-CCqayoUz.js.map} +1 -1
  24. package/dist/{ensure-collection-tables-1WVNALOW.js → ensure-collection-tables-DvvImXDe.js} +5 -5
  25. package/dist/{ensure-collection-tables-1WVNALOW.js.map → ensure-collection-tables-DvvImXDe.js.map} +1 -1
  26. package/dist/{ensure-tables-D-Nm2k3S.js → ensure-tables-Dpgwx5sy.js} +2 -2
  27. package/dist/{ensure-tables-D-Nm2k3S.js.map → ensure-tables-Dpgwx5sy.js.map} +1 -1
  28. package/dist/{enum-labels-kept-e_93v2Ic.js → enum-labels-kept-CUlUlRkO.js} +2 -2
  29. package/dist/{enum-labels-kept-e_93v2Ic.js.map → enum-labels-kept-CUlUlRkO.js.map} +1 -1
  30. package/dist/index.es.js +6 -6
  31. package/dist/{open-rebase-Cwnqo5LU.js → open-rebase-BKA7Nyoe.js} +21 -16
  32. package/dist/{open-rebase-Cwnqo5LU.js.map → open-rebase-BKA7Nyoe.js.map} +1 -1
  33. package/dist/{pg-error-utils-Cmo8wZPy.js → pg-error-utils-Bv5n2PLn.js} +2 -2
  34. package/dist/{pg-error-utils-Cmo8wZPy.js.map → pg-error-utils-Bv5n2PLn.js.map} +1 -1
  35. package/dist/{push-index-prebuild-SXRlWBjc.js → push-index-prebuild-DIequ4bV.js} +3 -3
  36. package/dist/{push-index-prebuild-SXRlWBjc.js.map → push-index-prebuild-DIequ4bV.js.map} +1 -1
  37. package/dist/{push-legacy-renames-B37yKDac.js → push-legacy-renames-BqJut4F3.js} +3 -3
  38. package/dist/{push-legacy-renames-B37yKDac.js.map → push-legacy-renames-BqJut4F3.js.map} +1 -1
  39. package/dist/{push-policy-plan-jXzHAWSu.js → push-policy-plan-CvX8hiPb.js} +2 -2
  40. package/dist/{push-policy-plan-jXzHAWSu.js.map → push-policy-plan-CvX8hiPb.js.map} +1 -1
  41. package/dist/schema/doctor-cli.js +2 -2
  42. package/dist/schema/introspect-db.js +1 -1
  43. package/dist/services/BranchService.d.ts +40 -4
  44. package/dist/{websocket-BT85Yv_G.js → websocket-MC0zTBar.js} +3 -3
  45. package/dist/{websocket-BT85Yv_G.js.map → websocket-MC0zTBar.js.map} +1 -1
  46. package/package.json +7 -7
  47. package/dist/BranchService-DO_3_CXt.js.map +0 -1
  48. package/dist/backup-service-DytMimsL.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rebasepro/server-postgres",
3
- "version": "0.25.0-canary.g70dad01",
3
+ "version": "0.25.0",
4
4
  "description": "PostgreSQL data source backend implementation for Rebase with Drizzle ORM",
5
5
  "keywords": [
6
6
  "cms",
@@ -50,11 +50,11 @@
50
50
  "execa": "^9.6.1",
51
51
  "pg": "^8.22.0",
52
52
  "ws": "^8.21.1",
53
- "@rebasepro/codegen": "0.25.0-canary.g70dad01",
54
- "@rebasepro/common": "0.25.0-canary.g70dad01",
55
- "@rebasepro/server": "0.25.0-canary.g70dad01",
56
- "@rebasepro/types": "0.25.0-canary.g70dad01",
57
- "@rebasepro/utils": "0.25.0-canary.g70dad01"
53
+ "@rebasepro/codegen": "0.25.0",
54
+ "@rebasepro/server": "0.25.0",
55
+ "@rebasepro/types": "0.25.0",
56
+ "@rebasepro/utils": "0.25.0",
57
+ "@rebasepro/common": "0.25.0"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@electric-sql/pglite": "0.5.6",
@@ -70,7 +70,7 @@
70
70
  "typescript": "^6.0.3",
71
71
  "vite": "^8.1.5",
72
72
  "vitest": "^4.1.11",
73
- "@rebasepro/client": "0.25.0-canary.g70dad01"
73
+ "@rebasepro/client": "0.25.0"
74
74
  },
75
75
  "gitHead": "d935eefa5aa8d1009a2398cfac2c1e4ee9aeb6b6",
76
76
  "publishConfig": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"BranchService-DO_3_CXt.js","names":[],"sources":["../src/services/BranchService.ts"],"sourcesContent":["/**\n * BranchService\n *\n * Manages database branching by creating/deleting PostgreSQL databases\n * using `CREATE DATABASE ... TEMPLATE`. Branch metadata is stored in the\n * `rebase.branches` table in the default (main) database, following the\n * same `rebase` schema convention used by entity_history, auth, etc.\n */\n\nimport { sql } from \"drizzle-orm\";\nimport { BranchInfo } from \"@rebasepro/types\";\nimport { revokeInternalTableSql } from \"@rebasepro/common\";\nimport { DrizzleClient } from \"../interfaces\";\nimport { BranchRow } from \"../branch-prune\";\nimport { DatabasePoolManager } from \"../databasePoolManager\";\nimport { extractPgError, extractCauseMessage } from \"../utils/pg-error-utils\";\n\n/** Internal prefix applied to branch database names to avoid collisions. */\nconst BRANCH_DB_PREFIX = \"rb_\";\n\n/** `duplicate_database` — the target database name is already taken. */\nconst PG_DUPLICATE_DATABASE = \"42P04\";\n\n/** `object_in_use` — the database still has connections attached. */\nconst PG_OBJECT_IN_USE = \"55006\";\n\n/** How many times `--force` disconnects the other sessions before it reports one still there. */\nconst FORCE_ATTEMPTS = 3;\n\n/** The database every Postgres server has, from which another one can be closed and opened. */\nconst MAINTENANCE_DATABASE = \"postgres\";\n\n/**\n * Describe a failed branch DDL statement in terms a user can act on.\n *\n * Drizzle reports failures as `Failed query: <sql> params:` and hides the real\n * PostgreSQL error in the `cause` chain, so matching on `err.message` never sees\n * the actual problem. Match on the PG error code instead — it survives wrapping\n * and, unlike the message text, is not locale-dependent.\n */\nfunction describeBranchDdlError(err: unknown, fallbackContext: string): Error {\n const pgError = extractPgError(err);\n\n if (pgError?.code === PG_DUPLICATE_DATABASE) {\n return new Error(`Database \"${fallbackContext}\" already exists on the server. Choose a different branch name.`);\n }\n if (pgError?.code === PG_OBJECT_IN_USE) {\n return new Error(\n `Cannot complete the operation: the database \"${fallbackContext}\" has active connections. ` +\n \"Close other clients or connections and try again.\"\n );\n }\n\n // Unknown failure: surface the real PG message rather than the Drizzle\n // wrapper, which would otherwise show the raw SQL and no reason at all.\n const detail = pgError?.message ?? extractCauseMessage(err);\n if (detail) return new Error(detail);\n return err instanceof Error ? err : new Error(String(err));\n}\n\n/** Fully-qualified metadata table in the rebase schema. */\nconst BRANCHES_TABLE = \"rebase.branches\";\n\n/**\n * The connected server cannot branch, so nothing was done.\n *\n * A refusal, not a fault: typed so the transports can forward it intact.\n * `websocket.ts` answers it with its own code and message rather than letting\n * it fall into the generic handler, which suppresses the text in production —\n * and the text is the only part that says what to do instead.\n */\nexport class BranchingUnsupportedError extends Error {\n /** Wire code, forwarded verbatim to the client. */\n readonly code = \"BRANCHING_UNSUPPORTED\";\n\n constructor(message: string) {\n super(message);\n this.name = \"BranchingUnsupportedError\";\n }\n}\n\n/**\n * What to say when the server serves one database.\n *\n * Deliberately the same argument the CLI's `refuseBranchOnManagedDatabase`\n * makes, because it is the same refusal — it just used to be available only to\n * whoever came in through argv. One paragraph, because this one has to fit in a\n * toast as well as a terminal.\n */\nconst BRANCHING_UNSUPPORTED_MESSAGE =\n \"Branching does not work on the managed development database. It copies a database with \"\n + \"CREATE DATABASE ... TEMPLATE, and the managed database is PGlite, which serves exactly one — \"\n + \"the copy would be the original, and every write you meant to sandbox would land in it. \"\n + \"Branching needs a real Postgres: run `rebase dev --docker`, or uncomment DATABASE_URL in .env \"\n + \"to point at your own.\";\n\n/**\n * Validate that a user-provided identifier only contains safe characters.\n * Throws if the value contains characters outside [a-zA-Z0-9_-].\n */\nfunction validateIdentifier(value: string, label: string): void {\n if (!/^[a-zA-Z0-9_-]+$/.test(value)) {\n throw new Error(`Invalid ${label}: only letters, digits, underscores, and hyphens are allowed.`);\n }\n}\n\n/**\n * Postgres truncates identifiers at NAMEDATALEN-1 = 63 bytes, and does it\n * silently. The prefix comes out of the same budget.\n */\nconst MAX_BRANCH_NAME_LENGTH = 63 - BRANCH_DB_PREFIX.length;\n\n/**\n * Check a user-provided branch name, and otherwise leave it exactly as given.\n *\n * This used to strip everything outside [a-zA-Z0-9_], so `my-feature` was\n * quietly created as `myfeature`: the name you typed was not the name `list`\n * gave back. Nothing ever needed that. Every identifier this service builds is\n * double-quoted (see `CREATE DATABASE` below), which is what makes a hyphen\n * safe, and `validateIdentifier` has always accepted hyphens for the `--from`\n * source database — the two disagreed about the same character class.\n *\n * Refusing a name we cannot represent is better than representing a different\n * one, which is also why the length is checked here rather than left to\n * Postgres, whose answer to an over-long identifier is a silent rename.\n */\nfunction assertValidBranchName(name: string): void {\n validateIdentifier(name, \"branch name\");\n if (name.length > MAX_BRANCH_NAME_LENGTH) {\n throw new Error(\n `Branch name \"${name}\" is too long: ${name.length} characters, maximum ${MAX_BRANCH_NAME_LENGTH}. ` +\n \"Postgres truncates identifiers past 63 bytes, which would give the branch a name you did not choose.\"\n );\n }\n}\n\n/**\n * Convert a user-facing branch name to the actual PostgreSQL database name.\n */\nfunction toBranchDbName(name: string): string {\n assertValidBranchName(name);\n return `${BRANCH_DB_PREFIX}${name}`;\n}\n\n/**\n * Where a server's branches are kept: the main database — what a branch is\n * copied from unless told otherwise, and what may never be dropped — and the\n * connection whose `rebase.branches` records them.\n */\nexport interface BranchHome {\n /** The main database's name. */\n database(): Promise<string>;\n /**\n * A connection on the database the registry is in. Asked for at each use:\n * a pool to the main database is closed before it is copied.\n */\n registry(): Promise<DrizzleClient>;\n}\n\nexport class BranchService {\n private readonly home: BranchHome;\n\n /**\n * @param db A connection on the server the branches are made on. Branch\n * DDL runs here.\n * @param home Where branches are kept. Without one, the database the\n * pool manager's connection string names, and `db`'s registry.\n */\n constructor(\n private db: DrizzleClient,\n private poolManager: DatabasePoolManager,\n home?: BranchHome\n ) {\n this.home = home ?? {\n database: async () => poolManager.defaultDatabaseName,\n registry: async () => db\n };\n }\n\n /**\n * Refuse a branch mutation the connected server cannot honour.\n *\n * The check lives here rather than in the CLI's argv parsing because the\n * CLI is not the only caller: Studio reaches `createBranch` over the\n * websocket, and before this it got \"Branch created successfully\" and a\n * detail pane promising isolation for a database that is the parent.\n *\n * Reads only, and only mutations are guarded: `listBranches` on a managed\n * database is an honest empty list, and refusing it would turn the Branches\n * pane into a failure with a \"Try again\" that can never succeed.\n */\n private async assertBranchingSupported(): Promise<void> {\n if (await this.poolManager.servesOneDatabase()) {\n throw new BranchingUnsupportedError(BRANCHING_UNSUPPORTED_MESSAGE);\n }\n }\n\n /**\n * Whether the `rebase.branches` registry exists. A database that has never\n * had a branch made on it may not have it, and reading it there is an\n * empty answer, not an error — nor a reason to create it. The CLI's `list`\n * and `info` ask this rather than running the DDL that creates it.\n */\n async hasBranchRegistry(): Promise<boolean> {\n const result = await (await this.home.registry()).execute(\n sql`SELECT to_regclass('rebase.branches') IS NOT NULL AS present`\n );\n const [row] = result.rows;\n return row !== undefined && Reflect.get(row, \"present\") === true;\n }\n\n /**\n * Ensure the `rebase.branches` metadata table exists in the default database.\n * Idempotent — safe to call on every startup.\n */\n async ensureBranchMetadataTable(): Promise<void> {\n // Create the rebase schema (idempotent — may already exist from auth/history init)\n const registry = await this.home.registry();\n await registry.execute(sql`CREATE SCHEMA IF NOT EXISTS rebase`);\n\n await registry.execute(sql.raw(`\n CREATE TABLE IF NOT EXISTS ${BRANCHES_TABLE} (\n name TEXT PRIMARY KEY,\n db_name TEXT NOT NULL UNIQUE,\n parent_db TEXT NOT NULL,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n metadata JSONB DEFAULT '{}'\n );\n `));\n\n // Not a collection, so no RLS — and it names every branch database on\n // this server. The driver's schema-wide grant reaches it, so revoke.\n await registry.execute(sql.raw(revokeInternalTableSql(\"rebase\", \"branches\")));\n }\n\n /**\n * Create a new branch database by templating the source database.\n *\n * Uses `CREATE DATABASE ... TEMPLATE` for an instant, full-fidelity copy\n * of both schema and data.\n *\n * @param name User-facing branch name (e.g., \"feature_auth\")\n * @param options.source Source database to clone; defaults to the main database.\n */\n async createBranch(\n name: string,\n options?: { source?: string; force?: boolean }\n ): Promise<BranchInfo> {\n await this.assertBranchingSupported();\n\n if (options?.source) {\n validateIdentifier(options.source, \"source database name\");\n }\n\n const dbName = toBranchDbName(name);\n const sourceDb = options?.source || await this.home.database();\n\n // Check if branch already exists\n const existing = await (await this.home.registry()).execute(\n sql`SELECT name FROM rebase.branches WHERE name = ${name} OR db_name = ${dbName}`\n );\n if ((existing.rows as unknown[]).length > 0) {\n throw new Error(`Branch \"${name}\" already exists.`);\n }\n\n // Disconnect any idle pools to the source DB so TEMPLATE works.\n // CREATE DATABASE ... TEMPLATE requires no other connections to the template.\n //\n // This only reaches pools inside *this* process. The CLI runs as its own\n // process, so a `rebase dev` holding the database open is untouched by\n // it — which is why the failure below has to name what is connected, and\n // why `--force` exists.\n await this.poolManager.disconnectDatabase(sourceDb);\n\n // Create the database using the source as a template.\n // Note: Identifiers must be double-quoted, not parameterized.\n const safeDbName = dbName.replace(/\"/g, '\"\"');\n const safeSourceDb = sourceDb.replace(/\"/g, '\"\"');\n const copy = async (): Promise<void> => {\n await this.db.execute(sql.raw(`CREATE DATABASE \"${safeDbName}\" TEMPLATE \"${safeSourceDb}\"`));\n };\n try {\n if (options?.force) {\n await this.whileClosedToNewConnections(sourceDb, () => this.disconnectingOthers(sourceDb, copy));\n } else {\n await copy();\n }\n } catch (err) {\n const pgError = extractPgError(err);\n if (pgError?.code === PG_OBJECT_IN_USE) {\n // The template — not the new database — is the one still in use.\n throw new Error(\n `Cannot create branch: the source database \"${sourceDb}\" ${options?.force\n ? \"still had connections after they were disconnected\"\n : \"has active connections\"}.\\n`\n + await this.describeBlockingConnections(sourceDb, { forced: options?.force === true })\n );\n }\n throw describeBranchDdlError(err, dbName);\n }\n\n // Record metadata in the registry — asked for again, as copying the\n // main database closed any pool on it.\n const now = new Date();\n await (await this.home.registry()).execute(\n sql`INSERT INTO rebase.branches (name, db_name, parent_db, created_at)\n VALUES (${name}, ${dbName}, ${sourceDb}, ${now.toISOString()})`\n );\n\n return {\n name,\n database: dbName,\n parentDatabase: sourceDb,\n createdAt: now\n };\n }\n\n /**\n * Delete a branch database and remove its metadata.\n * Cannot delete the main/default database.\n */\n async deleteBranch(name: string, options?: { force?: boolean }): Promise<void> {\n await this.assertBranchingSupported();\n\n assertValidBranchName(name);\n\n // Safety, first pass: a request that would target the default database\n // is refused before any metadata is read, so the answer costs nothing\n // and cannot depend on what a row happens to say.\n const mainDatabase = await this.home.database();\n if (toBranchDbName(name) === mainDatabase) {\n throw new Error(\"Cannot delete the main database.\");\n }\n\n // Verify the branch exists, and take the database name from the row\n // rather than deriving it again. A branch created before names stopped\n // being stripped is recorded as `rb_myfeature` while `my-feature` now\n // derives `rb_my-feature`; re-deriving would drop a database this row\n // never named — or, if that name happened to exist, somebody else's.\n // The stored value is the only one that is true by construction.\n const existing = await (await this.home.registry()).execute(\n sql`SELECT db_name FROM rebase.branches WHERE name = ${name}`\n );\n const existingRows = existing.rows as Record<string, unknown>[];\n if (existingRows.length === 0) {\n throw new Error(`Branch \"${name}\" not found.`);\n }\n const dbName = existingRows[0].db_name as string;\n\n // Safety, second pass: the first checked a name we derived, this checks\n // the one we are about to drop. They differ for any row written under\n // the old scheme, and it is this one that governs.\n if (dbName === mainDatabase) {\n throw new Error(\"Cannot delete the main database.\");\n }\n\n // Disconnect any pools to this branch before dropping. Same limit as\n // `createBranch`: in-process pools only.\n await this.poolManager.disconnectDatabase(dbName);\n\n // Drop the database\n const safeDbName = dbName.replace(/\"/g, '\"\"');\n const drop = async (): Promise<void> => {\n await this.db.execute(sql.raw(`DROP DATABASE \"${safeDbName}\"`));\n };\n try {\n if (options?.force) await this.disconnectingOthers(dbName, drop);\n else await drop();\n } catch (err) {\n const pgError = extractPgError(err);\n if (pgError?.code === PG_OBJECT_IN_USE) {\n throw new Error(\n `Cannot delete branch \"${name}\": the database ${options?.force\n ? \"still had connections after they were disconnected\"\n : \"has active connections\"}.\\n`\n + await this.describeBlockingConnections(dbName, { forced: options?.force === true })\n );\n }\n throw describeBranchDdlError(err, dbName);\n }\n\n // Remove metadata\n await (await this.home.registry()).execute(\n sql`DELETE FROM rebase.branches WHERE name = ${name}`\n );\n }\n\n /**\n * Who is holding the database open, in words a developer can act on.\n *\n * `CREATE DATABASE ... TEMPLATE` and `DROP DATABASE` both require that no\n * other session is connected, and the one thing the old message could not\n * say is the only thing worth knowing: *which* session. \"Close other\n * clients or connections and try again\" is advice you cannot follow when\n * you do not know there is a `rebase dev` in another terminal — and that is\n * the common case, because wanting a branch and running the app are the\n * same moment.\n *\n * `application_name` is the useful column: node-postgres sends none by\n * default, so a Rebase process shows as `(unnamed)` while DBeaver, pgAdmin\n * and psql all name themselves. Counting by it separates \"my own dev\n * server\" from \"the GUI I forgot about\" without any guessing.\n *\n * Best-effort by construction: this runs while reporting a failure, and a\n * diagnostic that throws would replace a real error with its own.\n */\n private async describeBlockingConnections(dbName: string, options: { forced?: boolean } = {}): Promise<string> {\n try {\n const result = await this.db.execute(sql`\n SELECT coalesce(nullif(application_name, ''), '(unnamed)') AS app,\n count(*)::int AS n\n FROM pg_stat_activity\n WHERE datname = ${dbName}\n AND pid <> pg_backend_pid()\n GROUP BY 1\n ORDER BY 2 DESC, 1\n `);\n const rows = result.rows as Record<string, unknown>[];\n if (rows.length === 0) {\n // The blocker went away between the failure and this query, or\n // it is a session Postgres does not attribute to this database.\n return \" Retry — whatever was connected has since disconnected.\";\n }\n\n const listed = rows\n .map((row) => ` ${row.n} × ${String(row.app)}`)\n .join(\"\\n\");\n\n // With --force they were disconnected already, and came back: the\n // one thing left to say is what to stop, not to pass --force.\n return ` Connected right now:\\n${listed}\\n`\n + (options.forced\n ? \" They reconnected as fast as they were disconnected. A running `rebase dev` is the\\n\"\n + \" usual one — stop it, then run this again.\"\n : \" A running `rebase dev` is the usual one — stop it, or re-run with --force to\\n\"\n + \" disconnect them for you.\");\n } catch {\n return options.forced\n ? \" Stop the clients connected to it — a running `rebase dev` is the usual one — then run this again.\"\n : \" Close other clients and connections, or re-run with --force.\";\n }\n }\n\n /**\n * Run `operation` with no other session on `dbName`, disconnecting them\n * first: what `--force` asks for.\n *\n * Disconnected, a client that reconnects — a running `rebase dev`'s\n * realtime listener does — can be back before `CREATE DATABASE … TEMPLATE`\n * or `DROP DATABASE` counts the sessions, and it failed on one about once\n * in seven tries, saying to pass the `--force` that had been passed. So a\n * refusal on a session still connected is retried, disconnecting again, a\n * few times before it is reported.\n */\n private async disconnectingOthers(dbName: string, operation: () => Promise<void>): Promise<void> {\n for (let attempt = 1; ; attempt++) {\n const closed = await this.terminateConnections(dbName);\n if (closed > 0) {\n // Postgres reports the backend as gone before its slot is\n // actually free, and the operation then fails on a connection\n // that no longer exists. A short settle first.\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n try {\n await operation();\n return;\n } catch (err) {\n if (attempt >= FORCE_ATTEMPTS || extractPgError(err)?.code !== PG_OBJECT_IN_USE) throw err;\n }\n }\n }\n\n /**\n * Run `operation` with `dbName` refusing new connections, and open it\n * again after, whatever happens.\n *\n * A client disconnected from the source — a running `rebase dev` holds a\n * pool and a realtime listener — cannot then reconnect before the copy has\n * counted the sessions on it. Postgres refuses `ALLOW_CONNECTIONS false` on\n * the database a session is connected to, so both statements run from the\n * server's `postgres` database, and they need the database's owner. Where\n * either is missing, the retries of {@link disconnectingOthers} are what is\n * left. A database that already refused connections is left as it was.\n *\n * Interrupted (Ctrl-C) while closed, it opens the database again before\n * the process exits; one it could not open is named in the error, with the\n * statement that does.\n */\n private async whileClosedToNewConnections(dbName: string, operation: () => Promise<void>): Promise<void> {\n const safe = dbName.replace(/\"/g, '\"\"');\n const maintenance = dbName === MAINTENANCE_DATABASE ? null : this.poolManager.getDrizzle(MAINTENANCE_DATABASE);\n let closed = false;\n try {\n if (maintenance) {\n const state = await maintenance.execute(sql`SELECT datallowconn FROM pg_database WHERE datname = ${dbName}`);\n const [row] = state.rows as Record<string, unknown>[];\n if (row?.datallowconn === true) {\n await maintenance.execute(sql.raw(`ALTER DATABASE \"${safe}\" ALLOW_CONNECTIONS false`));\n closed = true;\n }\n }\n } catch {\n // No `postgres` database to run it from, or not the owner.\n }\n if (!closed) {\n await this.poolManager.disconnectDatabase(MAINTENANCE_DATABASE);\n await operation();\n return;\n }\n\n let reopening: Promise<void> | undefined;\n const reopen = (): Promise<void> => {\n reopening ??= this.reopenToConnections(dbName);\n return reopening;\n };\n const onSignal = (signal: NodeJS.Signals): void => {\n void reopen().finally(() => process.kill(process.pid, signal));\n };\n process.once(\"SIGINT\", onSignal);\n process.once(\"SIGTERM\", onSignal);\n try {\n await operation();\n } finally {\n process.removeListener(\"SIGINT\", onSignal);\n process.removeListener(\"SIGTERM\", onSignal);\n await reopen();\n }\n }\n\n /** `ALLOW_CONNECTIONS true` again, from the maintenance database, or an error that says how to do it by hand. */\n private async reopenToConnections(dbName: string): Promise<void> {\n const statement = `ALTER DATABASE \"${dbName.replace(/\"/g, '\"\"')}\" ALLOW_CONNECTIONS true`;\n try {\n await this.poolManager.getDrizzle(MAINTENANCE_DATABASE).execute(sql.raw(statement));\n } catch (err) {\n throw new Error(\n `\"${dbName}\" was closed to new connections for the copy and could not be opened again ` +\n `(${extractPgError(err)?.message ?? extractCauseMessage(err) ?? String(err)}). ` +\n `Nothing can connect to it until you run, from another database: ${statement};`\n );\n } finally {\n await this.poolManager.disconnectDatabase(MAINTENANCE_DATABASE);\n }\n }\n\n /**\n * Disconnect every other session on a database, and say how many.\n *\n * `pg_terminate_backend` rather than `pg_cancel_backend`: cancelling a\n * query leaves the session connected, and a connected session is exactly\n * what blocks the operation.\n *\n * The current backend is excluded — terminating the connection running this\n * statement would abort the command that asked for it.\n */\n private async terminateConnections(dbName: string): Promise<number> {\n const result = await this.db.execute(sql`\n SELECT pg_terminate_backend(pid)\n FROM pg_stat_activity\n WHERE datname = ${dbName}\n AND pid <> pg_backend_pid()\n `);\n\n return (result.rows as unknown[]).length;\n }\n\n /**\n * Everything prune needs to decide, in two queries.\n *\n * Reads the rows and the server's database list rather than joining them,\n * so the *disagreements* between the two are visible — a row whose database\n * is gone and a database with no row are the two things prune exists to\n * find, and a join hides both.\n */\n async pruneCandidates(): Promise<{ rows: BranchRow[]; databases: string[] }> {\n const rowResult = await (await this.home.registry()).execute(sql.raw(`\n SELECT name, db_name, created_at FROM ${BRANCHES_TABLE} ORDER BY created_at\n `));\n const rows = (rowResult.rows as Record<string, unknown>[]).map((row) => ({\n name: row.name as string,\n dbName: row.db_name as string,\n createdAt: new Date(row.created_at as string)\n }));\n\n const dbResult = await this.db.execute(sql`\n SELECT datname FROM pg_database WHERE NOT datistemplate\n `);\n const databases = (dbResult.rows as Record<string, unknown>[]).map((row) => String(row.datname));\n\n return { rows, databases };\n }\n\n /** Remove a metadata row whose database is already gone. */\n async forgetBranchRow(name: string): Promise<void> {\n await (await this.home.registry()).execute(sql`DELETE FROM rebase.branches WHERE name = ${name}`);\n }\n\n /**\n * Drop a database by name, with no metadata row required.\n *\n * `deleteBranch` deliberately takes its database name from the row, because\n * the row is the only value that is true by construction. Prune has the\n * opposite job — the cases it handles are exactly the ones where row and\n * database disagree — so it needs to name a database directly. Guarded the\n * same way regardless: the main database is never droppable.\n */\n async dropDatabase(dbName: string): Promise<void> {\n validateIdentifier(dbName, \"database name\");\n if (dbName === await this.home.database()) {\n throw new Error(\"Cannot delete the main database.\");\n }\n\n await this.poolManager.disconnectDatabase(dbName);\n try {\n await this.db.execute(sql.raw(`DROP DATABASE \"${dbName.replace(/\"/g, '\"\"')}\"`));\n } catch (err) {\n throw describeBranchDdlError(err, dbName);\n }\n }\n\n /**\n * List all branches recorded in the metadata table.\n * Optionally fetches database sizes from pg_database.\n */\n async listBranches(): Promise<BranchInfo[]> {\n const result = await (await this.home.registry()).execute(sql.raw(`\n SELECT \n b.name,\n b.db_name,\n b.parent_db,\n b.created_at,\n pg_database_size(b.db_name) as size_bytes\n FROM ${BRANCHES_TABLE} b\n JOIN pg_database d ON d.datname = b.db_name\n ORDER BY b.created_at DESC\n `));\n\n return (result.rows as Record<string, unknown>[]).map((row) => ({\n name: row.name as string,\n database: row.db_name as string,\n parentDatabase: row.parent_db as string,\n createdAt: new Date(row.created_at as string),\n sizeBytes: row.size_bytes != null ? Number(row.size_bytes) : undefined\n }));\n }\n\n /**\n * Get info about a specific branch.\n */\n async getBranchInfo(name: string): Promise<BranchInfo | undefined> {\n assertValidBranchName(name);\n\n const result = await (await this.home.registry()).execute(sql`\n SELECT\n b.name,\n b.db_name,\n b.parent_db,\n b.created_at\n FROM rebase.branches b\n WHERE b.name = ${name}\n `);\n\n const rows = result.rows as Record<string, unknown>[];\n if (rows.length === 0) return undefined;\n\n const row = rows[0];\n\n // Attempt to get size — may fail if the DB was externally dropped.\n // Same reason as `deleteBranch`: the size of a re-derived name is the\n // size of some other database, or of nothing.\n let sizeBytes: number | undefined;\n try {\n const dbName = row.db_name as string;\n const sizeResult = await this.db.execute(\n sql`SELECT pg_database_size(${dbName}) as size_bytes`\n );\n const sizeRows = sizeResult.rows as Record<string, unknown>[];\n if (sizeRows.length > 0 && sizeRows[0].size_bytes != null) {\n sizeBytes = Number(sizeRows[0].size_bytes);\n }\n } catch {\n // Database might not exist anymore\n }\n\n return {\n name: row.name as string,\n database: row.db_name as string,\n parentDatabase: row.parent_db as string,\n createdAt: new Date(row.created_at as string),\n sizeBytes\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkBA,IAAM,mBAAmB;;AAGzB,IAAM,wBAAwB;;AAG9B,IAAM,mBAAmB;;AAGzB,IAAM,iBAAiB;;AAGvB,IAAM,uBAAuB;;;;;;;;;AAU7B,SAAS,uBAAuB,KAAc,iBAAgC;CAC1E,MAAM,UAAU,eAAe,GAAG;CAElC,IAAI,SAAS,SAAS,uBAClB,uBAAO,IAAI,MAAM,aAAa,gBAAgB,gEAAgE;CAElH,IAAI,SAAS,SAAS,kBAClB,uBAAO,IAAI,MACP,gDAAgD,gBAAgB,4EAEpE;CAKJ,MAAM,SAAS,SAAS,WAAW,oBAAoB,GAAG;CAC1D,IAAI,QAAQ,OAAO,IAAI,MAAM,MAAM;CACnC,OAAO,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAC7D;;AAGA,IAAM,iBAAiB;;;;;;;;;AAUvB,IAAa,4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,UAAU;EAEjD,QAAQ,CAER;EAEA,OAAO;GACH,MAAM,IAAI;GACV,UAAU,IAAI;GACd,gBAAgB,IAAI;GACpB,WAAW,IAAI,KAAK,IAAI,UAAoB;GAC5C;EACJ;CACJ;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"backup-service-DytMimsL.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/** The schemas and tables a dump creates, read off its table of contents. */\nexport interface DumpObjects {\n schemas: string[];\n tables: { schema: string; table: string }[];\n /**\n * Every relation it creates — tables, views, materialized views, foreign\n * tables and sequences — by schema and name: what `restore --clean` can\n * tell apart from what the target holds besides.\n */\n relations: { schema: string; name: string }[];\n}\n\n/** `<id>; <catalog oid> <oid> <description> <namespace> <tag…> <owner>`, the shape of a TOC entry. */\nconst TOC_ENTRY = /^\\d+;\\s+\\d+\\s+\\d+\\s+(SCHEMA|TABLE)\\s+(?!DATA\\s)(\\S+)\\s+(.+)\\s+(\\S+)$/;\n\n/** A TOC entry for a relation of any kind. `TABLE DATA`, `SEQUENCE SET` and `SEQUENCE OWNED BY` are not relations. */\nconst TOC_RELATION = /^\\d+;\\s+\\d+\\s+\\d+\\s+(?:FOREIGN TABLE|MATERIALIZED VIEW|TABLE|VIEW|SEQUENCE)\\s+(?!DATA\\s|SET\\s|OWNED BY\\s)(\\S+)\\s+(.+)\\s+(\\S+)$/;\n\n/**\n * The schemas and tables in `pg_restore --list` output: the objects a\n * restore without `--clean` fails on when the target already has them.\n *\n * A TOC line ends in the object's owner, after its namespace and its name;\n * a schema's namespace is `-`. The name is what lies between the two, so a\n * name with a space in it (`Odd Name`) reads whole. `TABLE DATA` and every\n * other kind of entry are not objects of their own here.\n */\nexport function parseDumpObjects(list: string): DumpObjects {\n const objects: DumpObjects = { schemas: [], tables: [], relations: [] };\n for (const line of list.split(\"\\n\")) {\n const trimmed = line.trim();\n const relation = TOC_RELATION.exec(trimmed);\n if (relation) objects.relations.push({ schema: relation[1], name: relation[2] });\n const entry = TOC_ENTRY.exec(trimmed);\n if (!entry) continue;\n const [, kind, namespace, name] = entry;\n if (kind === \"SCHEMA\") objects.schemas.push(name);\n else objects.tables.push({ schema: namespace, table: name });\n }\n return objects;\n}\n\n/** A Postgres identifier, double-quoted. */\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n\n/**\n * How long `restore --clean` waits for a lock before it gives up.\n *\n * A `rebase dev` serving from the database holds connections, and one inside a\n * transaction would otherwise make the restore wait without a word. The dump's\n * own script sets `lock_timeout = 0` after this, for the objects it creates.\n */\nexport const CLEAN_LOCK_TIMEOUT = \"15s\";\n\n/**\n * What `restore --clean` runs first, in the transaction the restore runs in:\n * every schema the dump creates, dropped with `CASCADE`, and every table it\n * creates in a schema it does not (`public`), the same.\n *\n * `CASCADE`, which `pg_restore --clean` never uses: a table the backup lacks\n * in one of its schemas — `rebase.atlas_schema_revisions` from `rebase db\n * migrate`, a table a newer runtime added — is exactly what stopped its plain\n * `DROP SCHEMA rebase`, and a table that references one of the backup's is what\n * stops a plain `DROP TABLE`. The dump's script follows, with its own `DROP …\n * IF EXISTS` for everything else it creates.\n */\nexport function cleanRestorePrelude(objects: DumpObjects): string[] {\n const schemas = objects.schemas.filter((schema) => schema !== \"public\");\n const dropped = new Set(schemas);\n const tables = objects.tables.filter((table) => !dropped.has(table.schema));\n return [\n \"SET client_min_messages = warning\",\n `SET lock_timeout = '${CLEAN_LOCK_TIMEOUT}'`,\n ...schemas.map((schema) => `DROP SCHEMA IF EXISTS ${quoteIdentifier(schema)} CASCADE`),\n ...tables.map((table) => `DROP TABLE IF EXISTS ${quoteIdentifier(table.schema)}.${quoteIdentifier(table.table)} CASCADE`)\n ];\n}\n\n/**\n * `pg_restore` writing the dump as a SQL script on stdout, with the `DROP …\n * IF EXISTS` that `--clean` adds, for `psql` to run. See {@link buildPsqlScriptArgs}.\n */\nexport function buildPgRestoreScriptArgs(opts: { inputFile: string; noOwner?: boolean }): string[] {\n return [\n \"--format=custom\",\n \"--clean\",\n \"--if-exists\",\n ...(opts.noOwner ? [\"--no-owner\"] : []),\n \"--file=-\",\n opts.inputFile\n ];\n}\n\n/**\n * `psql` running a script read from stdin, stopping at its first error.\n *\n * `-X`, so no `.psqlrc` changes what runs; `-q`, so it prints errors and\n * warnings, not a command tag per statement. The transaction is the script's\n * own: `restore --clean` writes the `BEGIN`, and the `COMMIT` only once\n * `pg_restore` has written the whole dump.\n */\nexport function buildPsqlScriptArgs(connectionString: string): string[] {\n return [\"-X\", \"-q\", \"--no-password\", \"-v\", \"ON_ERROR_STOP=1\", `--dbname=${forLibpq(connectionString)}`, \"--file=-\"];\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\" | \"psql\";\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 psql: \"PSQL_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` / `psql`, 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 { pgToolVariable, 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 buildPgRestoreScriptArgs,\n buildPsqlScriptArgs,\n cleanRestorePrelude,\n checkToolServerCompatibility,\n type DumpObjects,\n globalsFileForDump,\n joinStorageKey,\n parsePgToolMajor,\n parseBackupTimestamp,\n parseDumpObjects,\n serverVersionNumToMajor,\n VersionCompatibility\n} from \"./pg-tools\";\nimport { BackupObject, RetentionOptions, selectBackupsToPrune } from \"./retention\";\nimport { applyGlobalsWith, discardPartialDumpWith, pruneWith } from \"./backup-logic\";\nimport { splitPassword } from \"../utils/connection-string\";\n\n/**\n * How a libpq tool is invoked for a connection string: the URL its command\n * line carries, and the environment it runs in.\n *\n * The password goes in `PGPASSWORD`, never on the command line, where every\n * process listing could read it and every failure printed it back (execa's\n * error repeats the command). See {@link splitPassword}.\n */\nfunction libpqInvocation(\n connectionString: string,\n env: Record<string, string | undefined>\n): { connectionString: string; env: Record<string, string> } {\n const split = splitPassword(connectionString);\n const toolEnv: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n if (value !== undefined) toolEnv[key] = value;\n }\n if (split.password !== null) toolEnv.PGPASSWORD = split.password;\n return { connectionString: split.connectionString, env: toolEnv };\n}\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\n/** PGlite names itself in `version()`: `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`. */\nconst SHARED_SESSION_ENGINE = /\\(PGlite\\b/i;\n\n/**\n * Put back what a client tool left set on a database that is one session\n * every connection shares, and do nothing on any other.\n *\n * The managed development database is PGlite: one session behind a socket\n * server, so what `pg_dump` sets for itself — `search_path` emptied,\n * `row_security` off, `PREPARE dumpEnumType …` — stays set for every client\n * after it, a running `rebase dev` included. One `rebase db backup` there left\n * every API request answering 500 \"table does not exist\", a restart did not\n * help (the database outlives `rebase dev`), and the next backup failed on\n * `prepared statement \"dumpenumtype\" already exists`.\n *\n * `RESET ALL` and `DEALLOCATE ALL`, not `DISCARD ALL`: that would also drop\n * the `LISTEN` a running `rebase dev`'s realtime holds on the same session.\n * Best effort: it runs after the tool, whose own outcome is what the caller\n * reports.\n */\nexport async function resetSharedSession(connectionString: string): Promise<void> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString, connectionTimeoutMillis: 10_000, query_timeout: 15_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n const { rows } = await client.query<{ version: string }>(\"SELECT version() AS version\");\n if (!SHARED_SESSION_ENGINE.test(rows[0]?.version ?? \"\")) return;\n await client.query(\"RESET ALL\");\n await client.query(\"DEALLOCATE ALL\");\n } catch {\n // Nothing to add to the tool's own result; see above.\n } finally {\n await client.end().catch(() => undefined);\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 createOwnerOnly(localFile);\n\n const tool = libpqInvocation(opts.connectionString, env);\n const args = buildPgDumpArgs({\n connectionString: tool.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> = { ...tool.env };\n if (opts.rowSecurity) {\n dumpEnv.PGOPTIONS = [env.PGOPTIONS, buildRowSecurityPgOptions(opts.rowSecurity)]\n .filter(Boolean).join(\" \");\n }\n\n try {\n try {\n await execa(bin, args, {\n stdio: opts.inheritStdio ? \"inherit\" : \"pipe\",\n env: dumpEnv\n });\n } finally {\n await resetSharedSession(opts.connectionString);\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 createOwnerOnly(globalsFile);\n try {\n try {\n await execa(\n dumpallBin,\n buildPgDumpallGlobalsArgs({ connectionString: tool.connectionString, outFile: globalsFile }),\n { stdio: opts.inheritStdio ? \"inherit\" : \"pipe\", env: tool.env }\n );\n } finally {\n await resetSharedSession(opts.connectionString);\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 * Create `file` empty and readable by its owner only, before a tool writes it.\n *\n * A dump holds every row, and the `.globals.sql` sidecar every role's password\n * hash. pg_dump and pg_dumpall create their `--file=` target with the\n * process's umask — 0644 on most machines, readable by every user — and keep\n * the mode of a file that is already there. Created 0600 first, the file is\n * never readable by anyone else, not even while the dump runs; chmod-ing it\n * afterwards would leave it open for as long as that takes. A file that\n * already existed is narrowed too.\n */\nfunction createOwnerOnly(file: string): void {\n fs.closeSync(fs.openSync(file, \"w\", 0o600));\n fs.chmodSync(file, 0o600);\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 tool = libpqInvocation(opts.connectionString, env);\n const args = buildPgRestoreArgs({\n connectionString: tool.connectionString,\n inputFile: opts.inputFile,\n clean: opts.clean,\n noOwner: opts.noOwner,\n exitOnError: opts.exitOnError\n });\n try {\n await execa(bin, args, {\n stdio: opts.inheritStdio ? \"inherit\" : \"pipe\",\n env: tool.env\n });\n } finally {\n await resetSharedSession(opts.connectionString);\n }\n}\n\n/**\n * A `restore --clean` that stopped, and so was rolled back whole.\n *\n * `tool` is the one that stopped it: `pg_restore`, writing the dump's script,\n * or `psql`, running it. `lockTimeout` when what `psql` stopped on was the\n * wait for a lock — `CLEAN_LOCK_TIMEOUT` in `pg-tools.ts`.\n */\nexport class CleanRestoreFailed extends Error {\n constructor(\n readonly tool: \"pg_restore\" | \"psql\",\n readonly exitCode: number | undefined,\n readonly lockTimeout: boolean\n ) {\n super(`${tool} exited with code ${exitCode ?? \"unknown\"}`);\n this.name = \"CleanRestoreFailed\";\n }\n}\n\n/**\n * Restore a dump over what the database holds, as one transaction:\n * {@link cleanRestorePrelude} first, then the dump as `pg_restore` writes it\n * for `psql`, and the `COMMIT` only after the last of it.\n *\n * One unit, so it either replaces what the dump holds or changes nothing:\n * `pg_restore --clean` runs each statement on its own, so the drops it starts\n * with had all happened when a later one failed — and its plain `DROP SCHEMA\n * rebase` fails on any table the backup lacks, which left a database with\n * every table dropped and nothing restored. Here a failure anywhere —\n * `pg_restore` cannot read the archive, a statement fails, the connection\n * drops — ends the transaction without a `COMMIT`, and Postgres rolls it back.\n *\n * Throws {@link CleanRestoreFailed} when it did not commit.\n */\nexport async function restoreDumpReplacing(opts: {\n connectionString: string;\n inputFile: string;\n objects: DumpObjects;\n noOwner?: boolean;\n inheritStdio?: boolean;\n env?: Record<string, string | undefined>;\n}): Promise<void> {\n const env = opts.env ?? process.env;\n const restoreBin = resolvePgBinary(\"pg_restore\", env);\n const psqlBin = resolvePgBinary(\"psql\", env);\n if (!restoreBin || !psqlBin) {\n const tool = restoreBin ? \"psql\" : \"pg_restore\";\n throw new BackupToolError(\n `Could not find the '${tool}' binary${tool === \"psql\" ? \", which runs a --clean restore as one transaction\" : \"\"}.`,\n `Install the PostgreSQL client tools or set ${pgToolVariable(tool)}.`\n );\n }\n const tool = libpqInvocation(opts.connectionString, env);\n\n const script = execa(restoreBin, buildPgRestoreScriptArgs({ inputFile: opts.inputFile, noOwner: opts.noOwner }), {\n stdin: \"ignore\",\n stdout: \"pipe\",\n stderr: opts.inheritStdio ? \"inherit\" : \"ignore\",\n buffer: false,\n reject: false,\n env: tool.env\n });\n // stdout is the rows of the script's own `SELECT`s (`set_config`,\n // `setval`), which say nothing. stderr is shown as it arrives and kept, to\n // tell a lock timeout from anything else.\n const apply = execa(psqlBin, buildPsqlScriptArgs(tool.connectionString), {\n stdin: \"pipe\",\n stdout: \"ignore\",\n stderr: opts.inheritStdio ? [\"pipe\", \"inherit\"] : \"pipe\",\n reject: false,\n env: tool.env\n });\n\n const sink = apply.stdin;\n const source = script.stdout;\n if (!sink || !source) throw new BackupToolError(\"Could not connect pg_restore to psql.\");\n // psql stops reading at its first error, and the script behind it must not\n // wait on a pipe nobody drains.\n sink.on(\"error\", () => undefined);\n apply.once(\"exit\", () => {\n source.unpipe(sink);\n source.resume();\n script.kill();\n });\n\n sink.write([\"BEGIN\", ...cleanRestorePrelude(opts.objects)].map((statement) => `${statement};\\n`).join(\"\"));\n source.pipe(sink, { end: false });\n\n const written = await script;\n const committed = written.exitCode === 0 && sink.writable;\n sink.end(committed ? \"COMMIT;\\n\" : undefined);\n const applied = await apply;\n await resetSharedSession(opts.connectionString);\n\n if (applied.exitCode !== 0) {\n const stderr = typeof applied.stderr === \"string\" ? applied.stderr : \"\";\n throw new CleanRestoreFailed(\"psql\", applied.exitCode, /lock timeout/i.test(stderr));\n }\n if (!committed) throw new CleanRestoreFailed(\"pg_restore\", written.exitCode, false);\n}\n\n/**\n * What `restore --clean` drops that the backup does not hold, so it can say\n * so before it runs: the tables and views in a schema the backup replaces\n * whole that it has no copy of, and the views and foreign keys elsewhere that\n * reference one of the relations it replaces. As `<kind> <name>`.\n *\n * None for a database that does not exist yet.\n */\nexport async function findCleanExtras(connectionString: string, objects: DumpObjects): Promise<string[]> {\n const schemas = objects.schemas.filter((schema) => schema !== \"public\");\n if (schemas.length === 0 && objects.relations.length === 0) return [];\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString });\n try {\n await client.connect();\n } catch (err) {\n // 3D000: the database does not exist yet, as `--create-db` finds it.\n if (err instanceof Error && \"code\" in err && err.code === \"3D000\") return [];\n throw err;\n }\n try {\n const { rows } = await client.query<{ kind: string; name: string }>(\n `WITH dumped AS (\n SELECT c.oid\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN unnest($2::text[], $3::text[]) AS d(schema_name, rel_name)\n ON d.schema_name = n.nspname AND d.rel_name = c.relname\n )\n SELECT kind, name FROM (\n SELECT CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view'\n WHEN 'f' THEN 'foreign table' ELSE 'table' END AS kind,\n n.nspname || '.' || c.relname AS name\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY($1::text[])\n AND c.relkind IN ('r', 'p', 'v', 'm', 'f')\n AND c.oid NOT IN (SELECT oid FROM dumped)\n UNION\n SELECT 'view', vn.nspname || '.' || v.relname\n FROM pg_depend dep\n JOIN pg_rewrite r ON r.oid = dep.objid AND dep.classid = 'pg_rewrite'::regclass\n JOIN pg_class v ON v.oid = r.ev_class\n JOIN pg_namespace vn ON vn.oid = v.relnamespace\n WHERE dep.refobjid IN (SELECT oid FROM dumped)\n AND v.oid NOT IN (SELECT oid FROM dumped)\n AND NOT vn.nspname = ANY($1::text[])\n UNION\n SELECT 'foreign key', con.conname || ' on ' || cn.nspname || '.' || cr.relname\n FROM pg_constraint con\n JOIN pg_class cr ON cr.oid = con.conrelid\n JOIN pg_namespace cn ON cn.oid = cr.relnamespace\n WHERE con.contype = 'f'\n AND con.confrelid IN (SELECT oid FROM dumped)\n AND con.conrelid NOT IN (SELECT oid FROM dumped)\n AND NOT cn.nspname = ANY($1::text[])\n ) extra\n ORDER BY name`,\n [schemas, objects.relations.map((r) => r.schema), objects.relations.map((r) => r.name)]\n );\n return rows.map((row) => `${row.kind} ${row.name}`);\n } finally {\n await client.end();\n }\n}\n\n/** The schemas and tables a dump creates, from `pg_restore --list`. See {@link parseDumpObjects}. */\nexport async function readDumpObjects(\n inputFile: string,\n env: Record<string, string | undefined> = process.env\n): Promise<DumpObjects> {\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 toolEnv = Object.fromEntries(\n Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)\n );\n const { stdout } = await execa(bin, buildPgRestoreListArgs(inputFile), { stdio: \"pipe\", env: toolEnv });\n return parseDumpObjects(stdout);\n}\n\n/**\n * Which of a dump's schemas and tables the target database already holds,\n * as `schema <name>` / `table <schema>.<name>`: what a restore without\n * `--clean` would stop on. `public` is left out of the schemas — every\n * database has it, and pg_restore does not create it. None for a database\n * that does not exist yet.\n */\nexport async function findRestoreConflicts(connectionString: string, objects: DumpObjects): Promise<string[]> {\n const schemas = objects.schemas.filter((schema) => schema !== \"public\");\n if (schemas.length === 0 && objects.tables.length === 0) return [];\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString });\n try {\n await client.connect();\n } catch (err) {\n // 3D000: the database does not exist yet, as `--create-db` finds it.\n if (err instanceof Error && \"code\" in err && err.code === \"3D000\") return [];\n throw err;\n }\n try {\n const existingSchemas = await client.query<{ nspname: string }>(\n \"SELECT nspname FROM pg_namespace WHERE nspname = ANY($1::text[]) ORDER BY nspname\",\n [schemas]\n );\n const existingTables = await client.query<{ nspname: string; relname: string }>(\n `SELECT n.nspname, c.relname\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN unnest($1::text[], $2::text[]) AS d(schema_name, table_name)\n ON d.schema_name = n.nspname AND d.table_name = c.relname\n WHERE c.relkind IN ('r', 'p')\n ORDER BY n.nspname, c.relname`,\n [objects.tables.map((t) => t.schema), objects.tables.map((t) => t.table)]\n );\n return [\n ...existingSchemas.rows.map((row) => `schema ${row.nspname}`),\n ...existingTables.rows.map((row) => `table ${row.nspname}.${row.relname}`)\n ];\n } finally {\n await client.end();\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(toDelete, deleteObject);\n return toDelete;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,mBAAmB,kBAAyC;CACxE,IAAI;EAEA,MAAM,OAAO,IADM,IAAI,gBACV,CAAA,CAAO,SAAS,QAAQ,OAAO,EAAE,CAAC,CAAC,KAAK;EACrD,OAAO,KAAK,SAAS,IAAI,OAAO;CACpC,QAAQ;EAEJ,MAAM,QAAQ,iBAAiB,MAAM,kBAAkB;EACvD,OAAO,SAAS,MAAM,KAAK,MAAM,KAAK;CAC1C;AACJ;;;;;;AAOA,SAAgB,iBAAiB,kBAA0B,QAAwB;CAC/E,IAAI;EACA,MAAM,SAAS,IAAI,IAAI,gBAAgB;EACvC,OAAO,WAAW,IAAI;EACtB,OAAO,OAAO,SAAS;CAC3B,QAAQ;EACJ,OAAO,iBAAiB,QAAQ,oBAAoB,IAAI,OAAO,GAAG;CACtE;AACJ;;;;;;AAOA,SAAgB,iBAAiB,eAAsC;CACnE,MAAM,QAAQ,cAAc,MAAM,mBAAmB;CACrD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,QAAQ,OAAO,MAAM,EAAE;CAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO;CAEpC,IAAI,UAAU,KAAK,MAAM,OAAO,KAAA,GAC5B,OAAO;CAEX,OAAO;AACX;;;;;;AAOA,SAAgB,wBAAwB,YAA4C;CAChF,MAAM,MAAM,OAAO,eAAe,WAAW,OAAO,UAAU,IAAI;CAClE,IAAI,CAAC,OAAO,SAAS,GAAG,KAAK,OAAO,GAAG,OAAO;CAC9C,IAAI,MAAM,KAE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