backupdrill 2.11.1 → 2.12.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.
- package/README.md +14 -0
- package/dist/auth-restore.d.ts +5 -0
- package/dist/auth-restore.js +11 -0
- package/dist/backup.d.ts +3 -0
- package/dist/backup.js +53 -23
- package/dist/dir-store.d.ts +55 -0
- package/dist/dir-store.js +208 -0
- package/dist/drill.d.ts +2 -0
- package/dist/drill.js +121 -16
- package/dist/index.js +60 -17
- package/dist/lib.d.ts +7 -2
- package/dist/lib.js +6 -1
- package/dist/manifest.d.ts +23 -0
- package/dist/manifest.js +39 -0
- package/dist/ping.d.ts +5 -0
- package/dist/ping.js +20 -0
- package/dist/recovery-doc.js +7 -2
- package/dist/restore.d.ts +1 -1
- package/dist/restore.js +40 -13
- 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/dist/drill.js
CHANGED
|
@@ -143,20 +143,77 @@ export function sandboxDataVolumeTarget(major) {
|
|
|
143
143
|
* 停掉命令也说不准守护进程之后还会不会把容器建出来(交叉审查)。拆开之后,慢的那一步(第一次拉镜像
|
|
144
144
|
* 可能好几分钟)什么都不建,中断时直接停掉;docker run 只剩建容器和启动。
|
|
145
145
|
*/
|
|
146
|
+
/**
|
|
147
|
+
* 本地已有镜像也要每次 pull:标签(postgres:17-alpine)跟着小版本走,只拉一次就会永远停在当时的小版本。
|
|
148
|
+
* 2026-11-24 事故:worker 上的沙箱停在 17.10,源库被 Supabase 升到带 CVE-2026-6460 补丁的新小版本,
|
|
149
|
+
* 旧 pg_dump 导出的 `ALTER COLUMN ... SET (pg_attver=…)` 在 17.10 上报 unrecognized parameter,
|
|
150
|
+
* 整个演练失败;17.12 会接受并忽略这句。镜像没变时 pull 只比一次清单,很快。
|
|
151
|
+
* 已有缓存时刷新失败(断网、仓库限流、超时)不算演练失败:退回本地镜像并提示。
|
|
152
|
+
*
|
|
153
|
+
* 收尾不等 stdio 关闭:docker 拉起的凭据助手可能还占着 stderr(交叉审查用卡住的助手复现)。
|
|
154
|
+
* 只等 docker 本身退出;到点或被中断时,连同它的子孙进程(凭据助手)一起 SIGKILL,再把我们这头的
|
|
155
|
+
* 管道关掉,CLI 才能照常退出,也不会每次超时留下一个助手。
|
|
156
|
+
* pull 留在演练所在的进程组里(不 detach):worker 叫停演练时按组结束,连助手一起带走。
|
|
157
|
+
*/
|
|
158
|
+
// 测试用的环境变量只为把 5 分钟缩短到几秒;不对用户公开
|
|
159
|
+
const IMAGE_REFRESH_TIMEOUT_MS = Number(process.env.BACKUPDRILL_TEST_IMAGE_REFRESH_TIMEOUT_MS) || 5 * 60_000;
|
|
160
|
+
/** 子孙进程 pid(pgrep -P 逐层往下找);没有 pgrep(Windows)时返回空,只停进程本身 */
|
|
161
|
+
async function descendantPids(pid) {
|
|
162
|
+
const children = await execFileAsync("pgrep", ["-P", String(pid)], { timeout: 5_000 }).then(({ stdout }) => stdout.split("\n").map(Number).filter((n) => n > 0), () => []);
|
|
163
|
+
const deeper = await Promise.all(children.map(descendantPids));
|
|
164
|
+
return [...children, ...deeper.flat()];
|
|
165
|
+
}
|
|
166
|
+
/** 先记下子孙再停:父进程一死,子进程就被收养,pgrep -P 再也找不到它们 */
|
|
167
|
+
async function killProcessTree(child) {
|
|
168
|
+
if (!child.pid || child.exitCode !== null || child.signalCode !== null)
|
|
169
|
+
return;
|
|
170
|
+
const descendants = await descendantPids(child.pid);
|
|
171
|
+
child.kill("SIGKILL");
|
|
172
|
+
for (const pid of descendants) {
|
|
173
|
+
try {
|
|
174
|
+
process.kill(pid, "SIGKILL");
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
// 已经退出
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
146
181
|
async function ensureImage(image) {
|
|
147
182
|
const present = await execFileAsync("docker", ["image", "inspect", "--format", "{{.Id}}", image]).then(() => true, () => false);
|
|
148
|
-
if (present)
|
|
149
|
-
return;
|
|
150
183
|
throwIfInterrupted();
|
|
151
|
-
log.step(`Pulling ${image}…`);
|
|
152
|
-
const pull =
|
|
153
|
-
const forget =
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
184
|
+
log.step(present ? `Checking ${image} for updates…` : `Pulling ${image}…`);
|
|
185
|
+
const pull = spawn("docker", ["pull", "--quiet", image], { stdio: ["ignore", "ignore", "pipe"] });
|
|
186
|
+
const forget = onInterrupt(() => killProcessTree(pull));
|
|
187
|
+
// 只留开头一段用来说明失败原因,其余照样读掉,别让吵闹的 docker 把内存撑大
|
|
188
|
+
let stderr = "";
|
|
189
|
+
pull.stderr?.on("data", (chunk) => {
|
|
190
|
+
if (stderr.length < 4096)
|
|
191
|
+
stderr += chunk.toString();
|
|
192
|
+
});
|
|
193
|
+
let timer;
|
|
194
|
+
const outcome = await new Promise((resolve) => {
|
|
195
|
+
pull.on("error", (error) => {
|
|
196
|
+
stderr ||= error.message;
|
|
197
|
+
resolve("failed");
|
|
198
|
+
});
|
|
199
|
+
pull.on("exit", (code) => resolve(code === 0 ? "ok" : "failed"));
|
|
200
|
+
if (present)
|
|
201
|
+
timer = setTimeout(() => resolve("timeout"), IMAGE_REFRESH_TIMEOUT_MS);
|
|
202
|
+
});
|
|
203
|
+
clearTimeout(timer);
|
|
204
|
+
if (outcome === "timeout")
|
|
205
|
+
await killProcessTree(pull);
|
|
206
|
+
pull.stderr?.destroy();
|
|
207
|
+
forget();
|
|
208
|
+
throwIfInterrupted();
|
|
209
|
+
if (outcome === "ok")
|
|
210
|
+
return;
|
|
211
|
+
const reason = outcome === "timeout"
|
|
212
|
+
? `docker pull timed out after ${Math.round(IMAGE_REFRESH_TIMEOUT_MS / 1000)}s`
|
|
213
|
+
: stderr.split("\n").map((line) => line.trim()).find(Boolean) ?? "docker pull failed";
|
|
214
|
+
if (!present)
|
|
215
|
+
throw new Error(`could not pull ${image}: ${reason}`);
|
|
216
|
+
log.warn(`Could not refresh ${image}; using the local copy (${reason})`);
|
|
160
217
|
}
|
|
161
218
|
async function startEphemeralPostgres(image, major, resourceName) {
|
|
162
219
|
const dataVolumeTarget = sandboxDataVolumeTarget(major);
|
|
@@ -190,6 +247,8 @@ async function startEphemeralPostgres(image, major, resourceName) {
|
|
|
190
247
|
"POSTGRES_DB=postgres",
|
|
191
248
|
"-p",
|
|
192
249
|
"127.0.0.1:0:5432", // 随机主机端口,避免撞端口
|
|
250
|
+
// 拉镜像只在 ensureImage 里做(有超时、可中断);缓存恰好在刷新时被清掉的话,这里报错而不是悄悄再拉一次
|
|
251
|
+
"--pull=never",
|
|
193
252
|
`--shm-size=${tuning.shmSize}`,
|
|
194
253
|
image,
|
|
195
254
|
"postgres",
|
|
@@ -476,6 +535,22 @@ function keptSandboxInfo(pg) {
|
|
|
476
535
|
// 真实 Supabase 项目的 manifest 几乎必然含沙箱装不上的托管扩展(pg_graphql 等),
|
|
477
536
|
// 若不按特征过滤,任何硬失败(归档损坏、OOM…)都会被误归因到沙箱。
|
|
478
537
|
const MISSING_EXTENSION_ERROR = /type "[^"]+" does not exist|schema "[^"]+" does not exist|extension "[^"]+" is not available/i;
|
|
538
|
+
// 沙箱小版本早于 2026-11 安全更新(CVE-2026-6460):不认识旧 pg_dump 从已更新的源库导出的列参数。
|
|
539
|
+
// 逐段看 pre-data 失败:主错误(段首 ERROR: 之后、Command was: 之前)整句就是这一条才算,
|
|
540
|
+
// 语句正文或 DETAIL 里出现这个词不算
|
|
541
|
+
const PG_ATTVER_REJECTED = /^pg_restore: error: could not execute query: ERROR:\s+unrecognized parameter "pg_attver"\s+Command was:/;
|
|
542
|
+
/** pre-data 失败里有没有"沙箱不认 pg_attver"这一条(导出给测试) */
|
|
543
|
+
export function sandboxRejectsAttver(preDataFailures) {
|
|
544
|
+
return preDataFailures.some((failure) => PG_ATTVER_REJECTED.test(failure));
|
|
545
|
+
}
|
|
546
|
+
/** pre-data 硬失败;sandboxTooOld = 至少一段失败的主错误是沙箱不认 pg_attver */
|
|
547
|
+
class PreDataRestoreError extends Error {
|
|
548
|
+
sandboxTooOld;
|
|
549
|
+
constructor(message, sandboxTooOld) {
|
|
550
|
+
super(message);
|
|
551
|
+
this.sandboxTooOld = sandboxTooOld;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
479
554
|
/** 兼容层:历史签名保留,分类逻辑的单一权威在统一引擎(restore-engine.ts)。 */
|
|
480
555
|
export function classifyPostDataErrors(stderr) {
|
|
481
556
|
const classified = classifyBlocks(stderr, SANDBOX_MANAGED_ERROR);
|
|
@@ -502,7 +577,7 @@ async function pgRestore(dumpPath, connString, dumpedSchemas, jobs, grants) {
|
|
|
502
577
|
grants: { schemas: dumpedSchemas, recorded: grants },
|
|
503
578
|
});
|
|
504
579
|
if (result.preData.failures.length) {
|
|
505
|
-
throw new
|
|
580
|
+
throw new PreDataRestoreError(`pg_restore failed: ${result.preData.failures.join(" | ")}`, sandboxRejectsAttver(result.preData.failures));
|
|
506
581
|
}
|
|
507
582
|
return {
|
|
508
583
|
supabaseSkipped: result.postData.expectedSkips,
|
|
@@ -699,12 +774,16 @@ async function verifyStorage(location, manifest, verifyAll) {
|
|
|
699
774
|
const scope = sample.length === files.length
|
|
700
775
|
? `all ${files.length} files`
|
|
701
776
|
: `random sample of ${sample.length} of ${files.length} files`;
|
|
777
|
+
// 部分复制的快照(2.12.0):抽样只在已复制的文件里做,结论照旧;覆盖范围写在最前面,先于"all"
|
|
778
|
+
const partial = manifest.storage?.partial;
|
|
779
|
+
const coverage = partial ? `backup copied ${partial.copied} of ${partial.total} Storage files; ` : "";
|
|
702
780
|
return {
|
|
703
781
|
name: "storage file integrity",
|
|
704
782
|
pass: mismatches.length === 0,
|
|
705
|
-
detail:
|
|
706
|
-
|
|
707
|
-
|
|
783
|
+
detail: coverage +
|
|
784
|
+
(mismatches.length === 0
|
|
785
|
+
? `${scope} match their manifest checksums`
|
|
786
|
+
: `${mismatches.length} failed in ${scope}: ${mismatches.slice(0, 5).join(", ")}`),
|
|
708
787
|
};
|
|
709
788
|
}
|
|
710
789
|
// ── 应用自检钩子(语义层)────────────────────────────────────────────
|
|
@@ -797,7 +876,8 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
|
|
|
797
876
|
const sourceMajor = parseInt(manifest.database.serverVersion, 10);
|
|
798
877
|
const toolMajor = await localPgRestoreMajor();
|
|
799
878
|
const sandboxMajor = sandboxMajorFor(sourceMajor, toolMajor);
|
|
800
|
-
const
|
|
879
|
+
const image = sandboxImage(manifest, sandboxMajor);
|
|
880
|
+
const pg = await startEphemeralPostgres(image, sandboxMajor, opts.supervision?.resourceName);
|
|
801
881
|
let pass = false; // 异常路径视为失败,供 finally 决定 --keep 是否保留沙箱
|
|
802
882
|
try {
|
|
803
883
|
if (sandboxMajor !== sourceMajor) {
|
|
@@ -846,6 +926,14 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
|
|
|
846
926
|
// 沙箱装不上扩展 + 错误特征命中"缺类型/schema/扩展" → 假设式归因到沙箱环境
|
|
847
927
|
// (不对备份健康下断言);其余失败与扩展无关,必须原样抛出
|
|
848
928
|
const message = error.message;
|
|
929
|
+
// 必须排在缺扩展归因前面:这类失败的连带错误(type "…" does not exist)也会命中
|
|
930
|
+
// MISSING_EXTENSION_ERROR,2026-11-24 的告警就被误指成了 supabase_vault
|
|
931
|
+
if (error instanceof PreDataRestoreError && error.sandboxTooOld) {
|
|
932
|
+
throw new Error(`restore failed: the drill sandbox (${image}) rejected "SET (pg_attver=…)". The sandbox needs the ` +
|
|
933
|
+
`November 2026 PostgreSQL security fix. Run "docker pull ${image}" and rerun the drill. Older pg_dump ` +
|
|
934
|
+
`versions can write this line when the source already has the fix. Use the latest minor version of ` +
|
|
935
|
+
`pg_dump for new backups. All errors: ${message}`);
|
|
936
|
+
}
|
|
849
937
|
if (unavailable.length && MISSING_EXTENSION_ERROR.test(message)) {
|
|
850
938
|
throw new Error(`restore failed; likely because the drill sandbox cannot install ` +
|
|
851
939
|
`extension(s) ${unavailable.join(", ")}. Original error: ${message}`);
|
|
@@ -988,6 +1076,23 @@ export async function runDrill(config, opts = {}) {
|
|
|
988
1076
|
restoredRowTotal: 0,
|
|
989
1077
|
};
|
|
990
1078
|
}
|
|
1079
|
+
// 这份快照里 Storage 没备上(整体失败),或一个文件也没复制进来:报告里写明,不影响演练结论
|
|
1080
|
+
// (演练验的是快照里有的东西能不能恢复)
|
|
1081
|
+
// (打勾的是"不影响演练结论",名字本身就说没验,扫一眼不会读成"Storage 验过了")
|
|
1082
|
+
if (manifest.storageFailure) {
|
|
1083
|
+
preChecks.push({
|
|
1084
|
+
name: "storage verification skipped",
|
|
1085
|
+
pass: true,
|
|
1086
|
+
detail: `Storage backup failed (${manifest.storageFailure.reason})`,
|
|
1087
|
+
});
|
|
1088
|
+
}
|
|
1089
|
+
else if (manifest.storage?.partial && manifest.storage.files.length === 0) {
|
|
1090
|
+
preChecks.push({
|
|
1091
|
+
name: "storage verification skipped",
|
|
1092
|
+
pass: true,
|
|
1093
|
+
detail: `the backup copied 0 of ${manifest.storage.partial.total} Storage files`,
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
991
1096
|
// Storage 文件完整性(备份含 Storage 时才校验)
|
|
992
1097
|
if (manifest.storage && manifest.storage.files.length) {
|
|
993
1098
|
await opts.supervision?.observe({ phase: "storage" });
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
import { loadConfig, resolvePingUrl } from "./config.js";
|
|
4
|
-
import { backupSummary, createPinger, drillOutcome, pingMessageOf, sensitiveValuesOf } from "./ping.js";
|
|
4
|
+
import { backupSummary, createPinger, drillOutcome, incompleteBackupSummary, pingMessageOf, sensitiveValuesOf } from "./ping.js";
|
|
5
5
|
import { runBackup } from "./backup.js";
|
|
6
6
|
import { runEstimate } from "./estimate.js";
|
|
7
7
|
import { runDrill } from "./drill.js";
|
|
@@ -9,6 +9,7 @@ import { createInterface } from "node:readline/promises";
|
|
|
9
9
|
import { Writable } from "node:stream";
|
|
10
10
|
import { runRestore, NO_SOURCE_DATABASE, restoreStatus, finishRestore } from "./restore.js";
|
|
11
11
|
import { fileRestoreRecords } from "./restore-record.js";
|
|
12
|
+
import { prepareDownloadedSnapshot } from "./dir-store.js";
|
|
12
13
|
import { recordDrillOutcome } from "./drill-record.js";
|
|
13
14
|
import { DEFAULT_EXPORTER_PORT, startExporter } from "./exporter.js";
|
|
14
15
|
import { exitCleanlyOnSignals, interrupted } from "./interrupt.js";
|
|
@@ -91,24 +92,40 @@ program
|
|
|
91
92
|
},
|
|
92
93
|
});
|
|
93
94
|
const manifest = await runBackup(config);
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
95
|
+
const tables = `${manifest.database.tableCount} tables`;
|
|
96
|
+
const partial = manifest.storage?.partial;
|
|
97
|
+
// Storage 没备全时不说 "Backup complete":先说 Storage 的问题,再说数据库存好了
|
|
98
|
+
if (manifest.storageFailure) {
|
|
99
|
+
log.warn(`Storage backup failed. Database saved (${tables}).`);
|
|
100
|
+
}
|
|
101
|
+
else if (partial) {
|
|
102
|
+
log.warn(`Storage backup incomplete. Copied ${partial.copied} of ${partial.total} Storage files. Database saved (${tables}).`);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
log.ok(`Backup complete — ${tables}${manifest.storage ? ` + ${manifest.storage.fileCount} Storage files` : " (database only)"}.`);
|
|
106
|
+
}
|
|
99
107
|
// 只有显式要求 Auth(--auth / BACKUPDRILL_AUTH=on)而它没备上,才让这次运行报失败:
|
|
100
108
|
// 数据库备份照样完成;退出码 3 与"整个备份失败"的 1 区分开。默认情况下做不了只打警告,
|
|
101
109
|
// 升级到这个版本的定时任务不会因此变红
|
|
102
110
|
// (显式要求时 planAuth 把所有"做不了"都记成 failed;只有 schemas 已含 auth 记 skipped——那时数据就在主 dump 里)
|
|
103
111
|
const authRequiredButMissing = config.auth === "on" && manifest.auth?.status === "failed";
|
|
112
|
+
// 2.12.0 起 Storage 失败或只复制了一部分时数据库照样备完;同样用退出码 3 区分,定时任务能看见
|
|
113
|
+
const storageIncomplete = Boolean(manifest.storageFailure || manifest.storage?.partial);
|
|
104
114
|
// stdout 输出机器可读结果,便于在 CI / GitHub Action 里消费
|
|
105
|
-
process.stdout.write(JSON.stringify(authRequiredButMissing
|
|
106
|
-
? {
|
|
115
|
+
process.stdout.write(JSON.stringify(authRequiredButMissing || storageIncomplete
|
|
116
|
+
? {
|
|
117
|
+
ok: false,
|
|
118
|
+
database: { ok: true },
|
|
119
|
+
...(authRequiredButMissing ? { auth: manifest.auth } : {}),
|
|
120
|
+
...(storageIncomplete
|
|
121
|
+
? { storage: manifest.storageFailure ? { failed: manifest.storageFailure } : { partial: manifest.storage?.partial } }
|
|
122
|
+
: {}),
|
|
123
|
+
manifest,
|
|
124
|
+
}
|
|
107
125
|
: { ok: true, manifest }) + "\n");
|
|
108
|
-
if (authRequiredButMissing) {
|
|
126
|
+
if (authRequiredButMissing || storageIncomplete) {
|
|
109
127
|
process.exitCode = 3;
|
|
110
|
-
await ping.fail(
|
|
111
|
-
`${manifest.auth?.reason ?? "unknown reason"}`, sensitiveValuesOf(config, opts.databaseUrl));
|
|
128
|
+
await ping.fail(incompleteBackupSummary(manifest, authRequiredButMissing), sensitiveValuesOf(config, opts.databaseUrl));
|
|
112
129
|
}
|
|
113
130
|
else {
|
|
114
131
|
await ping.success(backupSummary(manifest));
|
|
@@ -229,6 +246,8 @@ program
|
|
|
229
246
|
.option("--skip-auth", "don't restore the snapshot's Auth users; restore the database the way 2.9 did (for example when you " +
|
|
230
247
|
"copied the users into the target yourself)")
|
|
231
248
|
.option("--storage-dir <path>", "local directory to write Storage files to (when not uploading)")
|
|
249
|
+
.option("--from-dir <path>", "restore from a BackupDrill download folder instead of from a bucket. Files are checked against the manifest " +
|
|
250
|
+
"before anything is written to the target; with --finish, only the manifest and the database dump")
|
|
232
251
|
.option("--snapshot <timestamp>", "which snapshot to restore (default: latest)")
|
|
233
252
|
.option("--bucket <name>", "bucket the backups live in")
|
|
234
253
|
.option("--endpoint <url>", "S3-compatible endpoint (for R2/B2)")
|
|
@@ -236,6 +255,7 @@ program
|
|
|
236
255
|
.option("--prefix <prefix>", "key prefix inside the bucket (default: backupdrill)")
|
|
237
256
|
.option("--project-name <name>", "project name used in the object key")
|
|
238
257
|
.action(async (opts) => {
|
|
258
|
+
let prepared = null;
|
|
239
259
|
try {
|
|
240
260
|
// restore --status / --finish:只针对带 Auth 的恢复,按这台机器上的恢复记录查结果、接着做。
|
|
241
261
|
// --status 只读、只要目标连接串,放在读配置之前:不需要桶的凭据
|
|
@@ -261,16 +281,23 @@ program
|
|
|
261
281
|
: `${status.target}: ${status.next}`);
|
|
262
282
|
return;
|
|
263
283
|
}
|
|
284
|
+
// --from-dir:快照在本地目录里,不连任何桶。桶参数一并给出说明用法混了,直接拒绝
|
|
285
|
+
if (opts.fromDir && (opts.bucket || opts.endpoint || opts.region || opts.prefix)) {
|
|
286
|
+
throw new Error("--from-dir restores from a downloaded folder; drop --bucket/--endpoint/--region/--prefix");
|
|
287
|
+
}
|
|
264
288
|
// 源库连接串不再无条件屏蔽:配置/环境里有真实源时,runRestore 的同源阻断门
|
|
265
289
|
// 要拿它比对;纯 flag 驱动(无任何源配置)才退回占位符
|
|
266
290
|
const overrides = {
|
|
267
291
|
projectName: opts.projectName,
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
292
|
+
// --from-dir 不读桶:给 loadConfig 填上不会被用到的桶字段,一台什么都没配的机器也能恢复
|
|
293
|
+
storage: opts.fromDir
|
|
294
|
+
? { bucket: "from-dir", accessKeyId: "from-dir", secretAccessKey: "from-dir" }
|
|
295
|
+
: {
|
|
296
|
+
bucket: opts.bucket,
|
|
297
|
+
endpoint: opts.endpoint,
|
|
298
|
+
region: opts.region,
|
|
299
|
+
prefix: opts.prefix,
|
|
300
|
+
},
|
|
274
301
|
};
|
|
275
302
|
let config;
|
|
276
303
|
try {
|
|
@@ -284,12 +311,23 @@ program
|
|
|
284
311
|
overrides: { ...overrides, databaseUrl: NO_SOURCE_DATABASE },
|
|
285
312
|
});
|
|
286
313
|
}
|
|
314
|
+
// --from-dir:写任何东西之前把下载的文件固定下来、逐个核对(dry-run 也核对:预检要回答"这份下载能不能用")。
|
|
315
|
+
// 不为删暂存目录接管 Ctrl+C / SIGTERM:清理期间恢复流程还活着,会接着往目标写(第 5 轮审查);
|
|
316
|
+
// 收到信号就照 Node 默认立即退出,暂存副本留在系统临时目录(0700)
|
|
317
|
+
prepared = opts.fromDir
|
|
318
|
+
? await prepareDownloadedSnapshot(opts.fromDir, { scope: opts.finish ? "database" : "all" })
|
|
319
|
+
: null;
|
|
320
|
+
if (prepared) {
|
|
321
|
+
log.ok(`Downloaded snapshot ${prepared.snapshot}: ${prepared.files} file(s) match the backup's checksums`);
|
|
322
|
+
}
|
|
323
|
+
const store = prepared?.store;
|
|
287
324
|
if (opts.finish) {
|
|
288
325
|
const finished = await finishRestore(config, {
|
|
289
326
|
targetDatabaseUrl: statusTarget,
|
|
290
327
|
confirmTarget: opts.confirmTarget,
|
|
291
328
|
restoreRecords: fileRestoreRecords(),
|
|
292
329
|
snapshot: opts.snapshot,
|
|
330
|
+
store,
|
|
293
331
|
});
|
|
294
332
|
console.log(JSON.stringify(finished));
|
|
295
333
|
if ((finished.databaseChecks ?? []).some((c) => !c.pass))
|
|
@@ -314,6 +352,7 @@ program
|
|
|
314
352
|
(await promptSecret("Target service-role key (BACKUPDRILL_TARGET_SERVICE_ROLE_KEY)"));
|
|
315
353
|
}
|
|
316
354
|
const result = await runRestore(config, {
|
|
355
|
+
store,
|
|
317
356
|
targetDatabaseUrl,
|
|
318
357
|
targetSupabaseUrl: opts.targetSupabaseUrl,
|
|
319
358
|
targetServiceRoleKey,
|
|
@@ -354,6 +393,10 @@ program
|
|
|
354
393
|
log.error(error.message);
|
|
355
394
|
process.exitCode = 1;
|
|
356
395
|
}
|
|
396
|
+
finally {
|
|
397
|
+
// 核对过的暂存副本在系统临时目录里,恢复结束就删
|
|
398
|
+
await prepared?.cleanup();
|
|
399
|
+
}
|
|
357
400
|
});
|
|
358
401
|
program
|
|
359
402
|
.command("estimate")
|
package/dist/lib.d.ts
CHANGED
|
@@ -12,8 +12,13 @@ export { sameDatabaseTarget } from "./restore.js";
|
|
|
12
12
|
export { runEstimate, project } from "./estimate.js";
|
|
13
13
|
export { loadConfig, requireBucket } from "./config.js";
|
|
14
14
|
export { targetClient, resolveSnapshot, getObjectText, downloadToFile, hashObject, } from "./snapshots.js";
|
|
15
|
-
export { s3SnapshotStore } from "./snapshot-store.js";
|
|
16
|
-
export type { SnapshotStore, SnapshotWriter, SnapshotReader, DumpUpload, StorageFilesLocation, } from "./snapshot-store.js";
|
|
15
|
+
export { s3SnapshotStore, s3StorageSource } from "./snapshot-store.js";
|
|
16
|
+
export type { SnapshotStore, SnapshotWriter, SnapshotReader, DumpUpload, StorageFilesLocation, StorageObjectSource, } from "./snapshot-store.js";
|
|
17
|
+
export { prepareDownloadedSnapshot, parseDownloadIndex, DOWNLOAD_INDEX_FILE } from "./dir-store.js";
|
|
18
|
+
export type { DownloadIndex, PreparedDownload } from "./dir-store.js";
|
|
19
|
+
export { StorageSyncError, STORAGE_KEY_MAX_BYTES, STORAGE_STALL_MS, describeStorageError } from "./storage.js";
|
|
20
|
+
export type { StorageSyncOptions, StorageNotCopiedReason, StoragePartial } from "./storage.js";
|
|
21
|
+
export { STORAGE_NOT_COPIED_REASONS } from "./manifest.js";
|
|
17
22
|
export type { BackupConfig, LoadedBackupConfig, StorageConfig, SupabaseStorageConfig, } from "./config.js";
|
|
18
23
|
export type { AuthPolicyInfo, AuthSection, AuthTriggerInfo, BucketAttrs, ExtensionInfo, Manifest, StorageFile, TableStat, } from "./manifest.js";
|
|
19
24
|
export type { AuthMode } from "./auth-backup.js";
|
package/dist/lib.js
CHANGED
|
@@ -17,4 +17,9 @@ export { runEstimate, project } from "./estimate.js";
|
|
|
17
17
|
export { loadConfig, requireBucket } from "./config.js";
|
|
18
18
|
export { targetClient, resolveSnapshot, getObjectText, downloadToFile, hashObject, } from "./snapshots.js";
|
|
19
19
|
// 快照位置接口:备份、演练、恢复都可以传入自己的实现(托管 worker 的 Google Drive 目标)
|
|
20
|
-
export { s3SnapshotStore } from "./snapshot-store.js";
|
|
20
|
+
export { s3SnapshotStore, s3StorageSource } from "./snapshot-store.js";
|
|
21
|
+
// 2.12.0:下载到本地的快照(托管存储下载脚本的产出)与 restore --from-dir
|
|
22
|
+
export { prepareDownloadedSnapshot, parseDownloadIndex, DOWNLOAD_INDEX_FILE } from "./dir-store.js";
|
|
23
|
+
// 2.12.0:Storage 复制的时间预算、停滞中止、写请求计数(runBackup 的 opts.storage)
|
|
24
|
+
export { StorageSyncError, STORAGE_KEY_MAX_BYTES, STORAGE_STALL_MS, describeStorageError } from "./storage.js";
|
|
25
|
+
export { STORAGE_NOT_COPIED_REASONS } from "./manifest.js";
|
package/dist/manifest.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { StorageNotCopiedReason } from "./storage.js";
|
|
1
2
|
import { type GrantedObject } from "./grants.js";
|
|
2
3
|
/**
|
|
3
4
|
* manifest.json —— 每次快照的自描述清单。
|
|
@@ -54,6 +55,8 @@ export interface ExtensionInfo {
|
|
|
54
55
|
* - (仍是 2)2.9.0 加 database.grants:可加字段,旧读取端忽略它、照旧恢复,不升版本,
|
|
55
56
|
* 免得还没升级的 CLI 和 worker 拒读新快照。
|
|
56
57
|
* - (仍是 2)2.10.0 加 auth:同样是可加字段。旧读取端忽略它和 auth.dump,演练和恢复与之前完全一样。
|
|
58
|
+
* - (仍是 2)2.12.0 加 storage.vanished / storage.partial / storageFailure:可加字段。旧读取端把部分
|
|
59
|
+
* 复制的快照当成"文件清单就是这些",恢复与演练照旧只处理清单里的文件。
|
|
57
60
|
*/
|
|
58
61
|
export declare const MANIFEST_SCHEMA_VERSION = 2;
|
|
59
62
|
export interface Manifest {
|
|
@@ -85,6 +88,24 @@ export interface Manifest {
|
|
|
85
88
|
fileCount: number;
|
|
86
89
|
totalBytes: number;
|
|
87
90
|
files: StorageFile[];
|
|
91
|
+
/** 2.12.0 起:列出时在、复制时已被删的文件(不算缺,不在 files 里) */
|
|
92
|
+
vanished?: {
|
|
93
|
+
bucket: string;
|
|
94
|
+
key: string;
|
|
95
|
+
}[];
|
|
96
|
+
/** 2.12.0 起:有文件没复制时在场;缺席 = 列出的文件(除了被删的)都在 files 里 */
|
|
97
|
+
partial?: {
|
|
98
|
+
copied: number;
|
|
99
|
+
total: number;
|
|
100
|
+
notCopied: {
|
|
101
|
+
reason: StorageNotCopiedReason;
|
|
102
|
+
count: number;
|
|
103
|
+
}[];
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
/** 2.12.0 起:这次 Storage 整体失败(列不出、读不了、写不进),数据库照常完成;此时 storage 为 null */
|
|
107
|
+
storageFailure?: {
|
|
108
|
+
reason: string;
|
|
88
109
|
};
|
|
89
110
|
}
|
|
90
111
|
/**
|
|
@@ -159,6 +180,8 @@ export interface StorageFile {
|
|
|
159
180
|
metadata?: Record<string, unknown>;
|
|
160
181
|
lastModified?: string;
|
|
161
182
|
}
|
|
183
|
+
/** manifest.storage.partial.notCopied[].reason 的取值 */
|
|
184
|
+
export declare const STORAGE_NOT_COPIED_REASONS: readonly StorageNotCopiedReason[];
|
|
162
185
|
/**
|
|
163
186
|
* 解析桶里的 manifest.json,并做**向前兼容**校验:比本程序更新的格式一律拒绝,
|
|
164
187
|
* 明确告诉用户升级,绝不按旧结构硬解析(那会静默产出错误的演练/恢复结果)。
|
package/dist/manifest.js
CHANGED
|
@@ -16,6 +16,8 @@ import { GRANT_PRIVILEGES, GRANT_ROLES, GRANTED_OBJECT_KINDS } from "./grants.js
|
|
|
16
16
|
* - (仍是 2)2.9.0 加 database.grants:可加字段,旧读取端忽略它、照旧恢复,不升版本,
|
|
17
17
|
* 免得还没升级的 CLI 和 worker 拒读新快照。
|
|
18
18
|
* - (仍是 2)2.10.0 加 auth:同样是可加字段。旧读取端忽略它和 auth.dump,演练和恢复与之前完全一样。
|
|
19
|
+
* - (仍是 2)2.12.0 加 storage.vanished / storage.partial / storageFailure:可加字段。旧读取端把部分
|
|
20
|
+
* 复制的快照当成"文件清单就是这些",恢复与演练照旧只处理清单里的文件。
|
|
19
21
|
*/
|
|
20
22
|
export const MANIFEST_SCHEMA_VERSION = 2;
|
|
21
23
|
/**
|
|
@@ -259,8 +261,45 @@ function assertManifestShape(m) {
|
|
|
259
261
|
}
|
|
260
262
|
}
|
|
261
263
|
}
|
|
264
|
+
if (m.storage.vanished !== undefined) {
|
|
265
|
+
if (!Array.isArray(m.storage.vanished))
|
|
266
|
+
malformed("storage.vanished");
|
|
267
|
+
for (const v of m.storage.vanished) {
|
|
268
|
+
if (typeof v?.bucket !== "string" || typeof v?.key !== "string")
|
|
269
|
+
malformed("storage.vanished[]");
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (m.storage.partial !== undefined) {
|
|
273
|
+
const p = m.storage.partial;
|
|
274
|
+
if (typeof p !== "object" || p === null)
|
|
275
|
+
malformed("storage.partial");
|
|
276
|
+
// copied 必须就是 files 的条数,total = copied + 各原因没复制的个数:不然"备了 N 个"的说法和清单对不上
|
|
277
|
+
if (!Number.isSafeInteger(p.copied) || p.copied !== m.storage.files.length || !Number.isSafeInteger(p.total)) {
|
|
278
|
+
malformed("storage.partial.copied/total");
|
|
279
|
+
}
|
|
280
|
+
if (!Array.isArray(p.notCopied) || p.notCopied.length === 0)
|
|
281
|
+
malformed("storage.partial.notCopied");
|
|
282
|
+
for (const n of p.notCopied) {
|
|
283
|
+
if (!STORAGE_NOT_COPIED_REASONS.includes(n?.reason) || !Number.isSafeInteger(n.count) || n.count <= 0) {
|
|
284
|
+
malformed("storage.partial.notCopied[]");
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (p.total !== p.copied + p.notCopied.reduce((sum, n) => sum + n.count, 0)) {
|
|
288
|
+
malformed("storage.partial.total does not match copied + notCopied");
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (m.storageFailure !== undefined) {
|
|
293
|
+
if (typeof m.storageFailure !== "object" || m.storageFailure === null || typeof m.storageFailure.reason !== "string") {
|
|
294
|
+
malformed("storageFailure");
|
|
295
|
+
}
|
|
296
|
+
// 失败的那次 Storage 一个文件也不算进快照:两者同时出现说明 manifest 被拼错了
|
|
297
|
+
if (m.storage !== null)
|
|
298
|
+
malformed("storageFailure with a storage section");
|
|
262
299
|
}
|
|
263
300
|
}
|
|
301
|
+
/** manifest.storage.partial.notCopied[].reason 的取值 */
|
|
302
|
+
export const STORAGE_NOT_COPIED_REASONS = ["time_budget", "read_stalled", "key_too_long"];
|
|
264
303
|
/**
|
|
265
304
|
* 解析桶里的 manifest.json,并做**向前兼容**校验:比本程序更新的格式一律拒绝,
|
|
266
305
|
* 明确告诉用户升级,绝不按旧结构硬解析(那会静默产出错误的演练/恢复结果)。
|
package/dist/ping.d.ts
CHANGED
|
@@ -14,6 +14,11 @@ export declare function createPinger(rawUrl: string | undefined, opts?: {
|
|
|
14
14
|
}): Pinger;
|
|
15
15
|
/** backup 成功时发给监控的一行。快照名取对象键里的目录名(和 drill --snapshot 认的是同一个) */
|
|
16
16
|
export declare function backupSummary(manifest: Manifest): string;
|
|
17
|
+
/**
|
|
18
|
+
* 备份完成、但有要处理的部分没备全时(退出码 3)的通知:先说哪部分出了问题、为什么,再说数据库存在了哪个快照。
|
|
19
|
+
* Storage 和 Auth 同时出问题时两样都写。
|
|
20
|
+
*/
|
|
21
|
+
export declare function incompleteBackupSummary(manifest: Manifest, authRequiredButMissing: boolean): string;
|
|
17
22
|
/** drill 跑完(没抛错)后发哪种 ping、带什么:通过 = 成功;没通过 = 失败,列出没过的检查 */
|
|
18
23
|
export declare function drillOutcome(report: DrillReport): {
|
|
19
24
|
pass: boolean;
|
package/dist/ping.js
CHANGED
|
@@ -128,6 +128,26 @@ export function backupSummary(manifest) {
|
|
|
128
128
|
(manifest.auth?.status === "included" ? ` + ${manifest.auth.rows.users} Auth users` : "") +
|
|
129
129
|
`, snapshot ${manifest.dump.key.split("/").at(-2) ?? manifest.createdAt}`);
|
|
130
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* 备份完成、但有要处理的部分没备全时(退出码 3)的通知:先说哪部分出了问题、为什么,再说数据库存在了哪个快照。
|
|
133
|
+
* Storage 和 Auth 同时出问题时两样都写。
|
|
134
|
+
*/
|
|
135
|
+
export function incompleteBackupSummary(manifest, authRequiredButMissing) {
|
|
136
|
+
const problems = [];
|
|
137
|
+
const partial = manifest.storage?.partial;
|
|
138
|
+
if (manifest.storageFailure)
|
|
139
|
+
problems.push(`Storage backup failed (${manifest.storageFailure.reason}).`);
|
|
140
|
+
else if (partial)
|
|
141
|
+
problems.push(`Storage backup incomplete. Copied ${partial.copied} of ${partial.total} files.`);
|
|
142
|
+
if (authRequiredButMissing) {
|
|
143
|
+
problems.push(`Auth users were required but not backed up (${manifest.auth?.reason ?? "unknown reason"}).`);
|
|
144
|
+
}
|
|
145
|
+
const saved = `Database saved in snapshot ${manifest.dump.key.split("/").at(-2) ?? manifest.createdAt} ` +
|
|
146
|
+
`(${manifest.database.tableCount} tables` +
|
|
147
|
+
(manifest.auth?.status === "included" ? `, ${manifest.auth.rows.users} Auth users` : "") +
|
|
148
|
+
`).`;
|
|
149
|
+
return `backupdrill ${TOOL_VERSION}. ${problems.join(" ")} ${saved}`;
|
|
150
|
+
}
|
|
131
151
|
/** drill 跑完(没抛错)后发哪种 ping、带什么:通过 = 成功;没通过 = 失败,列出没过的检查 */
|
|
132
152
|
export function drillOutcome(report) {
|
|
133
153
|
const outcome = `snapshot ${report.snapshot}, ${report.restoredTableCount} tables / ` +
|
package/dist/recovery-doc.js
CHANGED
|
@@ -298,8 +298,13 @@ ${extensions.length
|
|
|
298
298
|
? ` - extensions required: ${extensions.map((e) => `${e.name} (schema "${e.schema}")`).join(", ")}`
|
|
299
299
|
: " - no extensions recorded"}
|
|
300
300
|
- **Storage files**: ${storage
|
|
301
|
-
?
|
|
302
|
-
|
|
301
|
+
? storage.partial
|
|
302
|
+
? `copied ${storage.partial.copied} of ${storage.partial.total} files (${mb(storage.totalBytes)} MB) to \`${base}/storage/<bucket>/<key>\`. ` +
|
|
303
|
+
`See manifest.json for file checksums and \`storage.partial\` for skip counts by reason`
|
|
304
|
+
: `${storage.fileCount} files, ${mb(storage.totalBytes)} MB under \`${base}/storage/<bucket>/<key>\` — per-file sha256 in manifest.json`
|
|
305
|
+
: manifest.storageFailure
|
|
306
|
+
? `not in this snapshot — copying them failed (${manifest.storageFailure.reason}); the database part is complete`
|
|
307
|
+
: "none (database-only snapshot)"}
|
|
303
308
|
${authText.contentsLine}- **Machine-readable inventory**: \`${base}/manifest.json\`
|
|
304
309
|
|
|
305
310
|
## Not covered — plan for these separately
|
package/dist/restore.d.ts
CHANGED
|
@@ -97,7 +97,7 @@ export declare function nonEmptyTargetMessage(schemas: string[], objectCount: nu
|
|
|
97
97
|
* 900 张表能过、1200 张表报 out of shared memory(2026-10-23,PG 17)。分区多的库会撞上。
|
|
98
98
|
* Supabase 只能用 CLI 调这个参数(会重启数据库),照官方文档的命令给出来。
|
|
99
99
|
*/
|
|
100
|
-
export declare function restoreFailureAdvice(
|
|
100
|
+
export declare function restoreFailureAdvice(failures: string[]): string;
|
|
101
101
|
/**
|
|
102
102
|
* 把一份快照恢复出来:数据库经统一引擎还原进目标(与演练同一条 pg_restore 路径与
|
|
103
103
|
* 错误分类),恢复后跑同一套表级验证;Storage 提供目标凭据时回传+对账(P0-D),
|