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/dist/storage.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import { Transform } from "node:stream";
|
|
3
3
|
import { pipeline } from "node:stream/promises";
|
|
4
|
-
import { S3Client, ListBucketsCommand, ListObjectsV2Command, GetObjectCommand, } from "@aws-sdk/client-s3";
|
|
5
|
-
import { Upload } from "@aws-sdk/lib-storage";
|
|
4
|
+
import { S3Client, ListBucketsCommand, ListObjectsV2Command, GetObjectCommand, HeadBucketCommand, HeadObjectCommand, PutObjectCommand, CreateMultipartUploadCommand, UploadPartCommand, CompleteMultipartUploadCommand, AbortMultipartUploadCommand, } from "@aws-sdk/client-s3";
|
|
6
5
|
import { log } from "./log.js";
|
|
7
6
|
import { partSizeFor } from "./part-size.js";
|
|
8
7
|
/**
|
|
@@ -21,16 +20,48 @@ function sourceClient(cfg) {
|
|
|
21
20
|
},
|
|
22
21
|
});
|
|
23
22
|
}
|
|
24
|
-
|
|
23
|
+
/**
|
|
24
|
+
* signal 触发,或者过了 ms,就取消;用完调 clear()。自己拼而不用 AbortSignal.any:
|
|
25
|
+
* engines 写的是 Node 20,20.3 之前没有它。SDK 被取消时一律抛 AbortError(describeStorageError 记成 "timed out")。
|
|
26
|
+
*/
|
|
27
|
+
function withTimeout(signal, ms) {
|
|
28
|
+
const controller = new AbortController();
|
|
29
|
+
const follow = () => controller.abort(signal?.reason);
|
|
30
|
+
if (signal?.aborted)
|
|
31
|
+
follow();
|
|
32
|
+
else
|
|
33
|
+
signal?.addEventListener("abort", follow, { once: true });
|
|
34
|
+
const timer = setTimeout(() => controller.abort(new Error(`no response within ${Math.round(ms / 1000)}s`)), ms);
|
|
35
|
+
return {
|
|
36
|
+
signal: controller.signal,
|
|
37
|
+
clear: () => {
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
signal?.removeEventListener("abort", follow);
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** 发一个请求,signal 之外再加一个只管这一个请求的时限 */
|
|
44
|
+
async function sendWithin(ms, signal, run) {
|
|
45
|
+
const limit = withTimeout(signal, ms);
|
|
46
|
+
try {
|
|
47
|
+
return await run(limit.signal);
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
limit.clear();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// 列举的每个请求最多等 requestMs(syncStorage 传读取停滞的时限):没设时间预算(CLI 默认)时,
|
|
54
|
+
// 卡住的列举也不能让备份一直挂着、数据库转储等不到 manifest
|
|
55
|
+
async function resolveBuckets(client, override, requestMs, signal) {
|
|
25
56
|
if (override && override.length)
|
|
26
57
|
return override;
|
|
27
|
-
const res = await client.send(new ListBucketsCommand({}));
|
|
58
|
+
const res = await sendWithin(requestMs, signal, (abortSignal) => client.send(new ListBucketsCommand({}), { abortSignal }));
|
|
28
59
|
return (res.Buckets ?? []).map((b) => b.Name).filter(Boolean);
|
|
29
60
|
}
|
|
30
|
-
async function* listObjects(client, bucket) {
|
|
61
|
+
async function* listObjects(client, bucket, requestMs, signal) {
|
|
31
62
|
let token;
|
|
32
63
|
do {
|
|
33
|
-
const res = await client.send(new ListObjectsV2Command({ Bucket: bucket, ContinuationToken: token }));
|
|
64
|
+
const res = await sendWithin(requestMs, signal, (abortSignal) => client.send(new ListObjectsV2Command({ Bucket: bucket, ContinuationToken: token }), { abortSignal }));
|
|
34
65
|
for (const obj of res.Contents ?? []) {
|
|
35
66
|
if (obj.Key)
|
|
36
67
|
yield { key: obj.Key, size: obj.Size ?? 0 };
|
|
@@ -67,72 +98,445 @@ export function fileMetadataFromS3(got) {
|
|
|
67
98
|
*/
|
|
68
99
|
export async function measureStorage(cfg) {
|
|
69
100
|
const client = sourceClient(cfg);
|
|
70
|
-
const buckets = await resolveBuckets(client, cfg.buckets);
|
|
101
|
+
const buckets = await resolveBuckets(client, cfg.buckets, STORAGE_STALL_MS);
|
|
71
102
|
let fileCount = 0;
|
|
72
103
|
let totalBytes = 0;
|
|
73
104
|
for (const bucket of buckets) {
|
|
74
|
-
for await (const obj of listObjects(client, bucket)) {
|
|
105
|
+
for await (const obj of listObjects(client, bucket, STORAGE_STALL_MS)) {
|
|
75
106
|
fileCount += 1;
|
|
76
107
|
totalBytes += obj.size;
|
|
77
108
|
}
|
|
78
109
|
}
|
|
79
110
|
return { fileCount, totalBytes, buckets };
|
|
80
111
|
}
|
|
112
|
+
/** 计入写请求的命令(单次上传与分片上传的每一步) */
|
|
113
|
+
const WRITE_COMMANDS = new Set([
|
|
114
|
+
"PutObjectCommand",
|
|
115
|
+
"CreateMultipartUploadCommand",
|
|
116
|
+
"UploadPartCommand",
|
|
117
|
+
"CompleteMultipartUploadCommand",
|
|
118
|
+
"AbortMultipartUploadCommand",
|
|
119
|
+
]);
|
|
120
|
+
/** 目标键上限(S3 与 R2 都是 1,024 字节,UTF-8) */
|
|
121
|
+
export const STORAGE_KEY_MAX_BYTES = 1024;
|
|
122
|
+
/** 读取多久没有新字节就放弃这个文件 */
|
|
123
|
+
export const STORAGE_STALL_MS = 2 * 60_000;
|
|
124
|
+
/** 写请求计数的回报粒度 */
|
|
125
|
+
export const STORAGE_WRITE_REPORT_EVERY = 1000;
|
|
126
|
+
/**
|
|
127
|
+
* Storage 阶段整体失败(列不出来、读不了、写不进目标):数据库那部分不受影响,由调用方记成
|
|
128
|
+
* "这次 Storage 失败",备份照常完成。
|
|
129
|
+
*/
|
|
130
|
+
export class StorageSyncError extends Error {
|
|
131
|
+
cause;
|
|
132
|
+
constructor(message, cause) {
|
|
133
|
+
super(message);
|
|
134
|
+
this.cause = cause;
|
|
135
|
+
this.name = "StorageSyncError";
|
|
136
|
+
}
|
|
137
|
+
}
|
|
81
138
|
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
139
|
+
* 写进 manifest、RECOVERY.md 和日志的失败原因:只用归一化的说法和 S3 错误码,
|
|
140
|
+
* 不带服务端返回的原文(可能含密钥 ID、请求 ID 之类的诊断信息)。
|
|
84
141
|
*/
|
|
85
|
-
export
|
|
142
|
+
export function describeStorageError(error) {
|
|
143
|
+
const e = error;
|
|
144
|
+
const code = e?.Code ?? e?.name;
|
|
145
|
+
const status = e?.$metadata?.httpStatusCode;
|
|
146
|
+
if (code === "AccessDenied" || code === "InvalidAccessKeyId" || code === "SignatureDoesNotMatch" || status === 401 || status === 403) {
|
|
147
|
+
return "access denied";
|
|
148
|
+
}
|
|
149
|
+
if (code === "NoSuchBucket")
|
|
150
|
+
return "bucket not found";
|
|
151
|
+
if (code === "SlowDown" || status === 429)
|
|
152
|
+
return "rate limited";
|
|
153
|
+
if (status === 503)
|
|
154
|
+
return "storage service unavailable (HTTP 503)";
|
|
155
|
+
if (code === "AbortError" || code === "TimeoutError")
|
|
156
|
+
return "timed out";
|
|
157
|
+
if (typeof e?.code === "string" && /^(ECONNRESET|ECONNREFUSED|ENOTFOUND|EPIPE|ETIMEDOUT|EAI_AGAIN)$/.test(e.code)) {
|
|
158
|
+
return "network error";
|
|
159
|
+
}
|
|
160
|
+
if (status === 404)
|
|
161
|
+
return "not found";
|
|
162
|
+
return typeof code === "string" && /^[A-Za-z]{2,64}$/.test(code) && code !== "Error" ? `error (${code})` : "unexpected error";
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* 把 Supabase Storage 的文件流式拷贝到目标桶,边拷边算 sha256。目标键:<base>/storage/<bucket>/<原始 key>。
|
|
166
|
+
*
|
|
167
|
+
* 开始时先把所有 bucket 列完,这份清单就是本次的分母;之后:
|
|
168
|
+
* - 列出时在、读取时 404:跳过,记进 vanished(用户在复制途中删了它,不算缺);
|
|
169
|
+
* - 目标键超过 1,024 字节:不复制,记"键过长";
|
|
170
|
+
* - 读取停滞(stallMs 没有新字节):中止这个文件,记"读取停滞",继续下一个;
|
|
171
|
+
* - 设了 deadline:估算传不完的不开始,在传的到点中止,截止后停止,都记"时间预算";
|
|
172
|
+
* 有没复制的文件时 partial 非空。列不出来、读文件出错(404 以外)、写目标出错:抛 StorageSyncError。
|
|
173
|
+
*/
|
|
174
|
+
export async function syncStorage(cfg, target, opts = {}) {
|
|
175
|
+
const stallMs = opts.stallMs ?? STORAGE_STALL_MS;
|
|
86
176
|
const src = sourceClient(cfg);
|
|
87
|
-
|
|
177
|
+
// 1. 基准集合:开始复制之前先列完。设了 deadline 时列举也在预算之内:列不完就算这次 Storage 失败;
|
|
178
|
+
// 不管设没设,每个列举请求 stallMs 内没回来也算失败
|
|
179
|
+
const listed = [];
|
|
180
|
+
let buckets;
|
|
181
|
+
const listing = new AbortController();
|
|
182
|
+
const listTimer = opts.deadline
|
|
183
|
+
? setTimeout(() => listing.abort(), Math.max(0, opts.deadline.getTime() - Date.now()))
|
|
184
|
+
: null;
|
|
185
|
+
try {
|
|
186
|
+
buckets = await resolveBuckets(src, cfg.buckets, stallMs, listing.signal);
|
|
187
|
+
for (const bucket of buckets) {
|
|
188
|
+
for await (const obj of listObjects(src, bucket, stallMs, listing.signal))
|
|
189
|
+
listed.push({ bucket, ...obj });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
if (listing.signal.aborted) {
|
|
194
|
+
throw new StorageSyncError("could not list all Storage files before the time ran out", error);
|
|
195
|
+
}
|
|
196
|
+
throw new StorageSyncError(`could not list Storage files: ${describeStorageError(error)}`, error);
|
|
197
|
+
}
|
|
198
|
+
finally {
|
|
199
|
+
if (listTimer)
|
|
200
|
+
clearTimeout(listTimer);
|
|
201
|
+
}
|
|
202
|
+
// 2. 写请求计数:只在这一段挂在目标客户端上,结束即摘掉
|
|
203
|
+
let writeRequests = 0;
|
|
204
|
+
// 已经确认落下的计数:回调成功之后才前进;失败的那一批留着,下一次回报连同新增一起再报
|
|
205
|
+
let confirmed = 0;
|
|
206
|
+
// 回报按顺序一个接一个落(回调可以是异步的,比如写进数据库)。回报失败只记警告:
|
|
207
|
+
// 计数是操作费的护栏,不该让这次备份失败
|
|
208
|
+
let reporting = Promise.resolve();
|
|
209
|
+
const report = (force) => {
|
|
210
|
+
const onWrite = opts.onWriteRequests;
|
|
211
|
+
if (!onWrite)
|
|
212
|
+
return;
|
|
213
|
+
reporting = reporting.then(async () => {
|
|
214
|
+
const delta = writeRequests - confirmed;
|
|
215
|
+
if (delta <= 0 || (!force && delta < STORAGE_WRITE_REPORT_EVERY))
|
|
216
|
+
return;
|
|
217
|
+
try {
|
|
218
|
+
await onWrite(delta);
|
|
219
|
+
confirmed += delta;
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
log.warn(`Storage write count not recorded yet: ${error.message}`);
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
};
|
|
226
|
+
const counterName = `backupdrill-storage-write-counter-${randomUUID()}`;
|
|
227
|
+
// 只数这次复制往目标桶 <base>/storage/ 下写的请求:同一个客户端上别的读写(或并发的另一次复制,
|
|
228
|
+
// 哪怕前缀相同、桶不同)不算进来
|
|
229
|
+
const storagePrefix = `${target.base}/storage/`;
|
|
230
|
+
target.client.middlewareStack.add((next, context) => async (args) => {
|
|
231
|
+
const input = args.input;
|
|
232
|
+
if (WRITE_COMMANDS.has(String(context.commandName)) &&
|
|
233
|
+
input?.Bucket === target.bucket &&
|
|
234
|
+
typeof input?.Key === "string" &&
|
|
235
|
+
input.Key.startsWith(storagePrefix)) {
|
|
236
|
+
writeRequests += 1;
|
|
237
|
+
report(false);
|
|
238
|
+
}
|
|
239
|
+
return next(args);
|
|
240
|
+
},
|
|
241
|
+
// finalizeRequest 在 SDK 重试之内:每一次实际发出的请求都数到
|
|
242
|
+
{ step: "finalizeRequest", name: counterName });
|
|
88
243
|
const files = [];
|
|
244
|
+
const vanished = [];
|
|
245
|
+
const notCopied = new Map();
|
|
246
|
+
const skip = (reason, n = 1) => notCopied.set(reason, (notCopied.get(reason) ?? 0) + n);
|
|
89
247
|
let totalBytes = 0;
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
248
|
+
let copiedBytes = 0;
|
|
249
|
+
let copyMs = 0;
|
|
250
|
+
try {
|
|
251
|
+
for (let i = 0; i < listed.length; i++) {
|
|
252
|
+
const obj = listed[i];
|
|
253
|
+
const targetKey = `${target.base}/storage/${obj.bucket}/${obj.key}`;
|
|
254
|
+
if (Buffer.byteLength(targetKey, "utf8") > STORAGE_KEY_MAX_BYTES) {
|
|
255
|
+
skip("key_too_long");
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
if (opts.deadline) {
|
|
259
|
+
const remaining = opts.deadline.getTime() - Date.now();
|
|
260
|
+
if (remaining <= 0) {
|
|
261
|
+
skip("time_budget", listed.length - i);
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
// 按本次已测得的速度估算;样本太少时(< 8 MiB 或 < 5 秒)不估,先传
|
|
265
|
+
if (copiedBytes >= 8 * 1024 * 1024 && copyMs >= 5000 && (obj.size * copyMs) / copiedBytes > remaining) {
|
|
266
|
+
skip("time_budget");
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const started = Date.now();
|
|
271
|
+
const outcome = await copyOne(src, target, obj, targetKey, {
|
|
272
|
+
deadline: opts.deadline,
|
|
273
|
+
stallMs,
|
|
274
|
+
commitGraceMs: opts.commitGraceMs ?? STORAGE_COMMIT_GRACE_MS,
|
|
115
275
|
});
|
|
116
|
-
|
|
117
|
-
|
|
276
|
+
if (outcome.kind === "copied") {
|
|
277
|
+
files.push(outcome.file);
|
|
278
|
+
totalBytes += outcome.file.bytes;
|
|
279
|
+
copiedBytes += outcome.file.bytes;
|
|
280
|
+
copyMs += Date.now() - started;
|
|
118
281
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
body.destroy();
|
|
122
|
-
await upload.abort().catch(() => { });
|
|
123
|
-
throw error;
|
|
282
|
+
else if (outcome.kind === "vanished") {
|
|
283
|
+
vanished.push({ bucket: obj.bucket, key: obj.key });
|
|
124
284
|
}
|
|
125
|
-
|
|
126
|
-
|
|
285
|
+
else {
|
|
286
|
+
skip(outcome.reason);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
finally {
|
|
291
|
+
target.client.middlewareStack.remove(counterName);
|
|
292
|
+
report(true);
|
|
293
|
+
// 最后一批最多等 30 秒:回调卡住不能挡住 manifest 落桶
|
|
294
|
+
await Promise.race([reporting, new Promise((res) => setTimeout(res, 30_000).unref())]);
|
|
295
|
+
}
|
|
296
|
+
for (const bucket of buckets) {
|
|
297
|
+
const n = files.filter((f) => f.bucket === bucket).length;
|
|
298
|
+
log.step(` ${bucket}: ${n} files`);
|
|
299
|
+
}
|
|
300
|
+
const notCopiedList = [...notCopied.entries()].map(([reason, count]) => ({ reason, count }));
|
|
301
|
+
const partial = notCopiedList.length
|
|
302
|
+
? { copied: files.length, total: listed.length - vanished.length, notCopied: notCopiedList }
|
|
303
|
+
: null;
|
|
304
|
+
// buckets 含空 bucket(files 推不出来)——manifest v2 的 bucket 属性采集要按它查
|
|
305
|
+
return {
|
|
306
|
+
fileCount: files.length,
|
|
307
|
+
totalBytes,
|
|
308
|
+
files,
|
|
309
|
+
buckets,
|
|
310
|
+
vanished,
|
|
311
|
+
partial,
|
|
312
|
+
writeRequests,
|
|
313
|
+
writeRequestsUnconfirmed: opts.onWriteRequests ? writeRequests - confirmed : 0,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
/** 源读完、到了截止还没等到目标确认时,再多等多久;之后中止并记"没复制" */
|
|
317
|
+
export const STORAGE_COMMIT_GRACE_MS = 60_000;
|
|
318
|
+
/** 没设 deadline 时(CLI 默认),源读完后最多等目标确认多久 */
|
|
319
|
+
export const STORAGE_CONFIRM_TIMEOUT_MS = 15 * 60_000;
|
|
320
|
+
/** 发往目标的单个写请求(一片或一次 PutObject)最多等多久;超时算写目标出错 */
|
|
321
|
+
export const STORAGE_WRITE_REQUEST_MS = 15 * 60_000;
|
|
322
|
+
/**
|
|
323
|
+
* 复制一个文件。目标写请求都带同一个取消信号(不用 lib-storage:它的中止不会传到已经发出的请求上)。
|
|
324
|
+
* - 源还在读的时候到点或停滞:取消读取和写入。正文没发完,S3 / R2 不会存下这个对象;
|
|
325
|
+
* 分片上传会被 AbortMultipartUpload 撤掉(没撤成的未完成分片由桶的生命周期清理)。
|
|
326
|
+
* - 分片上传时,一片在发往目标、读取停下来等它(背压)的那段时间不算读取停滞;停滞计时只在等源的字节时走。
|
|
327
|
+
* 目标的每个写请求另有 STORAGE_WRITE_REQUEST_MS 的时限,超时算写目标出错。
|
|
328
|
+
* - 源已经读完、在等目标确认:慢的目标不算"读取停滞";设了截止就等到截止 + commitGraceMs,没设就等
|
|
329
|
+
* STORAGE_CONFIRM_TIMEOUT_MS,还没确认就取消并记"没复制"。只有目标确认了才算复制成功 —— 不靠事后
|
|
330
|
+
* 按大小猜。(极少数情况下目标其实已经存下、只是确认没回来,这个对象会作为清单之外的多余文件留在
|
|
331
|
+
* 快照目录里;manifest 不会说它在。)
|
|
332
|
+
*/
|
|
333
|
+
async function copyOne(src, target, obj, targetKey, limits) {
|
|
334
|
+
const controller = new AbortController();
|
|
335
|
+
let abortReason = null;
|
|
336
|
+
let sourceDone = false;
|
|
337
|
+
let confirmTimedOut = false;
|
|
338
|
+
const stop = (reason) => {
|
|
339
|
+
if (abortReason || sourceDone)
|
|
340
|
+
return;
|
|
341
|
+
abortReason = reason;
|
|
342
|
+
controller.abort();
|
|
343
|
+
};
|
|
344
|
+
let lastByteAt = Date.now();
|
|
345
|
+
// 正在发往目标的写请求数:大于 0 时读取是在等目标(背压),不是源停滞
|
|
346
|
+
let writesInFlight = 0;
|
|
347
|
+
const destination = {
|
|
348
|
+
begin: () => {
|
|
349
|
+
writesInFlight += 1;
|
|
350
|
+
},
|
|
351
|
+
end: () => {
|
|
352
|
+
writesInFlight -= 1;
|
|
353
|
+
// 目标请求结束后读取才接着走:停滞从这时重新计
|
|
354
|
+
lastByteAt = Date.now();
|
|
355
|
+
},
|
|
356
|
+
};
|
|
357
|
+
const readTimers = [];
|
|
358
|
+
let confirmTimer = null;
|
|
359
|
+
if (limits.deadline) {
|
|
360
|
+
readTimers.push(setTimeout(() => stop("time_budget"), Math.max(0, limits.deadline.getTime() - Date.now())));
|
|
361
|
+
}
|
|
362
|
+
readTimers.push(setInterval(() => {
|
|
363
|
+
if (writesInFlight === 0 && Date.now() - lastByteAt > limits.stallMs)
|
|
364
|
+
stop("read_stalled");
|
|
365
|
+
}, Math.min(5000, Math.max(50, Math.floor(limits.stallMs / 4)))));
|
|
366
|
+
try {
|
|
367
|
+
let got;
|
|
368
|
+
try {
|
|
369
|
+
got = await src.send(new GetObjectCommand({ Bucket: obj.bucket, Key: obj.key }), {
|
|
370
|
+
abortSignal: controller.signal,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
catch (error) {
|
|
374
|
+
if (abortReason)
|
|
375
|
+
return { kind: "skipped", reason: abortReason };
|
|
376
|
+
if (await vanishedAtSource(src, obj, error))
|
|
377
|
+
return { kind: "vanished" };
|
|
378
|
+
throw new StorageSyncError(`could not read a Storage file: ${describeStorageError(error)}`, error);
|
|
379
|
+
}
|
|
380
|
+
const body = got.Body;
|
|
381
|
+
const size = got.ContentLength ?? obj.size;
|
|
382
|
+
const hash = createHash("sha256");
|
|
383
|
+
let bytes = 0;
|
|
384
|
+
const meter = new Transform({
|
|
385
|
+
transform(chunk, _enc, cb) {
|
|
386
|
+
lastByteAt = Date.now();
|
|
387
|
+
hash.update(chunk);
|
|
388
|
+
bytes += chunk.length;
|
|
389
|
+
cb(null, chunk);
|
|
390
|
+
},
|
|
391
|
+
flush(cb) {
|
|
392
|
+
// 源读完:读取侧的到点中止和停滞检测停掉,换成"等目标确认"的时限
|
|
393
|
+
sourceDone = true;
|
|
394
|
+
for (const t of readTimers)
|
|
395
|
+
clearTimeout(t);
|
|
396
|
+
const wait = limits.deadline
|
|
397
|
+
? Math.max(0, limits.deadline.getTime() - Date.now()) + limits.commitGraceMs
|
|
398
|
+
: STORAGE_CONFIRM_TIMEOUT_MS;
|
|
399
|
+
confirmTimer = setTimeout(() => {
|
|
400
|
+
confirmTimedOut = true;
|
|
401
|
+
controller.abort();
|
|
402
|
+
}, wait);
|
|
403
|
+
cb();
|
|
404
|
+
},
|
|
405
|
+
});
|
|
406
|
+
// pipeline(而非裸 pipe)才会传播源流错误;两侧任一失败都终止另一侧
|
|
407
|
+
const copy = pipeline(body, meter);
|
|
408
|
+
try {
|
|
409
|
+
await Promise.all([
|
|
410
|
+
copy,
|
|
411
|
+
putWithCancel(target.client, target.bucket, targetKey, meter, size, controller.signal, destination),
|
|
412
|
+
]);
|
|
413
|
+
}
|
|
414
|
+
catch (error) {
|
|
415
|
+
meter.destroy();
|
|
416
|
+
body.destroy();
|
|
417
|
+
if (!controller.signal.aborted)
|
|
418
|
+
controller.abort();
|
|
419
|
+
if (abortReason)
|
|
420
|
+
return { kind: "skipped", reason: abortReason };
|
|
421
|
+
if (confirmTimedOut)
|
|
422
|
+
return { kind: "skipped", reason: "time_budget" };
|
|
423
|
+
throw new StorageSyncError(`could not copy a Storage file: ${describeStorageError(error)}`, error);
|
|
424
|
+
}
|
|
425
|
+
return {
|
|
426
|
+
kind: "copied",
|
|
427
|
+
file: {
|
|
428
|
+
bucket: obj.bucket,
|
|
127
429
|
key: obj.key,
|
|
128
430
|
bytes,
|
|
129
431
|
sha256: hash.digest("hex"),
|
|
130
432
|
...fileMetadataFromS3(got),
|
|
131
|
-
}
|
|
132
|
-
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
finally {
|
|
437
|
+
for (const t of readTimers)
|
|
438
|
+
clearTimeout(t);
|
|
439
|
+
if (confirmTimer)
|
|
440
|
+
clearTimeout(confirmTimer);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* 把一个流写到目标,每个请求都带 signal。和之前用的 lib-storage 走一样的线路:按分片大小缓冲,
|
|
445
|
+
* 只有一片就一次 PutObject,多片就分片上传;请求正文都是 Buffer(不发 aws-chunked 流式正文,
|
|
446
|
+
* 一些 S3 兼容存储不认)。失败或取消时撤掉分片上传(撤销请求另给 15 秒,不受已触发的 signal 影响)。
|
|
447
|
+
*/
|
|
448
|
+
async function putWithCancel(client, bucket, key, body, size, signal, destination) {
|
|
449
|
+
// 每个写请求:带上整体的取消信号和自己的时限,并让调用方知道"现在在等目标"
|
|
450
|
+
const write = async (run) => {
|
|
451
|
+
destination.begin();
|
|
452
|
+
try {
|
|
453
|
+
return await sendWithin(STORAGE_WRITE_REQUEST_MS, signal, run);
|
|
454
|
+
}
|
|
455
|
+
finally {
|
|
456
|
+
destination.end();
|
|
133
457
|
}
|
|
134
|
-
|
|
458
|
+
};
|
|
459
|
+
const parts = chunksOf(body, partSizeFor(size))[Symbol.asyncIterator]();
|
|
460
|
+
const first = await parts.next();
|
|
461
|
+
const second = first.done ? first : await parts.next();
|
|
462
|
+
if (second.done) {
|
|
463
|
+
await write((abortSignal) => client.send(new PutObjectCommand({ Bucket: bucket, Key: key, Body: first.done ? Buffer.alloc(0) : first.value }), { abortSignal }));
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const created = await write((abortSignal) => client.send(new CreateMultipartUploadCommand({ Bucket: bucket, Key: key }), { abortSignal }));
|
|
467
|
+
const uploadId = created.UploadId;
|
|
468
|
+
try {
|
|
469
|
+
const done = [];
|
|
470
|
+
const upload = async (chunk) => {
|
|
471
|
+
const partNumber = done.length + 1;
|
|
472
|
+
const res = await write((abortSignal) => client.send(new UploadPartCommand({ Bucket: bucket, Key: key, UploadId: uploadId, PartNumber: partNumber, Body: chunk }), { abortSignal }));
|
|
473
|
+
done.push({ ETag: res.ETag, PartNumber: partNumber });
|
|
474
|
+
};
|
|
475
|
+
await upload(first.value);
|
|
476
|
+
await upload(second.value);
|
|
477
|
+
for (let next = await parts.next(); !next.done; next = await parts.next())
|
|
478
|
+
await upload(next.value);
|
|
479
|
+
await write((abortSignal) => client.send(new CompleteMultipartUploadCommand({ Bucket: bucket, Key: key, UploadId: uploadId, MultipartUpload: { Parts: done } }), { abortSignal }));
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
await client
|
|
483
|
+
.send(new AbortMultipartUploadCommand({ Bucket: bucket, Key: key, UploadId: uploadId }), {
|
|
484
|
+
abortSignal: AbortSignal.timeout(15_000),
|
|
485
|
+
})
|
|
486
|
+
.catch(() => { });
|
|
487
|
+
throw error;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/** 把流切成固定大小的块(最后一块可以小一些) */
|
|
491
|
+
async function* chunksOf(stream, size) {
|
|
492
|
+
let pending = [];
|
|
493
|
+
let pendingBytes = 0;
|
|
494
|
+
for await (const chunk of stream) {
|
|
495
|
+
let buf = chunk;
|
|
496
|
+
while (buf.length) {
|
|
497
|
+
const take = Math.min(size - pendingBytes, buf.length);
|
|
498
|
+
pending.push(buf.subarray(0, take));
|
|
499
|
+
pendingBytes += take;
|
|
500
|
+
buf = buf.subarray(take);
|
|
501
|
+
if (pendingBytes === size) {
|
|
502
|
+
yield Buffer.concat(pending);
|
|
503
|
+
pending = [];
|
|
504
|
+
pendingBytes = 0;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (pendingBytes)
|
|
509
|
+
yield Buffer.concat(pending);
|
|
510
|
+
}
|
|
511
|
+
/** 复核请求(HeadObject / HeadBucket)的时限 */
|
|
512
|
+
const STORAGE_RECHECK_MS = 15_000;
|
|
513
|
+
/**
|
|
514
|
+
* 读取时 404,是不是"这个文件在复制途中被删了":明确的 NoSuchKey 才直接算;其他 404 再用 HeadObject
|
|
515
|
+
* 复核,对象不在、而且桶还能访问(HeadBucket 成功),才算被删;桶没了、端点错了都是失败。
|
|
516
|
+
*/
|
|
517
|
+
async function vanishedAtSource(src, obj, error) {
|
|
518
|
+
const e = error;
|
|
519
|
+
const code = e?.Code ?? e?.name;
|
|
520
|
+
if (code === "NoSuchKey")
|
|
521
|
+
return true;
|
|
522
|
+
if (e?.$metadata?.httpStatusCode !== 404 || code === "NoSuchBucket")
|
|
523
|
+
return false;
|
|
524
|
+
try {
|
|
525
|
+
await src.send(new HeadObjectCommand({ Bucket: obj.bucket, Key: obj.key }), {
|
|
526
|
+
abortSignal: AbortSignal.timeout(STORAGE_RECHECK_MS),
|
|
527
|
+
});
|
|
528
|
+
return false; // 对象还在:那个 404 不是"被删了"
|
|
529
|
+
}
|
|
530
|
+
catch (headError) {
|
|
531
|
+
const h = headError;
|
|
532
|
+
if (!((h?.name === "NotFound" || h?.Code === "NotFound") && h?.$metadata?.httpStatusCode === 404))
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
try {
|
|
536
|
+
await src.send(new HeadBucketCommand({ Bucket: obj.bucket }), { abortSignal: AbortSignal.timeout(STORAGE_RECHECK_MS) });
|
|
537
|
+
return true;
|
|
538
|
+
}
|
|
539
|
+
catch {
|
|
540
|
+
return false;
|
|
135
541
|
}
|
|
136
|
-
// buckets 含空 bucket(files 推不出来)——manifest v2 的 bucket 属性采集要按它查
|
|
137
|
-
return { fileCount: files.length, totalBytes, files, buckets };
|
|
138
542
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "backupdrill",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.12.1",
|
|
4
4
|
"description": "Open-source CLI to back up a Supabase project to your own S3/R2/B2 bucket (the Postgres database, Auth users when your role can read them, and Storage files once you add the project's Storage S3 keys), then run a restore drill that proves the backup restores.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/plugin/README.md
CHANGED
|
@@ -7,7 +7,7 @@ Back up a Supabase project to a bucket you own and prove the backup restores, by
|
|
|
7
7
|
- `drill` restores a snapshot into a throwaway Postgres in Docker, checks that the tables and their data came back, and checksums a sample of the Storage files.
|
|
8
8
|
- `restore` puts a snapshot into a new, empty Supabase project, after a dry run and only once you confirm the target.
|
|
9
9
|
|
|
10
|
-
The agent runs every command as `npx -y backupdrill@2.11.
|
|
10
|
+
The agent runs every command as `npx -y backupdrill@2.11.2`, so the CLI version stays fixed.
|
|
11
11
|
|
|
12
12
|
## What you need
|
|
13
13
|
|
|
@@ -56,7 +56,7 @@ Everything runs on your machine:
|
|
|
56
56
|
|
|
57
57
|
- `npx` downloads the `backupdrill` package from the npm registry the first time.
|
|
58
58
|
- The CLI connects to your Supabase project's database, to its Storage if you add Storage S3 keys, and to your bucket. `restore` also connects to the target project you name.
|
|
59
|
-
- `drill` starts a temporary Postgres container in Docker.
|
|
59
|
+
- `drill` starts a temporary Postgres container in Docker. Before each drill, Docker checks Docker Hub and downloads any missing image layers. If that fails and a local image is available, `drill` uses it.
|
|
60
60
|
- Nothing goes to BackupDrill. There is no account, telemetry or license check.
|
|
61
61
|
|
|
62
62
|
What the agent reads while it works, such as command output with table names, row counts and file names, goes to your model provider like the rest of your conversation. The CLI itself never deletes objects in your bucket.
|
|
@@ -7,7 +7,7 @@ description: Use when the user wants to back up a Supabase project to their own
|
|
|
7
7
|
|
|
8
8
|
backupdrill is an open-source (MIT) command-line tool. `backup` dumps the project's Postgres database with `pg_dump`, copies Storage files too once their S3 keys are set, and writes everything to a bucket the user owns, with a checksummed `manifest.json` and a `RECOVERY.md` in every snapshot. `drill` restores a snapshot into a throwaway Postgres in Docker and checks that it came back. The CLI runs on the user's machine. It talks to their Supabase project, their bucket and the local Docker daemon, and sends nothing to BackupDrill.
|
|
9
9
|
|
|
10
|
-
Always run it as `npx -y backupdrill@2.11.
|
|
10
|
+
Always run it as `npx -y backupdrill@2.11.2 <command>`, so every run uses the same version. Every command and option is documented at [backupdrill.com/docs/cli](https://backupdrill.com/docs/cli); check there before using an option this skill doesn't mention.
|
|
11
11
|
|
|
12
12
|
If the user asks what Supabase already backs up on their plan, wants a plain `pg_dump` backup without the CLI, or wants to test a restore by hand, read [references/postgres-backup-basics.md](references/postgres-backup-basics.md).
|
|
13
13
|
|
|
@@ -71,7 +71,7 @@ Every backup reads the whole database, and every configured Storage file, out of
|
|
|
71
71
|
```sh
|
|
72
72
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
73
73
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
74
|
-
npx -y backupdrill@2.11.
|
|
74
|
+
npx -y backupdrill@2.11.2 estimate --plan pro )
|
|
75
75
|
```
|
|
76
76
|
|
|
77
77
|
Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the projection back before suggesting a daily schedule. On a large database, suggest weekly.
|
|
@@ -82,7 +82,7 @@ Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the pr
|
|
|
82
82
|
report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "stdout → $report"
|
|
83
83
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
84
84
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
85
|
-
npx -y backupdrill@2.11.
|
|
85
|
+
npx -y backupdrill@2.11.2 backup ) > "$report"
|
|
86
86
|
```
|
|
87
87
|
|
|
88
88
|
- The progress lines on stderr show where everything went (`Dumping → s3://…`, `Manifest written → s3://…`) and end with `Backup complete — N tables + M Storage files`. stdout goes to the file named on the first line, a new one each run that only the user can read: one line of JSON with the whole manifest, which lists every table and Storage file, so read only the fields you need from it.
|
|
@@ -95,10 +95,10 @@ report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "
|
|
|
95
95
|
```sh
|
|
96
96
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
97
97
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
98
|
-
npx -y backupdrill@2.11.
|
|
98
|
+
npx -y backupdrill@2.11.2 drill )
|
|
99
99
|
```
|
|
100
100
|
|
|
101
|
-
- It reads the latest snapshot from the bucket, restores it into a throwaway Postgres container, runs its checks and removes the container. It doesn't connect to the Supabase project.
|
|
101
|
+
- It reads the latest snapshot from the bucket, restores it into a throwaway Postgres container, runs its checks and removes the container. It doesn't connect to the Supabase project. Before starting Postgres, `drill` checks Docker Hub and downloads any missing image layers. If the pull fails and a local image is available, `drill` uses it.
|
|
102
102
|
- `--snapshot <timestamp>` picks an older snapshot. `--verify-all-files` checksums every Storage file instead of a sample.
|
|
103
103
|
- `--check-cmd "<command>"` runs the user's own test against the restored copy, with its connection string in `BACKUPDRILL_SANDBOX_URL`. It connects as a superuser, so it can check data and business rules but not row-level security.
|
|
104
104
|
- stdout ends with `{"ok":...,"report":{...}}`. Go through the check lines. If the drill fails, quote the failing check as printed and don't guess at a cause it doesn't state.
|
|
@@ -114,7 +114,7 @@ A restore writes data, so go step by step and let the user drive.
|
|
|
114
114
|
```sh
|
|
115
115
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
116
116
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
117
|
-
npx -y backupdrill@2.11.
|
|
117
|
+
npx -y backupdrill@2.11.2 restore --database --target-supabase-url https://<target-ref>.supabase.co --dry-run )
|
|
118
118
|
```
|
|
119
119
|
|
|
120
120
|
Leave out `--target-supabase-url` when the snapshot is database only. To write Storage files to a local folder instead of the new project, use `--storage-dir ./recovered`.
|
|
@@ -99,7 +99,7 @@ jobs:
|
|
|
99
99
|
|
|
100
100
|
- name: Run backupdrill
|
|
101
101
|
# Pinned so every run uses the same CLI. Raise it on purpose when you upgrade.
|
|
102
|
-
run: npx -y backupdrill@2.11.
|
|
102
|
+
run: npx -y backupdrill@2.11.2 backup
|
|
103
103
|
env:
|
|
104
104
|
# --- required ---
|
|
105
105
|
BACKUPDRILL_DATABASE_URL: ${{ secrets.BACKUPDRILL_DATABASE_URL }}
|