backupdrill 2.11.2 → 2.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -2
- package/dist/auth-backup.d.ts +5 -14
- package/dist/auth-backup.js +6 -69
- package/dist/auth-restore.js +1 -1
- package/dist/backup.d.ts +15 -2
- package/dist/backup.js +146 -53
- package/dist/dir-store.d.ts +55 -0
- package/dist/dir-store.js +208 -0
- package/dist/drill.js +24 -3
- package/dist/estimate.js +7 -4
- package/dist/grants.js +4 -0
- package/dist/index.js +64 -20
- package/dist/lib.d.ts +7 -2
- package/dist/lib.js +6 -1
- package/dist/manifest.d.ts +27 -2
- package/dist/manifest.js +44 -1
- package/dist/orphaned-foreign-keys.js +8 -1
- package/dist/ping.d.ts +5 -0
- package/dist/ping.js +20 -0
- package/dist/recovery-doc.d.ts +6 -1
- package/dist/recovery-doc.js +53 -16
- package/dist/restore.js +33 -14
- package/dist/schema-patterns.d.ts +38 -0
- package/dist/schema-patterns.js +115 -0
- package/dist/snapshot-store.d.ts +19 -1
- package/dist/snapshot-store.js +17 -1
- package/dist/storage-restore.d.ts +2 -6
- package/dist/storage-restore.js +6 -13
- package/dist/storage.d.ts +81 -8
- package/dist/storage.js +456 -52
- package/package.json +1 -1
- package/plugin/README.md +2 -2
- package/plugin/skills/supabase-backup/SKILL.md +6 -6
- package/plugin/skills/supabase-backup/assets/scheduled-backup.yml +1 -1
package/README.md
CHANGED
|
@@ -21,6 +21,7 @@ This CLI gets your database into a bucket **you** control, with a manifest you c
|
|
|
21
21
|
## Requirements
|
|
22
22
|
|
|
23
23
|
- Node.js ≥ 20
|
|
24
|
+
- A source database on PostgreSQL 11 or newer (12 or newer for a separate `auth.dump`, see `BACKUPDRILL_AUTH` below). `backup` checks the version before it creates a snapshot.
|
|
24
25
|
- `pg_dump` whose **major version ≥ your Supabase Postgres version** (Supabase runs PG 15–17). On macOS: `brew install libpq` then add it to `PATH`, or point `BACKUPDRILL_PG_DUMP` at the binary. The CLI checks this and refuses to run a mismatched dump.
|
|
25
26
|
|
|
26
27
|
## Install
|
|
@@ -76,8 +77,8 @@ All recognized variables:
|
|
|
76
77
|
|---|---|---|
|
|
77
78
|
| `BACKUPDRILL_DATABASE_URL` | Source connection string (falls back to `DATABASE_URL`) | — (required) |
|
|
78
79
|
| `BACKUPDRILL_PROJECT_NAME` | Readable name used in object keys and the manifest | `supabase` |
|
|
79
|
-
| `BACKUPDRILL_SCHEMAS` | Comma-separated
|
|
80
|
-
| `BACKUPDRILL_AUTH` | Supabase Auth users
|
|
80
|
+
| `BACKUPDRILL_SCHEMAS` | Comma-separated `pg_dump --schema` patterns, such as `public,app_*`. See [Choosing schemas](#choosing-schemas) | `public` |
|
|
81
|
+
| `BACKUPDRILL_AUTH` | On PostgreSQL 12+, BackupDrill tries to write Supabase Auth users to `auth.dump` beside `dump.pgcustom` if the backup role can read every row in `auth.users` and `auth.identities`. `off` skips only `auth.dump`. `on` saves the database backup and exits with code 3 if neither archive contains both tables. Also set with `--auth`, `--no-auth` or `"auth": true/false`. See [Choosing schemas](#choosing-schemas). | on when possible |
|
|
81
82
|
| `BACKUPDRILL_S3_ENDPOINT` | S3-compatible endpoint (R2/B2/self-hosted; omit for AWS S3) | — |
|
|
82
83
|
| `BACKUPDRILL_S3_REGION` | Destination bucket region | `auto` |
|
|
83
84
|
| `BACKUPDRILL_S3_BUCKET` | Destination bucket | — (required) |
|
|
@@ -91,6 +92,19 @@ All recognized variables:
|
|
|
91
92
|
| `BACKUPDRILL_STATE_DIR` | Where `restore` keeps its record of restores with Auth users, for `--status` and `--finish` | `~/.backupdrill/restores` |
|
|
92
93
|
| `BACKUPDRILL_PING_URL` | Healthchecks.io ping URL for `backup` and `drill` — see [Alerts with Healthchecks.io](#alerts-with-healthchecksio) | — |
|
|
93
94
|
|
|
95
|
+
### Choosing schemas
|
|
96
|
+
|
|
97
|
+
`BACKUPDRILL_SCHEMAS` and `--schema` take `pg_dump --schema` patterns. Outside double quotes, ASCII letters become lowercase and `*` and `?` act as wildcards, so `app_*` matches every schema whose name starts with `app_`. To match `Sales` exactly, quote it: `export BACKUPDRILL_SCHEMAS='"Sales"'`. Leave out the database name. A name containing a comma can't go in the variable; use `--schema` or the config file's `schemas` array.
|
|
98
|
+
|
|
99
|
+
`manifest.json` lists the schemas the patterns matched, with their tables and grants. Before it creates a snapshot, BackupDrill checks that at least one schema matches and that none of them are PostgreSQL system schemas such as `pg_catalog` or `information_schema`. After the dump it matches the patterns again and fails the backup if a different set of schemas matches.
|
|
100
|
+
|
|
101
|
+
If your patterns select `auth`, BackupDrill skips `auth.dump` and lets `pg_dump` export the `auth` schema. If `dump.pgcustom` includes `auth.users`, any pending password-reset and confirmation tokens stay intact. BackupDrill also skips `auth.dump` unless every matched schema name starts with a lowercase ASCII letter or `_` and contains only lowercase ASCII letters, digits and `_`. When BackupDrill writes a separate `auth.dump`, it clears those tokens before upload.
|
|
102
|
+
|
|
103
|
+
Two known limits, until a later release checks the dump's own table list:
|
|
104
|
+
|
|
105
|
+
- If a schema name has non-ASCII characters and the client encoding isn't UTF-8, `manifest.json` can list a schema that `pg_dump` didn't dump. Run the backup with `PGCLIENTENCODING=UTF8` and leave `client_encoding` out of the connection string.
|
|
106
|
+
- A schema renamed and renamed back, or an Auth table dropped, while the backup runs can go unnoticed. Don't change the database structure during a backup.
|
|
107
|
+
|
|
94
108
|
### Config file
|
|
95
109
|
|
|
96
110
|
Copy `backupdrill.config.example.json` → `backupdrill.config.json` (it's gitignored) and fill it in. Keep secrets in env vars even when using a file. To also back up Storage files, start from `backupdrill.config.with-storage.example.json` instead — only copy the `supabaseStorage` block once you actually have S3 access keys for your project's Storage.
|
|
@@ -133,6 +147,8 @@ export BACKUPDRILL_SUPABASE_STORAGE_SECRET_ACCESS_KEY="…"
|
|
|
133
147
|
|
|
134
148
|
With those set, `backupdrill backup` also copies every Storage file into your bucket and records each file's checksum in the manifest. Omit them to back up the database only.
|
|
135
149
|
|
|
150
|
+
Since 2.12.0, if the Storage copy is incomplete, the snapshot still holds the database dump and any Auth archive, provided BackupDrill can save the manifest and recovery guide afterwards; `backup` then exits with code 3. Files deleted from your project between listing and copying go in `storage.vanished` and aren't counted as missing. A file is skipped if reading it stalls for two minutes, its full key in the backup location would be longer than 1,024 bytes, or the destination hasn't confirmed its upload 15 minutes after the read finished. The snapshot keeps the files that copied, and `storage.partial` counts the skipped ones by reason. If Storage listing, reading or writing fails outright, the manifest lists no Storage files and `storageFailure` records why. That includes a listing request getting no answer for two minutes, or a single upload request for 15 minutes. Files uploaded before the failure may still be in the backup bucket.
|
|
151
|
+
|
|
136
152
|
## Egress & cost — read this before scheduling daily backups
|
|
137
153
|
|
|
138
154
|
A backup pulls data **out** of Supabase, which counts as **egress on your Supabase bill**. Verified rates (2026-07-10, [egress docs](https://supabase.com/docs/guides/platform/manage-your-usage/egress) + [pricing](https://supabase.com/pricing)):
|
|
@@ -219,6 +235,14 @@ backupdrill restore --database --target-supabase-url https://<ref>.supabase.co -
|
|
|
219
235
|
|
|
220
236
|
Prefer files on disk instead? Skip the Storage target and pass `--storage-dir ./recovered`.
|
|
221
237
|
|
|
238
|
+
To restore a backup downloaded with BackupDrill's download script, pass `--from-dir` the folder that holds `backupdrill-download.json`. The other restore flags work as usual (`--database`, `--target-supabase-url`, `--dry-run`, `--confirm-target`); leave out `--bucket`, `--endpoint`, `--region` and `--prefix`, which `restore` refuses with `--from-dir`. Before writing to the target, `restore` checks the size and SHA-256 of the database dump and of any Auth archive and Storage files the manifest lists, and stops if one is missing or doesn't match; rerun the download script, then retry. With `--finish`, the folder needs `backupdrill-download.json`, the manifest and the database dump; the Auth archive and Storage files can be missing.
|
|
239
|
+
|
|
240
|
+
The restore works from private copies of those files, kept in your system temp folder (`TMPDIR` if set) and removed when it finishes. Without copy-on-write support, allow room there for the database dump, any Auth archive and the Storage files; a database restore also writes its own working copy of the dump and Auth archive.
|
|
241
|
+
|
|
242
|
+
```bash
|
|
243
|
+
backupdrill restore --from-dir ./backupdrill-download --database --target-supabase-url https://<ref>.supabase.co --dry-run
|
|
244
|
+
```
|
|
245
|
+
|
|
222
246
|
`--dry-run` writes nothing to the target. Besides checking the target (not the source project, schemas empty, Postgres and `pg_restore` versions, extensions available), it downloads the dump to a temporary directory, checks its sha256 and looks for foreign keys that point outside the backup (see [Tables that reference auth.users](#tables-that-reference-authusers)). The real run repeats those checks before it writes anything; a foreign key into a table that one of the recorded extensions creates is checked again once the extensions are installed. The database restore then runs in a single transaction: if any statement fails, nothing from the snapshot stays on the target, and you can run it again on the same project once you've fixed the cause. (If the connection drops while it commits, the error says so and asks you to check the target first.) Right after that transaction commits, the grants for `anon`, `authenticated` and `service_role` are set in a transaction of their own (see [Grants for anon, authenticated and service_role](#grants-for-anon-authenticated-and-service_role)). Foreign keys between two tables in the backup are the exception to the single transaction: they're added after that, in one more. If rows in your data already break one of them (deleting with triggers switched off, for example under `session_replication_role = replica`, can leave rows like that), the key is added as `NOT VALID` instead of failing the restore. Those rows come back as they are, new writes are still checked, and the report names the key and, when it can count them, how many rows break it. Keys on or into partitioned tables, keys into an extension's tables, and every key in an archive whose foreign key statements BackupDrill can't fully read stay in the main transaction, so a broken one rolls the whole restore back. A key over a generated column is added in the second step but is never relaxed, because the restore recomputes those values; if it breaks, that step fails. Keys added as `NOT VALID` don't fail a drill: the drill passes and lists them in its report. If a step after the main transaction fails for any other reason, the tables and data are already on the target and the error says so. Extensions the run installed stay installed, since the next run needs them too, and the empty-target check doesn't count objects that belong to an extension (except an extension's configuration tables, whose rows a dump can carry). One transaction holds a lock on every table, index and sequence until it commits, so a very large schema can run out of lock slots: on Supabase's smallest compute size, about a thousand tables (partitions count as tables). The restore then stops with nothing written and tells you how to raise `max_locks_per_transaction`.
|
|
223
247
|
|
|
224
248
|
Snapshots taken with 2.10.0 or later usually hold the Auth users as well. For those, `restore` writes the Auth users, the database and the triggers on the Auth tables that it can recreate in **one** transaction. Triggers it can't recreate, and policies on the Auth tables, are listed as manual steps. A foreign key like `profiles.id → auth.users` then finds its users. If anything fails before the commit, the target is left as it was. The grants and some foreign keys come after the commit, as with any restore (see above). A few things come with that:
|
package/dist/auth-backup.d.ts
CHANGED
|
@@ -19,22 +19,13 @@ export declare const AUTH_TABLES: readonly ["users", "identities"];
|
|
|
19
19
|
/** auth.dump 的技术上限:对应数百万用户或巨大的 metadata。超过就跳过,不拖慢和撑爆演练与恢复 */
|
|
20
20
|
export declare const AUTH_DUMP_MAX_BYTES: number;
|
|
21
21
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* - "no":全是普通名字,且没有 auth。
|
|
28
|
-
*/
|
|
29
|
-
export declare function authInSchemas(schemas: string[]): "yes" | "maybe" | "no";
|
|
30
|
-
/**
|
|
31
|
-
* 普通 schema 名字:不加引号、只有字母数字和下划线,按 pg_dump 的规则折成小写。其余一律返回 null,
|
|
32
|
-
* 按模式写法处理(不另备 Auth)。名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
|
|
33
|
-
* 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会
|
|
22
|
+
* 小写的普通 schema 名字:按 pg_dump 的规则,不加引号的名字折成小写;只有字母数字和下划线的才返回,其余返回 null。
|
|
23
|
+
* 名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
|
|
24
|
+
* 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会。
|
|
25
|
+
* 2.12.1 起 manifest.database.schemas 记的是解析好的真实名字(见 schema-patterns.ts),单独的 auth.dump 只在
|
|
26
|
+
* 每个名字都满足 plainSchemaName(name) === name 时才做;更早的快照记的是用户写的模式,带 Auth 的那些也全是普通名字
|
|
34
27
|
*/
|
|
35
28
|
export declare function plainSchemaName(pattern: string): string | null;
|
|
36
|
-
/** 默认模式用:确定会、或说不准,都算"可能已含 auth"——宁可少做,不碰现有备份 */
|
|
37
|
-
export declare function schemasMayIncludeAuth(schemas: string[]): boolean;
|
|
38
29
|
/**
|
|
39
30
|
* 连库,但能被 signal 随时打断:到点时直接断开连接,不管它还在连接池里排队、还是正在跑查询。
|
|
40
31
|
* Auth 这两条连接都在主 dump 之前用,绝不能让它们占着连接、把数据库备份堵在后面。
|
package/dist/auth-backup.js
CHANGED
|
@@ -5,78 +5,15 @@ export const AUTH_TABLES = ["users", "identities"];
|
|
|
5
5
|
/** auth.dump 的技术上限:对应数百万用户或巨大的 metadata。超过就跳过,不拖慢和撑爆演练与恢复 */
|
|
6
6
|
export const AUTH_DUMP_MAX_BYTES = 2 * 1024 * 1024 * 1024;
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*/
|
|
14
|
-
function schemaPatternRegex(pattern) {
|
|
15
|
-
let re = "";
|
|
16
|
-
let quoted = false;
|
|
17
|
-
for (let i = 0; i < pattern.length; i++) {
|
|
18
|
-
const ch = pattern[i];
|
|
19
|
-
if (ch === '"') {
|
|
20
|
-
if (quoted && pattern[i + 1] === '"') {
|
|
21
|
-
re += '"';
|
|
22
|
-
i++;
|
|
23
|
-
}
|
|
24
|
-
else {
|
|
25
|
-
quoted = !quoted;
|
|
26
|
-
}
|
|
27
|
-
continue;
|
|
28
|
-
}
|
|
29
|
-
if (quoted) {
|
|
30
|
-
re += ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
31
|
-
continue;
|
|
32
|
-
}
|
|
33
|
-
if (ch === "*")
|
|
34
|
-
re += ".*";
|
|
35
|
-
else if (ch === "?")
|
|
36
|
-
re += ".";
|
|
37
|
-
else if (ch === "$")
|
|
38
|
-
re += "\\$";
|
|
39
|
-
else if (/[A-Za-z0-9_]/.test(ch))
|
|
40
|
-
re += ch.toLowerCase();
|
|
41
|
-
else
|
|
42
|
-
return null;
|
|
43
|
-
}
|
|
44
|
-
return new RegExp(`^(?:${re})$`);
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* schemas 配置和 Auth 备份的关系。单独的 Auth 备份只在每一项都是普通 schema 名字时才做:
|
|
48
|
-
* 模式写法(通配、正则、"库.schema")由 PostgreSQL 自己解析,我们在这里算不准它最终选中哪些 schema,
|
|
49
|
-
* 也就没法可靠地判断"会不会重复导出"和"恢复时目标里哪些 schema 该是空的"——干脆不做。
|
|
50
|
-
* - "yes":明写了 auth(主 dump 里已经有),或某个模式确定匹配得到 auth(例如 "*");
|
|
51
|
-
* - "maybe":有模式写法,而又不能确定它包含 auth;
|
|
52
|
-
* - "no":全是普通名字,且没有 auth。
|
|
53
|
-
*/
|
|
54
|
-
export function authInSchemas(schemas) {
|
|
55
|
-
let maybe = false;
|
|
56
|
-
for (const pattern of schemas) {
|
|
57
|
-
const plain = plainSchemaName(pattern);
|
|
58
|
-
if (plain === "auth")
|
|
59
|
-
return "yes";
|
|
60
|
-
if (plain !== null)
|
|
61
|
-
continue;
|
|
62
|
-
if (schemaPatternRegex(pattern)?.test("auth"))
|
|
63
|
-
return "yes";
|
|
64
|
-
maybe = true;
|
|
65
|
-
}
|
|
66
|
-
return maybe ? "maybe" : "no";
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* 普通 schema 名字:不加引号、只有字母数字和下划线,按 pg_dump 的规则折成小写。其余一律返回 null,
|
|
70
|
-
* 按模式写法处理(不另备 Auth)。名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
|
|
71
|
-
* 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会
|
|
8
|
+
* 小写的普通 schema 名字:按 pg_dump 的规则,不加引号的名字折成小写;只有字母数字和下划线的才返回,其余返回 null。
|
|
9
|
+
* 名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
|
|
10
|
+
* 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会。
|
|
11
|
+
* 2.12.1 起 manifest.database.schemas 记的是解析好的真实名字(见 schema-patterns.ts),单独的 auth.dump 只在
|
|
12
|
+
* 每个名字都满足 plainSchemaName(name) === name 时才做;更早的快照记的是用户写的模式,带 Auth 的那些也全是普通名字
|
|
72
13
|
*/
|
|
73
14
|
export function plainSchemaName(pattern) {
|
|
74
15
|
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(pattern) ? pattern.toLowerCase() : null;
|
|
75
16
|
}
|
|
76
|
-
/** 默认模式用:确定会、或说不准,都算"可能已含 auth"——宁可少做,不碰现有备份 */
|
|
77
|
-
export function schemasMayIncludeAuth(schemas) {
|
|
78
|
-
return authInSchemas(schemas) !== "no";
|
|
79
|
-
}
|
|
80
17
|
/**
|
|
81
18
|
* 连库,但能被 signal 随时打断:到点时直接断开连接,不管它还在连接池里排队、还是正在跑查询。
|
|
82
19
|
* Auth 这两条连接都在主 dump 之前用,绝不能让它们占着连接、把数据库备份堵在后面。
|
|
@@ -444,7 +381,7 @@ async function firstNonStockObject(client) {
|
|
|
444
381
|
* 用户自己建在 extensions 之类里的函数不在任何一份归档里,新项目里也没有。
|
|
445
382
|
*/
|
|
446
383
|
function schemaCovered(schema, backedUpSchemas) {
|
|
447
|
-
//
|
|
384
|
+
// 带 Auth 的快照里 schemas 都是普通名字(见 plainSchemaName)
|
|
448
385
|
return backedUpSchemas.some((name) => plainSchemaName(name) === schema);
|
|
449
386
|
}
|
|
450
387
|
/** 触发器依赖的函数所在的全部 schema(触发函数 + WHEN 里调用的);旧记录没有 dependencySchemas 时只看触发函数 */
|
package/dist/auth-restore.js
CHANGED
|
@@ -461,7 +461,7 @@ export async function restoreWithAuth(opts) {
|
|
|
461
461
|
return null;
|
|
462
462
|
return `pg_restore stopped while writing out ${what} (${code === null ? "killed by a signal" : `exit code ${code}`}): ${firstRestoreError(genStderr)}`;
|
|
463
463
|
};
|
|
464
|
-
// 带 Auth 的快照里 schemas 全是普通名字(备份端
|
|
464
|
+
// 带 Auth 的快照里 schemas 全是普通名字(备份端 planAuth 保证),按 pg_dump 的规则规范化后才是真正的 schema 名;
|
|
465
465
|
// plainSchemaName 只放行 [a-z0-9_],拼进 SQL 字面量是安全的
|
|
466
466
|
const schemaNames = opts.schemas.map((name) => plainSchemaName(name)).filter((name) => name !== null);
|
|
467
467
|
const schemaArray = `array[${schemaNames.map((name) => `'${name}'`).join(", ")}]::text[]`;
|
package/dist/backup.d.ts
CHANGED
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
import type { BackupConfig } from "./config.js";
|
|
2
2
|
import { type SnapshotStore } from "./snapshot-store.js";
|
|
3
3
|
import type { Manifest } from "./manifest.js";
|
|
4
|
+
import { type StorageSyncOptions } from "./storage.js";
|
|
4
5
|
import { parsePgDumpMajor } from "./pgbin.js";
|
|
5
6
|
export { parsePgDumpMajor };
|
|
6
|
-
/**
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* 能备份的最老服务端:PostgreSQL 11,读授权要 pg_proc.prokind(11 起才有)。再老的库以前会在备份半途报一句
|
|
9
|
+
* "column does not exist",现在动手之前就挡。Supabase 的项目都在 15 以上,这条只挡自建的老库
|
|
10
|
+
*/
|
|
11
|
+
export declare const MIN_SERVER_VERSION_NUM = 110000;
|
|
12
|
+
/** 另备 Auth 用户(auth.dump)要 12:检查 auth.users 用到 pg_attribute.attgenerated(12 起才有) */
|
|
13
|
+
export declare const MIN_AUTH_SERVER_VERSION_NUM = 120000;
|
|
14
|
+
/**
|
|
15
|
+
* 主 dump 的 pg_dump 参数。patterns 是用户写的 --schema 模式,原样交给 pg_dump(为什么不换成解析出的名字见
|
|
16
|
+
* schema-patterns.ts)。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样)
|
|
17
|
+
*/
|
|
18
|
+
export declare function mainDumpArgs(patterns: string[], snapshotId?: string): string[];
|
|
8
19
|
/**
|
|
9
20
|
* Auth 一侧的两个时限(导出供测试调短,产品里不改):
|
|
10
21
|
* - waitAfterMainMs:主 dump 完成后还肯等 Auth 导出多久
|
|
@@ -23,4 +34,6 @@ export declare const AUTH_TIMEOUTS: {
|
|
|
23
34
|
export declare function runBackup(config: BackupConfig, opts?: {
|
|
24
35
|
/** 快照写到哪;省略 = config.storage 指的 S3 兼容桶 */
|
|
25
36
|
store?: SnapshotStore;
|
|
37
|
+
/** Storage 文件复制的时间预算、停滞阈值、写请求计数回报(见 StorageSyncOptions);省略 = 不设预算 */
|
|
38
|
+
storage?: StorageSyncOptions;
|
|
26
39
|
}): Promise<Manifest>;
|
package/dist/backup.js
CHANGED
|
@@ -4,9 +4,9 @@ import { Transform } from "node:stream";
|
|
|
4
4
|
import { promisify } from "node:util";
|
|
5
5
|
import { s3SnapshotStore } from "./snapshot-store.js";
|
|
6
6
|
import { MANIFEST_SCHEMA_VERSION } from "./manifest.js";
|
|
7
|
-
import { AUTH_DUMP_MAX_BYTES, authDumpArgs, exportSharedSnapshot, inspectAuth,
|
|
7
|
+
import { AUTH_DUMP_MAX_BYTES, AUTH_TABLES, authDumpArgs, exportSharedSnapshot, inspectAuth, manualAuthObjects, plainSchemaName, redactValues, } from "./auth-backup.js";
|
|
8
8
|
import { scrubPendingAuthTokens } from "./auth-archive.js";
|
|
9
|
-
import { syncStorage } from "./storage.js";
|
|
9
|
+
import { syncStorage, StorageSyncError } from "./storage.js";
|
|
10
10
|
import { inspectBucketAttrs } from "./storage-catalog.js";
|
|
11
11
|
import { projectRefOf, refFromStorageEndpoint, assertNoHostOverride } from "./restore-engine.js";
|
|
12
12
|
import { log } from "./log.js";
|
|
@@ -14,6 +14,7 @@ import { TOOL_VERSION } from "./version.js";
|
|
|
14
14
|
import { parsePgDumpMajor } from "./pgbin.js";
|
|
15
15
|
import { relationBytes } from "./estimate.js";
|
|
16
16
|
import { captureIdentifiedGrants, grantsHeldThroughout } from "./grants.js";
|
|
17
|
+
import { resolveSchemaPatterns, schemaNamesText } from "./schema-patterns.js";
|
|
17
18
|
// 解析函数搬到了 pgbin(演练与恢复都要读 pg_restore 版本,放这里会成环);保留旧出口
|
|
18
19
|
export { parsePgDumpMajor };
|
|
19
20
|
import { dumpUrlFor, connectPg, isSupabaseHost } from "./supabase-ca.js";
|
|
@@ -23,6 +24,13 @@ function majorOf(serverVersionNum) {
|
|
|
23
24
|
// server_version_num: 150004 → 15, 170002 → 17
|
|
24
25
|
return Math.floor(serverVersionNum / 10000);
|
|
25
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* 能备份的最老服务端:PostgreSQL 11,读授权要 pg_proc.prokind(11 起才有)。再老的库以前会在备份半途报一句
|
|
29
|
+
* "column does not exist",现在动手之前就挡。Supabase 的项目都在 15 以上,这条只挡自建的老库
|
|
30
|
+
*/
|
|
31
|
+
export const MIN_SERVER_VERSION_NUM = 110000;
|
|
32
|
+
/** 另备 Auth 用户(auth.dump)要 12:检查 auth.users 用到 pg_attribute.attgenerated(12 起才有) */
|
|
33
|
+
export const MIN_AUTH_SERVER_VERSION_NUM = 120000;
|
|
26
34
|
async function pgDumpVersion(bin) {
|
|
27
35
|
try {
|
|
28
36
|
const { stdout } = await execFileAsync(bin, ["--version"]);
|
|
@@ -41,13 +49,18 @@ async function pgDumpVersion(bin) {
|
|
|
41
49
|
throw error;
|
|
42
50
|
}
|
|
43
51
|
}
|
|
44
|
-
async function inspectDatabase(databaseUrl,
|
|
52
|
+
async function inspectDatabase(databaseUrl, patterns) {
|
|
45
53
|
// Supabase 主机 → 用打包的根 CA 做 verify-full(pooler 证书自签、不在系统信任库);
|
|
46
54
|
// 非 Supabase(本 CLI 不限制目标)→ 保持默认,别把开源用户挡在门外
|
|
47
55
|
const client = await connectPg(databaseUrl);
|
|
48
56
|
try {
|
|
49
57
|
const version = await client.query("show server_version");
|
|
50
58
|
const versionNum = await client.query("show server_version_num");
|
|
59
|
+
if (Number(versionNum.rows[0].server_version_num) < MIN_SERVER_VERSION_NUM) {
|
|
60
|
+
throw new Error(`This database runs PostgreSQL ${version.rows[0].server_version}. BackupDrill backs up PostgreSQL 11 or newer ` +
|
|
61
|
+
`(12 or newer for a separate auth.dump).`);
|
|
62
|
+
}
|
|
63
|
+
const schemas = await resolveSchemaPatterns(client, patterns);
|
|
51
64
|
// 只统计将被 dump 的 schema,manifest 才与转储内容一致。
|
|
52
65
|
// 口径 = pg_class relkind in ('r','p','m'):普通表 + 分区父表 + 物化视图,
|
|
53
66
|
// 与 pg_dump 实际转储的关系集合一致,且必须与 drill 校验端(verifyRestored)
|
|
@@ -61,6 +74,17 @@ async function inspectDatabase(databaseUrl, schemas) {
|
|
|
61
74
|
where c.relkind in ('r', 'p', 'm')
|
|
62
75
|
and n.nspname = any($1::text[])
|
|
63
76
|
order by 1, 2`, [schemas]);
|
|
77
|
+
// 备份范围带上 auth 时,两张 Auth 表会不会进主 dump 决定这次算不算备了 Auth 用户(见 planAuth)。
|
|
78
|
+
// 只算普通表:分区表的行在各个分区里,分区可以建在备份范围之外的 schema,pg_dump 只按 schema 导出;
|
|
79
|
+
// 扩展自己的表 pg_dump 不导出,也不算。Supabase 的这两张表都是普通表
|
|
80
|
+
const authTablesDumped = schemas.includes("auth")
|
|
81
|
+
? (await client.query(`select c.relname as name
|
|
82
|
+
from pg_class c
|
|
83
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
84
|
+
where n.nspname = 'auth' and c.relname = any($1::text[]) and c.relkind = 'r'
|
|
85
|
+
and not exists (select 1 from pg_depend d
|
|
86
|
+
where d.classid = 'pg_catalog.pg_class'::regclass and d.objid = c.oid and d.deptype = 'e')`, [[...AUTH_TABLES]])).rows.map((r) => r.name)
|
|
87
|
+
: [];
|
|
64
88
|
// 非内置扩展清单(排除必装的 plpgsql):--schema 转储不含 CREATE EXTENSION,
|
|
65
89
|
// 演练沙箱要靠它在恢复前把扩展类型(如 vector)装回来
|
|
66
90
|
const extensions = await client.query(`select e.extname as name, e.extversion as version, n.nspname as schema
|
|
@@ -80,6 +104,8 @@ async function inspectDatabase(databaseUrl, schemas) {
|
|
|
80
104
|
return {
|
|
81
105
|
serverVersion: version.rows[0].server_version,
|
|
82
106
|
serverVersionNum: Number(versionNum.rows[0].server_version_num),
|
|
107
|
+
schemas,
|
|
108
|
+
authTablesDumped,
|
|
83
109
|
tables: tables.rows.map((r) => ({
|
|
84
110
|
schema: r.schema,
|
|
85
111
|
name: r.name,
|
|
@@ -93,6 +119,15 @@ async function inspectDatabase(databaseUrl, schemas) {
|
|
|
93
119
|
await client.end();
|
|
94
120
|
}
|
|
95
121
|
}
|
|
122
|
+
async function readSchemaNames(databaseUrl, patterns) {
|
|
123
|
+
const client = await connectPg(databaseUrl);
|
|
124
|
+
try {
|
|
125
|
+
return await resolveSchemaPatterns(client, patterns);
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
await client.end();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
96
131
|
async function readGrants(databaseUrl, schemas) {
|
|
97
132
|
const client = await connectPg(databaseUrl);
|
|
98
133
|
try {
|
|
@@ -102,14 +137,17 @@ async function readGrants(databaseUrl, schemas) {
|
|
|
102
137
|
await client.end();
|
|
103
138
|
}
|
|
104
139
|
}
|
|
105
|
-
/**
|
|
106
|
-
|
|
140
|
+
/**
|
|
141
|
+
* 主 dump 的 pg_dump 参数。patterns 是用户写的 --schema 模式,原样交给 pg_dump(为什么不换成解析出的名字见
|
|
142
|
+
* schema-patterns.ts)。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样)
|
|
143
|
+
*/
|
|
144
|
+
export function mainDumpArgs(patterns, snapshotId) {
|
|
107
145
|
return [
|
|
108
146
|
"--format=custom",
|
|
109
147
|
"--no-owner",
|
|
110
148
|
"--no-privileges",
|
|
111
149
|
...(snapshotId ? [`--snapshot=${snapshotId}`] : []),
|
|
112
|
-
...
|
|
150
|
+
...patterns.map((s) => `--schema=${s}`),
|
|
113
151
|
];
|
|
114
152
|
}
|
|
115
153
|
class AuthDumpTooLarge extends Error {
|
|
@@ -277,11 +315,16 @@ const AUTH_SKIP_TEXT = {
|
|
|
277
315
|
no_permission: "the backup role can't read every row of auth.users and auth.identities (it needs BYPASSRLS or superuser, plus read access)",
|
|
278
316
|
no_auth_schema: "this database has no Supabase auth schema",
|
|
279
317
|
unsupported_destination: "this backup destination can't hold the Auth archive yet",
|
|
280
|
-
schemas_include_auth: "
|
|
318
|
+
schemas_include_auth: "the selected schemas include auth, so the Auth users are in the database dump",
|
|
319
|
+
// 2.12.1 之前:模式写法算不清选中哪些 schema。新快照不再记这个原因,旧快照的说法照旧
|
|
281
320
|
schemas_not_plain: "your schema list uses a pattern or a quoted name, so the Auth users aren't backed up separately " +
|
|
282
321
|
"(they are in the database dump only if one of those patterns matches auth)",
|
|
322
|
+
schema_names_not_plain: "one of the selected schema names blocks auth.dump, and the database dump excludes auth. " +
|
|
323
|
+
"Each name must start with a–z or _ and use only a–z, 0–9 and _",
|
|
283
324
|
too_large: "the Auth archive is larger than 2 GiB",
|
|
284
325
|
snapshot_unavailable: "a consistent snapshot for the Auth export couldn't be set up",
|
|
326
|
+
server_too_old: "the source database runs PostgreSQL 11, and a separate auth.dump requires PostgreSQL 12 or newer " +
|
|
327
|
+
"(BackupDrill checks auth.users with a column added in 12); the database itself is backed up",
|
|
285
328
|
};
|
|
286
329
|
/** 报错只留第一行、截短:pg_dump / 上传的错误不该把大段原文(更不能是行值)带进 manifest 和告警 */
|
|
287
330
|
function shortReason(error) {
|
|
@@ -291,33 +334,44 @@ function shortReason(error) {
|
|
|
291
334
|
* 决定这次要不要、能不能另外备 Auth。任何"不能"都在这里落成 skipped/failed,不抛错——
|
|
292
335
|
* 主 dump 永远不因 Auth 受影响。返回 dump 时,共享快照已经导出,调用方负责释放。
|
|
293
336
|
*/
|
|
294
|
-
async function planAuth(
|
|
295
|
-
//
|
|
296
|
-
|
|
297
|
-
|
|
337
|
+
async function planAuth(writer, mode, db, databaseUrl) {
|
|
338
|
+
// db.schemas 是备份范围在源库上解析出来的 schema 名字,和主 dump 导出的一致(见 schema-patterns.ts)
|
|
339
|
+
const authDumped = db.schemas.includes("auth");
|
|
340
|
+
const authTablesDumped = AUTH_TABLES.every((name) => db.authTablesDumped.includes(name));
|
|
341
|
+
// 2.11.1 起只有 auth.dump 抹掉待处理 token;主 dump 带着 auth.users 时,里面的 token 还是原样,
|
|
342
|
+
// 每次备份提醒一句(只看 auth.users,token 都在这张表里)。不管 Auth 备份开没开都提醒:主 dump 的内容和它无关
|
|
343
|
+
if (db.authTablesDumped.includes("users")) {
|
|
298
344
|
log.warn("Your schema list includes auth, so dump.pgcustom holds the Auth tables as they are, " +
|
|
299
345
|
"including pending password-reset and confirmation tokens. Only auth.dump has them cleared.");
|
|
300
346
|
}
|
|
301
347
|
if (mode === "off")
|
|
302
348
|
return { kind: "none" };
|
|
303
|
-
//
|
|
304
|
-
//
|
|
305
|
-
//
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
349
|
+
// 主 dump 已经带上 auth:今天怎样以后还怎样,不另备一份。两张 Auth 表都会进主 dump 才算备上了(skipped,数据在主 dump 里);
|
|
350
|
+
// auth 这个 schema 在、表缺了一张(不是 Supabase 的库,或表归扩展所有、pg_dump 不导出),
|
|
351
|
+
// 显式要求时记 failed——不能在 Auth 用户哪份归档都不在时报成功
|
|
352
|
+
if (authDumped) {
|
|
353
|
+
return {
|
|
354
|
+
kind: "settled",
|
|
355
|
+
section: authTablesDumped ? { status: "skipped", reason: "schemas_include_auth" } : authNotDone(mode, "no_auth_schema"),
|
|
356
|
+
};
|
|
309
357
|
}
|
|
310
|
-
|
|
311
|
-
|
|
358
|
+
// 单独的 auth.dump 只在每个 schema 名字都是小写普通名字时才做:名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,
|
|
359
|
+
// 恢复端也按这个规则读(plainSchemaName)。带大写、$ 这类字符的名字(加引号建的 schema)不给拼接出错的机会
|
|
360
|
+
if (!db.schemas.every((name) => plainSchemaName(name) === name)) {
|
|
361
|
+
return { kind: "settled", section: authNotDone(mode, "schema_names_not_plain") };
|
|
312
362
|
}
|
|
313
363
|
if (!writer.uploadAuthDump || !writer.authDumpKey) {
|
|
314
364
|
return { kind: "settled", section: authNotDone(mode, "unsupported_destination") };
|
|
315
365
|
}
|
|
366
|
+
// PostgreSQL 11 的库照常备数据库,只是做不了 auth.dump(见 MIN_AUTH_SERVER_VERSION_NUM)
|
|
367
|
+
if (db.serverVersionNum < MIN_AUTH_SERVER_VERSION_NUM) {
|
|
368
|
+
return { kind: "settled", section: authNotDone(mode, "server_too_old") };
|
|
369
|
+
}
|
|
316
370
|
// 导出快照和统计都发生在主 dump 之前,必须有总时限:连接池满时新连接会一直排队,
|
|
317
371
|
// 不能让数据库备份陪着等。到点就按"快照不可用"放弃,并立刻断开 Auth 的两条连接
|
|
318
372
|
// (不管它们还在排队还是在跑查询),把连接让给主 dump
|
|
319
373
|
const stop = new AbortController();
|
|
320
|
-
const prepared = prepareAuthDump(
|
|
374
|
+
const prepared = prepareAuthDump(databaseUrl, writer, mode, stop.signal);
|
|
321
375
|
prepared.catch(() => { });
|
|
322
376
|
let deadline;
|
|
323
377
|
const timedOut = new Promise((resolve) => {
|
|
@@ -331,13 +385,13 @@ async function planAuth(config, writer, mode) {
|
|
|
331
385
|
clearTimeout(deadline);
|
|
332
386
|
return plan;
|
|
333
387
|
}
|
|
334
|
-
async function prepareAuthDump(
|
|
335
|
-
const shared = await exportSharedSnapshot(
|
|
388
|
+
async function prepareAuthDump(databaseUrl, writer, mode, signal) {
|
|
389
|
+
const shared = await exportSharedSnapshot(databaseUrl, signal);
|
|
336
390
|
if (!shared)
|
|
337
391
|
return { kind: "settled", section: authNotDone(mode, "snapshot_unavailable") };
|
|
338
392
|
let inspection;
|
|
339
393
|
try {
|
|
340
|
-
inspection = await inspectAuth(
|
|
394
|
+
inspection = await inspectAuth(databaseUrl, shared.id, signal);
|
|
341
395
|
}
|
|
342
396
|
catch (error) {
|
|
343
397
|
await shared.release();
|
|
@@ -535,6 +589,11 @@ function logAuthOutcome(auth, schemas) {
|
|
|
535
589
|
log.warn(`Auth users backup failed: ${why}. The database backup itself is complete.`);
|
|
536
590
|
}
|
|
537
591
|
}
|
|
592
|
+
const STORAGE_REASON_TEXT = {
|
|
593
|
+
time_budget: "ran out of time",
|
|
594
|
+
read_stalled: "stopped sending data",
|
|
595
|
+
key_too_long: "name too long for the backup location",
|
|
596
|
+
};
|
|
538
597
|
export async function runBackup(config, opts = {}) {
|
|
539
598
|
// 源身份先于一切传输(评审第 12 轮):①连接串不许带 ?host=/user= 覆盖——否则
|
|
540
599
|
// 快照记的 ref 与实际读取对象脱节,恢复端的同源保护随之失真;②库与 Storage
|
|
@@ -552,8 +611,9 @@ export async function runBackup(config, opts = {}) {
|
|
|
552
611
|
const pgDumpBin = process.env.BACKUPDRILL_PG_DUMP || "pg_dump";
|
|
553
612
|
log.step("Inspecting database…");
|
|
554
613
|
const db = await inspectDatabase(config.databaseUrl, config.schemas);
|
|
614
|
+
// 授权、Auth 判断、manifest 用解析出来的 schema 名字;pg_dump 拿原样的模式(见 schema-patterns.ts)
|
|
555
615
|
const serverMajor = majorOf(db.serverVersionNum);
|
|
556
|
-
log.ok(`Postgres ${db.serverVersion} — schema(s) ${
|
|
616
|
+
log.ok(`Postgres ${db.serverVersion} — schema(s) ${schemaNamesText(db.schemas)}: ` +
|
|
557
617
|
`${db.tables.length} tables, ` +
|
|
558
618
|
`~${db.tables.reduce((n, t) => n + t.estimatedRows, 0).toLocaleString()} rows`);
|
|
559
619
|
// pg_dump 主版本必须 ≥ 服务端,否则转储会失败或不完整(PRD §4.2)
|
|
@@ -575,11 +635,11 @@ export async function runBackup(config, opts = {}) {
|
|
|
575
635
|
// 授权在转储前后各读一次,只记两次都有的(为什么见 grantsHeldThroughout)。
|
|
576
636
|
// 哪次读不到都让备份失败,不留一份缺授权记录的快照:恢复端把"没有记录"当成 2.9.0 之前的旧快照,
|
|
577
637
|
// 按 Supabase 以前的默认授权开放 public,会把源库关着的表打开
|
|
578
|
-
const grantsBeforeDump = await readGrants(config.databaseUrl,
|
|
579
|
-
// Auth 用户另备一份(2.10.0 起,见 auth-backup.ts)。库调用方没传 =
|
|
580
|
-
//
|
|
638
|
+
const grantsBeforeDump = await readGrants(config.databaseUrl, db.schemas);
|
|
639
|
+
// Auth 用户另备一份(2.10.0 起,见 auth-backup.ts)。库调用方没传 = 关闭:不另导 auth.dump、pg_dump 不带 --snapshot,
|
|
640
|
+
// manifest 里没有 auth 段。共享快照在转储前一刻才导出,尽量少占连接
|
|
581
641
|
const authMode = config.auth ?? "off";
|
|
582
|
-
const authPlan = await planAuth(
|
|
642
|
+
const authPlan = await planAuth(writer, authMode, db, config.databaseUrl);
|
|
583
643
|
let auth = authPlan.kind === "settled" ? authPlan.section : undefined;
|
|
584
644
|
log.step(`Dumping → ${writer.describe("dump.pgcustom")}`);
|
|
585
645
|
let bytes;
|
|
@@ -599,37 +659,68 @@ export async function runBackup(config, opts = {}) {
|
|
|
599
659
|
}
|
|
600
660
|
log.ok(`Database dumped (${(bytes / 1024 / 1024).toFixed(1)} MB, sha256 ${sha256.slice(0, 12)}…)`);
|
|
601
661
|
if (auth)
|
|
602
|
-
logAuthOutcome(auth,
|
|
603
|
-
|
|
604
|
-
//
|
|
662
|
+
logAuthOutcome(auth, db.schemas);
|
|
663
|
+
// 转储前解析的 schema 名字要在转储后还是同一份:中间有人建、删、改名了 schema,pg_dump 按它那一刻的样子导出,
|
|
664
|
+
// manifest 却记着之前的名字,两边对不上。pg_dump 的快照落在这两次解析之间,两次一样就说明它看到的也一样
|
|
665
|
+
const schemasAfterDump = await readSchemaNames(config.databaseUrl, config.schemas);
|
|
666
|
+
if (schemasAfterDump.join("\u0000") !== db.schemas.join("\u0000")) {
|
|
667
|
+
throw new Error(`The schemas matching your patterns changed while the backup ran ` +
|
|
668
|
+
`(before: ${schemaNamesText(db.schemas)}; after: ${schemaNamesText(schemasAfterDump)}), ` +
|
|
669
|
+
`so this snapshot's manifest might not match its dump. Run the backup again.`);
|
|
670
|
+
}
|
|
671
|
+
const grants = grantsHeldThroughout(grantsBeforeDump, await readGrants(config.databaseUrl, db.schemas));
|
|
672
|
+
// Storage 文件同步(源配置存在才做;否则只备数据库)。2.12.0 起 Storage 失败不拖累数据库:
|
|
673
|
+
// 列不出来、读不了、写不进目标时这份快照照常完成,manifest 记 storageFailure,storage 为 null
|
|
605
674
|
let storageResult = null;
|
|
675
|
+
let storageFailure;
|
|
606
676
|
if (config.supabaseStorage && storageFiles) {
|
|
607
677
|
log.step("Syncing Storage files…");
|
|
608
|
-
|
|
609
|
-
client: storageFiles.s3,
|
|
610
|
-
bucket: storageFiles.bucket,
|
|
611
|
-
base: storageFiles.base, // syncStorage 内部会加 /storage/<bucket>/<key>
|
|
612
|
-
});
|
|
613
|
-
// v2 bucket 属性采集,通道 = 已有的只读库连接(per-file 元数据已随 GetObject
|
|
614
|
-
// 响应在 syncStorage 内原子捕获)。失败只降级不报错:storage schema 读不到
|
|
615
|
-
// (如收紧的 backup_reader 角色)时,manifest 缺 buckets 字段,恢复端把缺失
|
|
616
|
-
// 如实标 not captured(PRD §5.1.3)。
|
|
617
|
-
let bucketAttrs;
|
|
678
|
+
let synced = null;
|
|
618
679
|
try {
|
|
619
|
-
|
|
680
|
+
synced = await syncStorage(config.supabaseStorage, {
|
|
681
|
+
client: storageFiles.s3,
|
|
682
|
+
bucket: storageFiles.bucket,
|
|
683
|
+
base: storageFiles.base, // syncStorage 内部会加 /storage/<bucket>/<key>
|
|
684
|
+
}, opts.storage);
|
|
620
685
|
}
|
|
621
686
|
catch (error) {
|
|
622
|
-
|
|
623
|
-
|
|
687
|
+
if (!(error instanceof StorageSyncError))
|
|
688
|
+
throw error;
|
|
689
|
+
storageFailure = { reason: error.message };
|
|
690
|
+
log.warn(`Storage files were not backed up this time: ${error.message}. The database backup itself is complete.`);
|
|
691
|
+
}
|
|
692
|
+
if (synced) {
|
|
693
|
+
// v2 bucket 属性采集,通道 = 已有的只读库连接(per-file 元数据已随 GetObject
|
|
694
|
+
// 响应在 syncStorage 内原子捕获)。失败只降级不报错:storage schema 读不到
|
|
695
|
+
// (如收紧的 backup_reader 角色)时,manifest 缺 buckets 字段,恢复端把缺失
|
|
696
|
+
// 如实标 not captured(PRD §5.1.3)。
|
|
697
|
+
let bucketAttrs;
|
|
698
|
+
try {
|
|
699
|
+
bucketAttrs = await inspectBucketAttrs(config.databaseUrl, synced.buckets);
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
log.warn(`Bucket attributes not captured (${error.message}); ` +
|
|
703
|
+
`this manifest will record them as absent — restore will say so instead of guessing.`);
|
|
704
|
+
}
|
|
705
|
+
storageResult = {
|
|
706
|
+
...(bucketAttrs ? { buckets: bucketAttrs } : {}),
|
|
707
|
+
fileCount: synced.fileCount,
|
|
708
|
+
totalBytes: synced.totalBytes,
|
|
709
|
+
files: synced.files,
|
|
710
|
+
...(synced.vanished.length ? { vanished: synced.vanished } : {}),
|
|
711
|
+
...(synced.partial ? { partial: synced.partial } : {}),
|
|
712
|
+
};
|
|
713
|
+
log.ok(`Storage synced (${synced.fileCount} files, ` +
|
|
714
|
+
`${(synced.totalBytes / 1024 / 1024).toFixed(1)} MB)`);
|
|
715
|
+
if (synced.vanished.length) {
|
|
716
|
+
log.step(` ${synced.vanished.length} file(s) were deleted in the project while we copied; nothing to back up for those.`);
|
|
717
|
+
}
|
|
718
|
+
if (synced.partial) {
|
|
719
|
+
const why = synced.partial.notCopied.map((n) => `${n.count} ${STORAGE_REASON_TEXT[n.reason]}`).join(", ");
|
|
720
|
+
log.warn(`Storage copy is partial: ${synced.partial.copied} of ${synced.partial.total} files (not copied: ${why}). ` +
|
|
721
|
+
`The database backup itself is complete.`);
|
|
722
|
+
}
|
|
624
723
|
}
|
|
625
|
-
storageResult = {
|
|
626
|
-
...(bucketAttrs ? { buckets: bucketAttrs } : {}),
|
|
627
|
-
fileCount: synced.fileCount,
|
|
628
|
-
totalBytes: synced.totalBytes,
|
|
629
|
-
files: synced.files,
|
|
630
|
-
};
|
|
631
|
-
log.ok(`Storage synced (${synced.fileCount} files, ` +
|
|
632
|
-
`${(synced.totalBytes / 1024 / 1024).toFixed(1)} MB)`);
|
|
633
724
|
}
|
|
634
725
|
const manifest = {
|
|
635
726
|
schemaVersion: MANIFEST_SCHEMA_VERSION,
|
|
@@ -641,7 +732,7 @@ export async function runBackup(config, opts = {}) {
|
|
|
641
732
|
database: {
|
|
642
733
|
serverVersion: db.serverVersion,
|
|
643
734
|
pgDumpVersion: pgd.raw,
|
|
644
|
-
schemas:
|
|
735
|
+
schemas: db.schemas,
|
|
645
736
|
tableCount: db.tables.length,
|
|
646
737
|
estimatedRowTotal: db.tables.reduce((n, t) => n + t.estimatedRows, 0),
|
|
647
738
|
tables: db.tables,
|
|
@@ -652,6 +743,8 @@ export async function runBackup(config, opts = {}) {
|
|
|
652
743
|
// 关闭时不写这个字段:manifest 与之前逐字节一致
|
|
653
744
|
...(auth ? { auth } : {}),
|
|
654
745
|
storage: storageResult,
|
|
746
|
+
// 只在失败时写:没失败的 manifest 与之前逐字节一致
|
|
747
|
+
...(storageFailure ? { storageFailure } : {}),
|
|
655
748
|
};
|
|
656
749
|
// RECOVERY.md(PRD §5.9.2.1)先于 manifest 落桶:manifest 是快照的"完成标记"
|
|
657
750
|
// (演练/恢复按它找快照)——先写手册再写标记,"快照完成"就蕴含"手册在场";
|