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/dist/restore.js CHANGED
@@ -4,9 +4,8 @@ import { createWriteStream } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join, dirname, resolve, sep } from "node:path";
6
6
  import { pipeline } from "node:stream/promises";
7
- import { GetObjectCommand } from "@aws-sdk/client-s3";
8
7
  import { parseManifest } from "./manifest.js";
9
- import { s3SnapshotStore } from "./snapshot-store.js";
8
+ import { s3SnapshotStore, s3StorageSource } from "./snapshot-store.js";
10
9
  import { afterCommit, deferredForeignKeysOf, restoreDatabaseArtifact, userObjectCountSql, installExtensions, projectRefOf, refFromStorageEndpoint, assertNoHostOverride, normalizeHost, } from "./restore-engine.js";
11
10
  import { checkExternalReferences, describe } from "./external-refs.js";
12
11
  import { verifyRestored } from "./drill.js";
@@ -17,7 +16,7 @@ import { orphanedForeignKeysCheck } from "./orphaned-foreign-keys.js";
17
16
  import { grantsCheck } from "./grants.js";
18
17
  import { localPgRestoreMajor, restoreToolTargetBlocker } from "./pgbin.js";
19
18
  import { describeTarget, restoreRecordKey } from "./restore-record.js";
20
- import { AUTH_TABLE_KEYS, authRestoreFailureMessage, authRestoreNotes, targetIdentity, transactionOutcome, authRestorePreflight, largeObjectEntries, psqlProblem, readAuthArchive, restoreWithAuth, } from "./auth-restore.js";
19
+ import { primaryAuthRestoreError, AUTH_TABLE_KEYS, authRestoreFailureMessage, authRestoreNotes, targetIdentity, transactionOutcome, authRestorePreflight, largeObjectEntries, psqlProblem, readAuthArchive, restoreWithAuth, } from "./auth-restore.js";
21
20
  import { parsePgDumpMajor } from "./backup.js";
22
21
  import { log } from "./log.js";
23
22
  /** 归档可读性要求:pg_restore 必须 ≥ max(写入工具版本, 源服务端版本)——格式跟随写入工具。 */
@@ -128,6 +127,17 @@ export function assertRequestApplies(manifest, wantsDatabase, wantsStorageUpload
128
127
  throw new Error("nothing to do: no database restore was requested (--database) and this snapshot has no " +
129
128
  "Storage files to download.");
130
129
  }
130
+ // 部分复制、一个文件也没复制进来的快照:本地下载无事可做;上传到目标时,没记下 bucket 设置也无事可做
131
+ // (没文件也能建 bucket)。不能把空操作报成一次成功恢复。Storage 本来就是空的完整快照不在此列
132
+ const nothingCopied = Boolean(manifest.storage?.partial) && manifest.storage.files.length === 0;
133
+ if (!wantsDatabase && !wantsStorageUpload && nothingCopied) {
134
+ throw new Error("nothing to do: no database restore was requested (--database) and none of this snapshot's " +
135
+ "Storage files were copied when it was taken.");
136
+ }
137
+ if (!wantsDatabase && wantsStorageUpload && nothingCopied && !manifest.storage.buckets?.length) {
138
+ throw new Error("nothing to do: this snapshot has no Storage files or bucket settings to restore. " +
139
+ "To restore its database, add --database.");
140
+ }
131
141
  }
132
142
  /**
133
143
  * 正式执行的确认门(PRD §5.3.3):用户必须键入目标 project ref(或非 Supabase 目标的
@@ -412,8 +422,17 @@ async function dryRunPreflight(config, manifest, targetUrl, storageTarget, alsoR
412
422
  * 900 张表能过、1200 张表报 out of shared memory(2026-10-23,PG 17)。分区多的库会撞上。
413
423
  * Supabase 只能用 CLI 调这个参数(会重启数据库),照官方文档的命令给出来。
414
424
  */
415
- export function restoreFailureAdvice(failure) {
416
- if (!/max_locks_per_transaction/.test(failure))
425
+ export function restoreFailureAdvice(failures) {
426
+ // 2026-11 安全更新(CVE-2026-6460)后:更新前的 pg_dump 导出已更新的源库,会写出
427
+ // `SET (pg_attver=…)`;已更新的目标会忽略它,没更新的目标直接拒绝。
428
+ // 传进来的每一项都以服务端主错误开头(firstRestoreError / 去掉阶段前缀的 psql 错误),
429
+ // 只看开头:语句正文或 DETAIL 里出现这个词不算
430
+ if (failures.some((failure) => /^unrecognized parameter "pg_attver"(?:\s|$)/.test(failure))) {
431
+ return (' The target rejected "SET (pg_attver=…)" from the snapshot. Older pg_dump versions can write this ' +
432
+ "line when the source has the November 2026 PostgreSQL security fix. Update the target to the latest " +
433
+ "minor release for its current PostgreSQL major version and retry.");
434
+ }
435
+ if (!failures.some((failure) => /max_locks_per_transaction/.test(failure)))
417
436
  return "";
418
437
  return (" The target ran out of lock slots: a single-transaction restore holds a lock on every table, index " +
419
438
  "and sequence until it commits. Raise max_locks_per_transaction on the target and retry. On Supabase " +
@@ -597,10 +616,22 @@ export async function runRestore(config, opts) {
597
616
  storageFilesWritten: 0,
598
617
  };
599
618
  assertRequestApplies(manifest, !!opts.targetDatabaseUrl, !!storageTarget);
619
+ // 2.12.0:这份快照里 Storage 只复制了一部分,或这次没备上 —— 恢复前说清楚,别让人以为文件齐了
620
+ if (manifest.storage?.partial) {
621
+ const p = manifest.storage.partial;
622
+ log.warn(`This snapshot holds ${p.copied} of ${p.total} Storage files; the others were not copied when it was taken.`);
623
+ }
624
+ else if (manifest.storageFailure) {
625
+ log.warn(`Storage files are not in this snapshot (copying them failed: ${manifest.storageFailure.reason}).`);
626
+ }
600
627
  // 这次运行会不会碰 Storage(回传到目标,或下载到本地)。只有会碰时,空目标门才该
601
628
  // 提示"库已恢复、只重试 Storage";skipStorage 的纯数据库运行(托管恢复)不该看到这句。
602
629
  const alsoRestoringStorage = !!manifest.storage && !opts.skipStorage;
603
- const storageSource = manifest.storage ? reader.storageFiles(manifest) : null;
630
+ // 本地目录(restore --from-dir)只提供 storageSource;桶里的快照按 storageFiles 的位置读
631
+ const storageLocation = manifest.storage && !reader.storageSource ? reader.storageFiles(manifest) : null;
632
+ const storageSource = manifest.storage
633
+ ? (reader.storageSource?.(manifest) ?? (storageLocation ? s3StorageSource(storageLocation) : null))
634
+ : null;
604
635
  if (alsoRestoringStorage && !storageSource) {
605
636
  throw new Error("the manifest lists Storage files, but this snapshot location cannot hold them — " +
606
637
  "restore the database only (skip Storage).");
@@ -827,7 +858,7 @@ export async function runRestore(config, opts) {
827
858
  await advance("done");
828
859
  if (run.transaction !== "committed") {
829
860
  // 结果由事务本身说了算(没写 COMMIT,或 pg_xact_status 的回答),不再数 schema 里的对象去推断
830
- throw new Error(authRestoreFailureMessage(run) + restoreFailureAdvice(run.failure ?? ""));
861
+ throw new Error(authRestoreFailureMessage(run) + restoreFailureAdvice(run.failure ? [primaryAuthRestoreError(run.failure)] : []));
831
862
  }
832
863
  const committed = run.transaction === "committed";
833
864
  const pass = committed ? run.afterCommit.pass : { expectedSkips: 0, failures: [run.failure] };
@@ -873,7 +904,7 @@ export async function runRestore(config, opts) {
873
904
  " Check the target before doing anything else; restore won't write into it again while those " +
874
905
  "objects are there."
875
906
  : await targetStateAfterFailure(targetUrl, manifest.database.schemas)) +
876
- restoreFailureAdvice(failures.join(" ")));
907
+ restoreFailureAdvice(failures));
877
908
  }
878
909
  result.restoredToDatabase = true;
879
910
  const orphaned = engine.orphanedForeignKeys ?? [];
@@ -973,11 +1004,7 @@ export async function runRestore(config, opts) {
973
1004
  throw new Error(`unsafe storage path escapes output directory: ${f.bucket}/${f.key}`);
974
1005
  }
975
1006
  await mkdir(dirname(dest), { recursive: true });
976
- const res = await storageSource.s3.send(new GetObjectCommand({
977
- Bucket: storageSource.bucket,
978
- Key: `${storageSource.base}/storage/${f.bucket}/${f.key}`,
979
- }));
980
- await pipeline(res.Body, createWriteStream(dest));
1007
+ await pipeline(await storageSource.open(f.bucket, f.key), createWriteStream(dest));
981
1008
  result.storageFilesWritten += 1;
982
1009
  }
983
1010
  result.storageDir = outDir;
@@ -19,6 +19,19 @@ export interface StorageFilesLocation {
19
19
  bucket: string;
20
20
  base: string;
21
21
  }
22
+ /**
23
+ * 读快照里的 Storage 文件(恢复回传、本地下载用)。range 为闭区间字节范围。
24
+ * S3 兼容桶经 s3StorageSource 包一层;下载到本地的快照(restore --from-dir)读本地文件。
25
+ */
26
+ export interface StorageObjectSource {
27
+ open(bucket: string, key: string, range?: {
28
+ start: number;
29
+ end: number;
30
+ }): Promise<Readable>;
31
+ }
32
+ export declare function s3StorageSource(location: StorageFilesLocation): StorageObjectSource;
33
+ /** 两种形态都收:老调用方传桶位置,新的传 StorageObjectSource */
34
+ export declare function asStorageSource(source: StorageObjectSource | StorageFilesLocation): StorageObjectSource;
22
35
  export interface DumpUpload {
23
36
  /** 转储全部写完才 resolve;任何失败都 reject */
24
37
  done: Promise<void>;
@@ -60,8 +73,13 @@ export interface SnapshotReader {
60
73
  bytes: number;
61
74
  sha256: string;
62
75
  }>;
63
- /** 这份快照的 Storage 文件从哪读;实现不支持 Storage 文件时为 null */
76
+ /** 这份快照的 Storage 文件在哪个桶位置(演练按它抽样);实现不支持 Storage 文件时为 null */
64
77
  storageFiles(manifest: Manifest): StorageFilesLocation | null;
78
+ /**
79
+ * 可选(2.12.0 起):恢复时从哪读 Storage 文件。没实现时由 storageFiles 的桶位置读;
80
+ * 本地目录(restore --from-dir)没有桶,只实现这一个。
81
+ */
82
+ storageSource?(manifest: Manifest): StorageObjectSource | null;
65
83
  }
66
84
  /** S3 兼容桶(S3 / R2 / B2 / Wasabi)。行为与抽出这层之前逐字一致。 */
67
85
  export declare function s3SnapshotStore(config: BackupConfig): SnapshotStore;
@@ -1,9 +1,25 @@
1
- import { PutObjectCommand } from "@aws-sdk/client-s3";
1
+ import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
2
2
  import { Upload } from "@aws-sdk/lib-storage";
3
3
  import { requireBucket } from "./config.js";
4
4
  import { targetClient, resolveSnapshot, getObjectText, downloadToFile } from "./snapshots.js";
5
5
  import { renderRecoveryDoc } from "./recovery-doc.js";
6
6
  import { dumpPartSizeFor } from "./part-size.js";
7
+ export function s3StorageSource(location) {
8
+ return {
9
+ async open(bucket, key, range) {
10
+ const got = await location.s3.send(new GetObjectCommand({
11
+ Bucket: location.bucket,
12
+ Key: `${location.base}/storage/${bucket}/${key}`,
13
+ ...(range ? { Range: `bytes=${range.start}-${range.end}` } : {}),
14
+ }));
15
+ return got.Body;
16
+ },
17
+ };
18
+ }
19
+ /** 两种形态都收:老调用方传桶位置,新的传 StorageObjectSource */
20
+ export function asStorageSource(source) {
21
+ return "open" in source ? source : s3StorageSource(source);
22
+ }
7
23
  /** 写入时的键都在 <prefix>/<projectName>/<快照名>/ 下;读取时 Storage 文件的 base 从 dump.key 反推。 */
8
24
  function storageBaseOf(manifest) {
9
25
  return manifest.dump.key.replace(/\/dump\.pgcustom$/, "");
@@ -1,4 +1,4 @@
1
- import { type S3Client } from "@aws-sdk/client-s3";
1
+ import { type StorageFilesLocation, type StorageObjectSource } from "./snapshot-store.js";
2
2
  import type { Manifest, StorageFile } from "./manifest.js";
3
3
  export interface StorageRestoreTarget {
4
4
  supabaseUrl: string;
@@ -72,8 +72,4 @@ export declare function planStorageRestore(target: StorageRestoreTarget, manifes
72
72
  verifiedResidue: number;
73
73
  warnings: string[];
74
74
  }>;
75
- export declare function restoreStorage(source: {
76
- s3: S3Client;
77
- bucket: string;
78
- base: string;
79
- }, target: StorageRestoreTarget, manifest: Manifest): Promise<StorageRestoreSummary>;
75
+ export declare function restoreStorage(sourceOrLocation: StorageObjectSource | StorageFilesLocation, target: StorageRestoreTarget, manifest: Manifest): Promise<StorageRestoreSummary>;
@@ -7,7 +7,7 @@
7
7
  // >= 比较会被多余对象掩蔽缺失(评审第 8 轮)。
8
8
  import { createHash } from "node:crypto";
9
9
  import { Readable } from "node:stream";
10
- import { GetObjectCommand } from "@aws-sdk/client-s3";
10
+ import { asStorageSource } from "./snapshot-store.js";
11
11
  import { sampleStorageFiles } from "./drill.js";
12
12
  import { log } from "./log.js";
13
13
  // PRD §5.4.2:默认小并发、有界超时与重试,均有安全上限
@@ -228,12 +228,7 @@ async function uploadViaTus(source, target, file, summary) {
228
228
  let chunk = null;
229
229
  for (let readAttempt = 1; readAttempt <= MAX_ATTEMPTS; readAttempt++) {
230
230
  try {
231
- const got = await source.s3.send(new GetObjectCommand({
232
- Bucket: source.bucket,
233
- Key: `${source.base}/storage/${file.bucket}/${file.key}`,
234
- Range: `bytes=${offset}-${end}`,
235
- }));
236
- chunk = await collectBody(got.Body);
231
+ chunk = await collectBody(await source.open(file.bucket, file.key, { start: offset, end }));
237
232
  break;
238
233
  }
239
234
  catch (error) {
@@ -332,14 +327,11 @@ async function uploadFile(source, target, file, summary) {
332
327
  let lastError = null;
333
328
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
334
329
  try {
335
- const got = await source.s3.send(new GetObjectCommand({
336
- Bucket: source.bucket,
337
- Key: `${source.base}/storage/${file.bucket}/${file.key}`,
338
- }));
330
+ const body = await source.open(file.bucket, file.key);
339
331
  const res = await fetch(`${target.supabaseUrl}/storage/v1/object/${encodeURIComponent(file.bucket)}/${encodedKey}`, {
340
332
  method: "POST",
341
333
  headers: { ...storageHeaders(target.serviceRoleKey), ...headers },
342
- body: Readable.toWeb(got.Body),
334
+ body: Readable.toWeb(body),
343
335
  signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
344
336
  // @ts-expect-error half-duplex for streaming body
345
337
  duplex: "half",
@@ -581,7 +573,8 @@ export async function planStorageRestore(target, manifest) {
581
573
  warnings: [...scratch.bucketAttrDrift, ...scratch.metadataNotes],
582
574
  };
583
575
  }
584
- export async function restoreStorage(source, target, manifest) {
576
+ export async function restoreStorage(sourceOrLocation, target, manifest) {
577
+ const source = asStorageSource(sourceOrLocation);
585
578
  const summary = emptySummary();
586
579
  const { plans, verifiedResidue } = await readOnlyStoragePlan(target, manifest, summary);
587
580
  summary.filesSkippedIdentical = verifiedResidue.size;
package/dist/storage.d.ts CHANGED
@@ -23,17 +23,90 @@ export declare function measureStorage(cfg: SupabaseStorageConfig): Promise<{
23
23
  totalBytes: number;
24
24
  buckets: string[];
25
25
  }>;
26
+ /** 目标键上限(S3 与 R2 都是 1,024 字节,UTF-8) */
27
+ export declare const STORAGE_KEY_MAX_BYTES = 1024;
28
+ /** 读取多久没有新字节就放弃这个文件 */
29
+ export declare const STORAGE_STALL_MS: number;
30
+ /** 写请求计数的回报粒度 */
31
+ export declare const STORAGE_WRITE_REPORT_EVERY = 1000;
32
+ /** 没复制的原因:时间预算用完 / 读取停滞 / 目标键超过上限 */
33
+ export type StorageNotCopiedReason = "time_budget" | "read_stalled" | "key_too_long";
34
+ export interface StorageSyncOptions {
35
+ /**
36
+ * 时间预算的硬边界:截止前估算传不完的文件不开始,在传的到点中止,截止后不再复制。
37
+ * 省略 = 不设时间预算(CLI 默认)。托管服务传"任务期限 − 30 分钟"。
38
+ */
39
+ deadline?: Date;
40
+ /** 读取停滞多久中止这个文件,也是列举时单个请求的时限;默认 STORAGE_STALL_MS */
41
+ stallMs?: number;
42
+ /** 源读完后、截止之后再等目标确认多久;默认 STORAGE_COMMIT_GRACE_MS(只在设了 deadline 时有意义) */
43
+ commitGraceMs?: number;
44
+ /**
45
+ * 写请求计数回报(给托管服务按账号累计操作费):复制途中每 STORAGE_WRITE_REPORT_EVERY 次回报一次增量,
46
+ * 结束时回报余数。含分片的每一片和 SDK 重试的每一次。
47
+ */
48
+ onWriteRequests?: (delta: number) => void | Promise<void>;
49
+ }
50
+ export interface StorageSyncResult {
51
+ fileCount: number;
52
+ totalBytes: number;
53
+ files: StorageFile[];
54
+ buckets: string[];
55
+ /** 列出时在、读取时已经不存在的文件(用户在复制途中删了它),不算缺 */
56
+ vanished: {
57
+ bucket: string;
58
+ key: string;
59
+ }[];
60
+ /** 有文件没复制时给出;null = 列出的文件(除了被删的)全部复制完 */
61
+ partial: StoragePartial | null;
62
+ /** 本次复制发往目标的请求数 */
63
+ writeRequests: number;
64
+ /**
65
+ * 其中 onWriteRequests 没确认收下的数(回报失败,或最后一批 30 秒内没回来);没传 onWriteRequests 时为 0。
66
+ * 调用方据此补记。最后一批超时的那次回调可能之后才落下,补记要能认出重复。
67
+ */
68
+ writeRequestsUnconfirmed: number;
69
+ }
70
+ export interface StoragePartial {
71
+ copied: number;
72
+ /** 分母 = 开始时列出的文件数 − 复制途中被删的 */
73
+ total: number;
74
+ notCopied: {
75
+ reason: StorageNotCopiedReason;
76
+ count: number;
77
+ }[];
78
+ }
26
79
  /**
27
- * 把 Supabase Storage 的每个文件流式拷贝到目标桶,边拷边算 sha256。
28
- * 目标键:<base>/storage/<bucket>/<原始 key>。
80
+ * Storage 阶段整体失败(列不出来、读不了、写不进目标):数据库那部分不受影响,由调用方记成
81
+ * "这次 Storage 失败",备份照常完成。
82
+ */
83
+ export declare class StorageSyncError extends Error {
84
+ readonly cause?: unknown | undefined;
85
+ constructor(message: string, cause?: unknown | undefined);
86
+ }
87
+ /**
88
+ * 写进 manifest、RECOVERY.md 和日志的失败原因:只用归一化的说法和 S3 错误码,
89
+ * 不带服务端返回的原文(可能含密钥 ID、请求 ID 之类的诊断信息)。
90
+ */
91
+ export declare function describeStorageError(error: unknown): string;
92
+ /**
93
+ * 把 Supabase Storage 的文件流式拷贝到目标桶,边拷边算 sha256。目标键:<base>/storage/<bucket>/<原始 key>。
94
+ *
95
+ * 开始时先把所有 bucket 列完,这份清单就是本次的分母;之后:
96
+ * - 列出时在、读取时 404:跳过,记进 vanished(用户在复制途中删了它,不算缺);
97
+ * - 目标键超过 1,024 字节:不复制,记"键过长";
98
+ * - 读取停滞(stallMs 没有新字节):中止这个文件,记"读取停滞",继续下一个;
99
+ * - 设了 deadline:估算传不完的不开始,在传的到点中止,截止后停止,都记"时间预算";
100
+ * 有没复制的文件时 partial 非空。列不出来、读文件出错(404 以外)、写目标出错:抛 StorageSyncError。
29
101
  */
30
102
  export declare function syncStorage(cfg: SupabaseStorageConfig, target: {
31
103
  client: S3Client;
32
104
  bucket: string;
33
105
  base: string;
34
- }): Promise<{
35
- fileCount: number;
36
- totalBytes: number;
37
- files: StorageFile[];
38
- buckets: string[];
39
- }>;
106
+ }, opts?: StorageSyncOptions): Promise<StorageSyncResult>;
107
+ /** 源读完、到了截止还没等到目标确认时,再多等多久;之后中止并记"没复制" */
108
+ export declare const STORAGE_COMMIT_GRACE_MS = 60000;
109
+ /** 没设 deadline 时(CLI 默认),源读完后最多等目标确认多久 */
110
+ export declare const STORAGE_CONFIRM_TIMEOUT_MS: number;
111
+ /** 发往目标的单个写请求(一片或一次 PutObject)最多等多久;超时算写目标出错 */
112
+ export declare const STORAGE_WRITE_REQUEST_MS: number;