@cardonjs/backups 0.0.0-stage → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/FORMAT.md +147 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1237 -2
  4. package/dist/copy.d.ts +175 -0
  5. package/dist/copy.d.ts.map +1 -0
  6. package/dist/copy.js +863 -0
  7. package/dist/copy.js.map +1 -0
  8. package/dist/encryption.d.ts +203 -0
  9. package/dist/encryption.d.ts.map +1 -0
  10. package/dist/encryption.js +609 -0
  11. package/dist/encryption.js.map +1 -0
  12. package/dist/export.d.ts +201 -0
  13. package/dist/export.d.ts.map +1 -0
  14. package/dist/export.js +447 -0
  15. package/dist/export.js.map +1 -0
  16. package/dist/index.d.ts +14 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +14 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/keys.d.ts +28 -0
  21. package/dist/keys.d.ts.map +1 -0
  22. package/dist/keys.js +97 -0
  23. package/dist/keys.js.map +1 -0
  24. package/dist/metadata.d.ts +49 -0
  25. package/dist/metadata.d.ts.map +1 -0
  26. package/dist/metadata.js +51 -0
  27. package/dist/metadata.js.map +1 -0
  28. package/dist/restore.d.ts +97 -0
  29. package/dist/restore.d.ts.map +1 -0
  30. package/dist/restore.js +276 -0
  31. package/dist/restore.js.map +1 -0
  32. package/dist/retention.d.ts +153 -0
  33. package/dist/retention.d.ts.map +1 -0
  34. package/dist/retention.js +295 -0
  35. package/dist/retention.js.map +1 -0
  36. package/dist/run.d.ts +94 -0
  37. package/dist/run.d.ts.map +1 -0
  38. package/dist/run.js +129 -0
  39. package/dist/run.js.map +1 -0
  40. package/dist/sniff.d.ts +15 -0
  41. package/dist/sniff.d.ts.map +1 -0
  42. package/dist/sniff.js +47 -0
  43. package/dist/sniff.js.map +1 -0
  44. package/dist/workflow.d.ts +102 -0
  45. package/dist/workflow.d.ts.map +1 -0
  46. package/dist/workflow.js +298 -0
  47. package/dist/workflow.js.map +1 -0
  48. package/llms.txt +249 -0
  49. package/package.json +76 -3
package/dist/copy.js ADDED
@@ -0,0 +1,863 @@
1
+ /**
2
+ * Streams a ready export into R2. The copy is given the `ready` answer itself, never a bookmark
3
+ * to poll: Cloudflare hands out a completed export's signed URL once (observed on 2026-11-20; a
4
+ * second poll answers "Not currently exporting anything."), so the code that receives `ready` is
5
+ * the code that downloads. Two paths, both atomic (the object appears only when the whole dump is
6
+ * in and checked):
7
+ *
8
+ * - The answer states its length, the length is at most `singlePutLimit` (4 GiB by default) and
9
+ * the runtime has `FixedLengthStream` (Workers): one `put` of a stream of that length, through
10
+ * a check that counts the bytes and reads the start. R2 refuses a stream of unknown length, and
11
+ * a `put` whose stream errors stores nothing.
12
+ * - Otherwise (no `Content-Length`, a compressed answer, a larger dump, or Node): the dump is read
13
+ * in parts of `partSize` bytes. A dump that fits in one part is one `put` of those bytes; a
14
+ * larger one is a multipart upload, completed only after the last part and aborted on any
15
+ * failure.
16
+ *
17
+ * Where the runtime has `crypto.DigestStream` (Workers), the dump's SHA-256 is computed on the way
18
+ * and written after the dump, once it is checked, to a sidecar object `<key>.sha256` (a multipart
19
+ * upload's metadata is fixed when it starts, before the digest is known). The sidecar is also
20
+ * the proof that a copy finished: a retried copy reuses an object only with it, only when it
21
+ * names the very object at the key (its R2 `version`), and only after reading the object back
22
+ * and finding the sidecar's digest (so a reused result's digest is the stored bytes'). It detects
23
+ * corruption, not tampering (whoever can rewrite the dump can rewrite the sidecar). Node has no
24
+ * incremental digest of a web stream (`crypto.subtle.digest` takes the whole input), so there
25
+ * the copy writes no sidecar and reuse rests on the size check alone.
26
+ *
27
+ * One deadline (`timeoutMs`) bounds the whole copy: every R2 call (`head`, `get`, `put`,
28
+ * `createMultipartUpload`, `uploadPart`, `complete`, the sidecar), the download and every read of
29
+ * its body race it. Past it the copy answers `timeout` and gives an open multipart
30
+ * upload a few seconds to abort. It issues no delete after the deadline (one landing late could
31
+ * remove a retry's object). A write that was already in flight may still land: it holds this
32
+ * export's complete, checked dump (or its digest), without a sidecar until a retry writes one.
33
+ *
34
+ * With `encryption` (opt-in), the dump is encrypted on the way (see `encryption.ts` and
35
+ * `FORMAT.md`): the plaintext is counted and checked as SQL, then encrypted, and what R2 stores,
36
+ * what the digest covers and what `size` reports are the encrypted bytes. The encrypted length
37
+ * is a function of the plaintext length, so a dump with `Content-Length` still goes as one
38
+ * known-length `put`; the path in parts encrypts before splitting into parts. Reuse also requires
39
+ * the object's encryption (none, or the scheme and key id) to be this call's; a copy made in
40
+ * plain or with another key id is written again under the current settings.
41
+ */
42
+ import { createEncryptStream, decryptBackup, ENCRYPTION_SCHEME, EncryptionTooLarge, encryptedSize, encryptionOption, isIdentity, } from "./encryption.js";
43
+ import { isValidBookmark, } from "./export.js";
44
+ import { parseKeyAnyPrefix } from "./keys.js";
45
+ import { digestKey, METADATA } from "./metadata.js";
46
+ import { createSqlSniffer } from "./sniff.js";
47
+ const MiB = 1024 * 1024;
48
+ const GiB = 1024 * MiB;
49
+ const DEFAULT_PART_SIZE = 10 * MiB;
50
+ /** R2's minimum part size (every part but the last). */
51
+ const MIN_PART_SIZE = 5 * MiB;
52
+ /**
53
+ * The largest part: the copy holds at most two parts at once (the one being sent and the next
54
+ * being filled), so 32 MiB keeps it near 64 MiB, half of a Worker's 128 MB of memory, which the
55
+ * runtime, the streams and the app's own code share.
56
+ */
57
+ const MAX_PART_SIZE = 32 * MiB;
58
+ /** R2's limit on parts per upload. */
59
+ const MAX_PARTS = 10_000;
60
+ /**
61
+ * The largest dump sent as one `put`. R2 documents about 5 GiB for a single upload (not verified
62
+ * here); 4 GiB leaves a margin. Larger dumps take the multipart path even with a known length.
63
+ */
64
+ const DEFAULT_SINGLE_PUT_LIMIT = 4 * GiB;
65
+ /** Below the Workflow steps' 30-minute timeout, so the copy reports `timeout` itself. */
66
+ const DEFAULT_TIMEOUT_MS = 25 * 60_000;
67
+ const MAX_TIMEOUT_MS = 6 * 60 * 60_000;
68
+ /** After the deadline, how long an open multipart upload's abort is waited for. */
69
+ const CLEANUP_GRACE_MS = 5000;
70
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
71
+ /** A sidecar holds 64 hex characters; a trailing newline (or CRLF) is tolerated. */
72
+ const SIDECAR_MIN_SIZE = 64;
73
+ const SIDECAR_MAX_SIZE = 66;
74
+ /** A run identity: a UUID (`crypto.randomUUID()`) or any short id of this shape. */
75
+ const RUN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
76
+ /** Whether `value` is a valid `run` for `copyExport`. */
77
+ export function isValidRun(value) {
78
+ return typeof value === "string" && RUN.test(value);
79
+ }
80
+ const fail = (reason, retryable) => ({
81
+ ok: false,
82
+ reason,
83
+ retryable,
84
+ });
85
+ function fixedLengthStream(length) {
86
+ return typeof FixedLengthStream === "function" ? new FixedLengthStream(length) : undefined;
87
+ }
88
+ /** `crypto.DigestStream` (Workers), or `undefined` where the runtime has none (Node). */
89
+ function digestStreamClass() {
90
+ if (typeof crypto === "undefined")
91
+ return undefined;
92
+ const value = crypto.DigestStream;
93
+ return typeof value === "function" ? value : undefined;
94
+ }
95
+ function createDigest() {
96
+ const Digest = digestStreamClass();
97
+ if (Digest === undefined) {
98
+ return {
99
+ available: false,
100
+ write: async () => undefined,
101
+ finish: async () => null,
102
+ abort: async () => undefined,
103
+ };
104
+ }
105
+ const stream = new Digest("SHA-256");
106
+ const writer = stream.getWriter();
107
+ return {
108
+ available: true,
109
+ write: (chunk) => writer.write(chunk),
110
+ async finish() {
111
+ await writer.close();
112
+ const bytes = new Uint8Array(await stream.digest);
113
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
114
+ },
115
+ abort: () => writer.abort().catch(() => undefined),
116
+ };
117
+ }
118
+ /**
119
+ * `body`, erroring as soon as `signal` aborts, even while a read is pending (a stalled
120
+ * connection). Each read races the signal, so this does not depend on the source honouring it
121
+ * (`pipeThrough`'s own `signal` did not end a stalled pull in workerd).
122
+ */
123
+ function bounded(body, signal) {
124
+ const reader = body.getReader();
125
+ let stop = () => undefined;
126
+ const aborted = new Promise((_, reject) => {
127
+ stop = () => reject(new Error("the download's deadline passed"));
128
+ });
129
+ aborted.catch(() => undefined);
130
+ if (signal.aborted)
131
+ stop();
132
+ else
133
+ signal.addEventListener("abort", stop, { once: true });
134
+ const release = () => signal.removeEventListener("abort", stop);
135
+ return new ReadableStream({
136
+ async pull(controller) {
137
+ let next;
138
+ try {
139
+ next = await Promise.race([reader.read(), aborted]);
140
+ }
141
+ catch (error) {
142
+ release();
143
+ // Not awaited: a stalled source may never settle its cancel.
144
+ reader.cancel().catch(() => undefined);
145
+ controller.error(error);
146
+ return;
147
+ }
148
+ if (next.done) {
149
+ release();
150
+ controller.close();
151
+ }
152
+ else {
153
+ controller.enqueue(next.value);
154
+ }
155
+ },
156
+ cancel(reason) {
157
+ release();
158
+ // Not awaited either: cancelling must not wait on a stalled source.
159
+ reader.cancel(reason).catch(() => undefined);
160
+ },
161
+ });
162
+ }
163
+ class CopyAbort extends Error {
164
+ reason;
165
+ retryable;
166
+ constructor(reason, retryable) {
167
+ super(reason);
168
+ this.reason = reason;
169
+ this.retryable = retryable;
170
+ this.name = "CopyAbort";
171
+ }
172
+ }
173
+ /** Thrown by `Deadline.bound` once the copy's deadline has passed. */
174
+ class DeadlinePassed extends Error {
175
+ constructor() {
176
+ super("the copy's deadline passed");
177
+ this.name = "DeadlinePassed";
178
+ }
179
+ }
180
+ function createDeadline(ms) {
181
+ const signal = AbortSignal.timeout(ms);
182
+ let reject = () => undefined;
183
+ const passed = new Promise((_, fail) => {
184
+ reject = fail;
185
+ });
186
+ passed.catch(() => undefined);
187
+ const onAbort = () => reject(new DeadlinePassed());
188
+ if (signal.aborted)
189
+ onAbort();
190
+ else
191
+ signal.addEventListener("abort", onAbort, { once: true });
192
+ return { signal, bound: (promise) => Promise.race([promise, passed]) };
193
+ }
194
+ /** Waits for `promise` to settle, at most `ms` (cleanup after the deadline: best effort). */
195
+ async function settleWithin(promise, ms) {
196
+ let timer;
197
+ await Promise.race([
198
+ promise.then(() => undefined, () => undefined),
199
+ new Promise((resolve) => {
200
+ timer = setTimeout(resolve, ms);
201
+ }),
202
+ ]);
203
+ if (timer !== undefined)
204
+ clearTimeout(timer);
205
+ }
206
+ function isR2Bucket(value) {
207
+ return (typeof value === "object" &&
208
+ value !== null &&
209
+ ["put", "head", "get", "delete", "list", "createMultipartUpload"].every((method) => typeof value[method] === "function"));
210
+ }
211
+ /**
212
+ * Deletes `key`, ignoring a failure (a later retry or retention handles it). Never after the
213
+ * deadline: a delete that landed late could remove the object a retry has written since.
214
+ */
215
+ async function discard(bucket, key, deadline) {
216
+ if (deadline.signal.aborted)
217
+ return;
218
+ await deadline.bound(bucket.delete(key)).catch(() => undefined);
219
+ }
220
+ function wholeIn(value, min, max) {
221
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max;
222
+ }
223
+ /**
224
+ * The identity of one write of an object, as R2 returns it from `put`, `complete`, `head` and
225
+ * `get` (`version`, unique per write; `etag` where a binding gives no version), or `null`.
226
+ * Checked in workerd: `put` (of a string or a `FixedLengthStream`) and a multipart `complete`
227
+ * return the same `version` as a later `head` or `get` of the key.
228
+ */
229
+ function objectIdentity(object) {
230
+ if (object === null || object === undefined)
231
+ return null;
232
+ const { version, etag } = object;
233
+ if (typeof version === "string" && version !== "")
234
+ return `version:${version}`;
235
+ if (typeof etag === "string" && etag !== "")
236
+ return `etag:${etag}`;
237
+ return null;
238
+ }
239
+ /**
240
+ * Reads `object`'s body back once (an R2 read, no export) and proves it is what this copy would
241
+ * have written. With `encryption`: the whole object goes through `decryptBackup` with the
242
+ * current key only, expecting this backup's database id, object key and key id (the plaintext
243
+ * is discarded), so forged metadata over a plain object, another key's object or another
244
+ * backup's object is refused. Without it: the body must start like SQL (an encrypted object
245
+ * with its metadata stripped is refused). In the same pass, where `Digest` exists, its SHA-256.
246
+ * `{ ok: false }` when any of it fails; every read races the deadline.
247
+ */
248
+ async function readBack(object, deadline, Digest, encryption, identity) {
249
+ const digest = Digest === undefined ? undefined : new Digest("SHA-256");
250
+ const writer = digest?.getWriter();
251
+ let stream = bounded(object.body, deadline.signal);
252
+ if (writer !== undefined) {
253
+ stream = stream.pipeThrough(new TransformStream({
254
+ async transform(chunk, controller) {
255
+ await writer.write(chunk.slice());
256
+ controller.enqueue(chunk);
257
+ },
258
+ }));
259
+ }
260
+ if (encryption !== null) {
261
+ // `keyId: current`: an authentic object of another listed key is not this copy's either.
262
+ stream = stream.pipeThrough(decryptBackup(encryption, {
263
+ expected: { ...identity, keyId: encryption.current },
264
+ }));
265
+ }
266
+ else {
267
+ const sniffer = createSqlSniffer();
268
+ stream = stream.pipeThrough(new TransformStream({
269
+ transform(chunk) {
270
+ if (sniffer.feed(chunk) === "bad")
271
+ throw new Error("not SQL");
272
+ },
273
+ flush() {
274
+ if (sniffer.end() !== "ok")
275
+ throw new Error("not SQL");
276
+ },
277
+ }));
278
+ }
279
+ try {
280
+ // The plaintext (or the plain dump) is dropped as it comes.
281
+ await deadline.bound(stream.pipeTo(new WritableStream()));
282
+ if (writer === undefined || digest === undefined)
283
+ return { ok: true, sha256: null };
284
+ await deadline.bound(writer.close());
285
+ const bytes = new Uint8Array(await deadline.bound(digest.digest));
286
+ return { ok: true, sha256: Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("") };
287
+ }
288
+ catch (error) {
289
+ if (error instanceof DeadlinePassed)
290
+ throw error;
291
+ writer?.abort().catch(() => undefined);
292
+ return { ok: false };
293
+ }
294
+ }
295
+ /**
296
+ * What `key` holds for a copy of `databaseId` by `run`. The rule: an object is this copy's only
297
+ * when its `run` metadata is this call's run. The run is fixed before the first export starts
298
+ * and stays the same across step retries and restarted exports, while the export's bookmark
299
+ * does not (a restarted export has its own), so the bookmark is never what decides: an object
300
+ * this run finished with an earlier export is its backup, and is reused; an object of another
301
+ * run (another instance or call that got the same key, even with the same bookmark) is
302
+ * `other`. The sidecar must carry the same database id, run and export bookmark as the dump,
303
+ * and the identity of **the very object at the key** (`dump-object`): a later write of the key
304
+ * (an earlier export's `put` landing late, with the same run and possibly the same bookmark)
305
+ * is not the object the sidecar was written for. Then the stored dump is read back and hashed:
306
+ * the digest returned on reuse is the stored object's, compared with the sidecar's, not the
307
+ * sidecar's word for it. Where no incremental digest exists (Node), there is no sidecar: reuse
308
+ * rests on the metadata and the size, plus, with encryption, the read-back below.
309
+ *
310
+ * The object's encryption must be this call's: none when `encryption` is `null`, else the same
311
+ * scheme and the `current` key id. A copy of this run made in plain, or with another key, is
312
+ * `unfinished` and written again under the current settings (a deploy that turned encryption on
313
+ * or rotated the key while the run was going): never reused, never `exists`. The sidecar carries
314
+ * the same two fields. The metadata is not taken on its word: the read-back (`readBack`, the
315
+ * same pass as the digest) decrypts the whole object with the current key and checks its
316
+ * authenticated header names this database and this key; on Node too, with encryption on. A
317
+ * plain object must start like SQL.
318
+ */
319
+ async function inspectExisting(bucket, key, databaseId, run, encryption, digestAvailable, deadline) {
320
+ const existing = await deadline.bound(bucket.head(key));
321
+ if (existing === null)
322
+ return { kind: "none" };
323
+ const meta = existing.customMetadata ?? {};
324
+ if (meta[METADATA.marker] !== "1" ||
325
+ meta[METADATA.databaseId] !== databaseId ||
326
+ meta[METADATA.run] !== run) {
327
+ return { kind: "other" };
328
+ }
329
+ if (meta[METADATA.encryption] !== (encryption === null ? undefined : encryption.scheme) ||
330
+ meta[METADATA.keyId] !== (encryption === null ? undefined : encryption.current)) {
331
+ return { kind: "unfinished" };
332
+ }
333
+ const exported = meta[METADATA.bookmark];
334
+ if (!isValidBookmark(exported))
335
+ return { kind: "unfinished" };
336
+ const stated = meta[METADATA.bytes];
337
+ if (stated !== undefined && Number(stated) !== existing.size)
338
+ return { kind: "unfinished" };
339
+ const backup = { databaseId, key };
340
+ const Digest = digestAvailable ? digestStreamClass() : undefined;
341
+ if (Digest === undefined) {
342
+ if (encryption === null) {
343
+ return { kind: "finished", size: existing.size, bookmark: exported, sha256: null };
344
+ }
345
+ // No sidecar here, but the object must still decrypt as this backup.
346
+ const stored = await deadline.bound(bucket.get(key));
347
+ if (stored === null)
348
+ return { kind: "unfinished" };
349
+ if (stored.size !== existing.size) {
350
+ stored.body.cancel().catch(() => undefined);
351
+ return { kind: "unfinished" };
352
+ }
353
+ const read = await readBack(stored, deadline, undefined, encryption, backup);
354
+ if (!read.ok)
355
+ return { kind: "unfinished" };
356
+ return { kind: "finished", size: existing.size, bookmark: exported, sha256: null };
357
+ }
358
+ const identity = objectIdentity(existing);
359
+ if (identity === null)
360
+ return { kind: "unfinished" };
361
+ const sidecar = await deadline.bound(bucket.get(digestKey(key)));
362
+ if (sidecar === null)
363
+ return { kind: "unfinished" };
364
+ const sideMeta = sidecar.customMetadata ?? {};
365
+ // Everything but the content first: an object of any size can sit at the sidecar's key.
366
+ if (sideMeta[METADATA.marker] !== "1" ||
367
+ sideMeta[METADATA.databaseId] !== databaseId ||
368
+ sideMeta[METADATA.run] !== run ||
369
+ sideMeta[METADATA.bookmark] !== exported ||
370
+ sideMeta[METADATA.dumpObject] !== identity ||
371
+ sideMeta[METADATA.encryption] !== meta[METADATA.encryption] ||
372
+ sideMeta[METADATA.keyId] !== meta[METADATA.keyId] ||
373
+ sidecar.size < SIDECAR_MIN_SIZE ||
374
+ sidecar.size > SIDECAR_MAX_SIZE) {
375
+ // Not awaited: the body is not needed, and cancelling must not wait on R2.
376
+ sidecar.body.cancel().catch(() => undefined);
377
+ return { kind: "unfinished" };
378
+ }
379
+ const text = (await deadline.bound(sidecar.text())).trim();
380
+ if (!SHA256_HEX.test(text))
381
+ return { kind: "unfinished" };
382
+ // The digest kept outside the bucket (the output, the log line) must be the stored dump's:
383
+ // read it back. The object read must still be the one the sidecar names.
384
+ const stored = await deadline.bound(bucket.get(key));
385
+ if (stored === null)
386
+ return { kind: "unfinished" };
387
+ if (objectIdentity(stored) !== identity || stored.size !== existing.size) {
388
+ stored.body.cancel().catch(() => undefined);
389
+ return { kind: "unfinished" };
390
+ }
391
+ const read = await readBack(stored, deadline, Digest, encryption, backup);
392
+ if (!read.ok || read.sha256 !== text)
393
+ return { kind: "unfinished" };
394
+ return { kind: "finished", size: existing.size, bookmark: exported, sha256: read.sha256 };
395
+ }
396
+ /**
397
+ * Internal: with encryption on, the database id and key go into the encrypted header, so they
398
+ * must fit its patterns. `d1Export` only builds UUID ids; a hand-built exporter is refused here,
399
+ * before anything is read or downloaded, rather than failing late. A fixed message, no value.
400
+ */
401
+ export function assertEncryptable(encryption, databaseId, key, who) {
402
+ if (encryption !== null && !isIdentity({ databaseId, key })) {
403
+ throw new TypeError(`${who}: with encryption, the exporter's databaseId must be 1 to 64 letters, digits, '.', '_', ':' or '-' (a D1 id).`);
404
+ }
405
+ }
406
+ function isReady(value) {
407
+ if (typeof value !== "object" || value === null)
408
+ return false;
409
+ const ready = value;
410
+ return (ready.status === "ready" &&
411
+ isValidBookmark(ready.bookmark) &&
412
+ typeof ready.download === "function");
413
+ }
414
+ function isExporter(value) {
415
+ return (typeof value === "object" &&
416
+ value !== null &&
417
+ typeof value.poll === "function" &&
418
+ typeof value.databaseId === "string" &&
419
+ (value.format === "d1" || value.format === "sqlite3"));
420
+ }
421
+ /**
422
+ * Streams the dump of a `ready` export into `bucket` at `key`. Results, not exceptions, for every
423
+ * expected outcome; a `TypeError` for invalid options. It never polls: `ready` is the one answer
424
+ * that carries the signed URL, and a failed copy needs a new export (`start`), since polling the
425
+ * same bookmark again answers `not_exporting`. `retryable` says whether that new attempt may
426
+ * succeed.
427
+ *
428
+ * A key that already holds an object is reused only when that object is this very backup: the
429
+ * marker, the same database id, **the same `run`** (see `inspectExisting`), the same encryption
430
+ * (none, or the scheme and the `current` key id), the stored size equal to the recorded one, and
431
+ * (where digests are computed) its digest sidecar, naming this very object and equal to the
432
+ * digest of the object read back. Then nothing is downloaded. An object of this run that is not
433
+ * proven finished, or not encrypted as asked, is written again; any other object is `exists`. A
434
+ * failure leaves no object and no open multipart upload (past the deadline, see the module's
435
+ * header). The copy does not look at other keys: two databases sharing a prefix both get their
436
+ * backups written, and `pruneBackups` refuses to prune it.
437
+ */
438
+ export async function copyExport(options) {
439
+ if (typeof options !== "object" || options === null) {
440
+ throw new TypeError("copyExport: options { exporter, ready, bucket, key, run } are required.");
441
+ }
442
+ const { exporter, ready, bucket, key, run } = options;
443
+ const partSize = options.partSize ?? DEFAULT_PART_SIZE;
444
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
445
+ const singlePutLimit = options.singlePutLimit ?? DEFAULT_SINGLE_PUT_LIMIT;
446
+ if (!isExporter(exporter)) {
447
+ throw new TypeError("copyExport: exporter must be the client returned by d1Export.");
448
+ }
449
+ if (!isReady(ready)) {
450
+ throw new TypeError("copyExport: ready must be the answer of the start or poll that reported the export complete.");
451
+ }
452
+ if (!isR2Bucket(bucket))
453
+ throw new TypeError("copyExport: bucket must be an R2 binding.");
454
+ const at = parseKeyAnyPrefix(key);
455
+ if (at === null) {
456
+ throw new TypeError("copyExport: key must be built with backupKey(prefix, at).");
457
+ }
458
+ if (!isValidRun(run)) {
459
+ throw new TypeError("copyExport: run must be 1 to 128 letters, digits, '.', '_', ':' or '-' (a UUID, say).");
460
+ }
461
+ if (!wholeIn(partSize, MIN_PART_SIZE, MAX_PART_SIZE)) {
462
+ throw new TypeError("copyExport: partSize must be a whole number from 5 MiB to 32 MiB.");
463
+ }
464
+ if (!wholeIn(timeoutMs, 1000, MAX_TIMEOUT_MS)) {
465
+ throw new TypeError("copyExport: timeoutMs must be 1000 ms to 6 hours.");
466
+ }
467
+ if (!wholeIn(singlePutLimit, 1, DEFAULT_SINGLE_PUT_LIMIT)) {
468
+ throw new TypeError("copyExport: singlePutLimit must be 1 byte to 4 GiB.");
469
+ }
470
+ const encryption = encryptionOption(options, "copyExport");
471
+ assertEncryptable(encryption, exporter.databaseId, key, "copyExport");
472
+ const deadline = createDeadline(timeoutMs);
473
+ try {
474
+ return await copyWithin(deadline, {
475
+ exporter,
476
+ ready,
477
+ bucket,
478
+ key,
479
+ run,
480
+ partSize,
481
+ singlePutLimit,
482
+ encryption,
483
+ createdAt: at.toISOString(),
484
+ });
485
+ }
486
+ catch (error) {
487
+ if (error instanceof DeadlinePassed)
488
+ return fail("timeout", true);
489
+ throw error;
490
+ }
491
+ }
492
+ /**
493
+ * Internal (the Workflow's start steps; not exported from the package): whether `key` already
494
+ * holds the finished backup of `run`, by the same rule as `copyExport`'s reuse (encryption
495
+ * included). A finished one is returned as a reused result; another run's object is `exists`;
496
+ * nothing, or an object of this run that is not proven finished, is `null` (an export is needed).
497
+ * Asked before starting an export, so a retry whose run already finished its copy starts none,
498
+ * and by a poll told no export is running, so a finished copy whose step result was lost is
499
+ * found. On Workers a finished object is read back whole (its digest), hence the copy's default
500
+ * deadline.
501
+ */
502
+ export async function findCopy(options) {
503
+ const { exporter, bucket, key, run } = options;
504
+ const at = parseKeyAnyPrefix(key);
505
+ if (!isExporter(exporter) || !isR2Bucket(bucket) || at === null || !isValidRun(run)) {
506
+ throw new TypeError("findCopy: invalid options.");
507
+ }
508
+ const encryption = encryptionOption(options, "findCopy");
509
+ assertEncryptable(encryption, exporter.databaseId, key, "findCopy");
510
+ const deadline = createDeadline(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
511
+ try {
512
+ const existing = await inspectExisting(bucket, key, exporter.databaseId, run, encryption, digestStreamClass() !== undefined, deadline);
513
+ if (existing.kind === "other")
514
+ return fail("exists", false);
515
+ if (existing.kind !== "finished")
516
+ return null;
517
+ return reusedResult(key, exporter.databaseId, at.toISOString(), existing, encryption);
518
+ }
519
+ catch (error) {
520
+ if (error instanceof DeadlinePassed)
521
+ return fail("timeout", true);
522
+ throw error;
523
+ }
524
+ }
525
+ /** How `encryption` encrypts, for results: scheme and key id, never a key. */
526
+ function encryptionInfo(encryption) {
527
+ return encryption === null
528
+ ? {}
529
+ : { encryption: { scheme: ENCRYPTION_SCHEME, keyId: encryption.current } };
530
+ }
531
+ function reusedResult(key, databaseId, createdAt, existing, encryption) {
532
+ return {
533
+ ok: true,
534
+ key,
535
+ size: existing.size,
536
+ bookmark: existing.bookmark,
537
+ databaseId,
538
+ createdAt,
539
+ sha256: existing.sha256,
540
+ reused: true,
541
+ ...encryptionInfo(encryption),
542
+ };
543
+ }
544
+ /** The copy itself; every await on R2 or the network races `deadline`. */
545
+ async function copyWithin(deadline, plan) {
546
+ const { exporter, ready, bucket, key, run, partSize, singlePutLimit, encryption, createdAt } = plan;
547
+ const { signal } = deadline;
548
+ const databaseId = exporter.databaseId;
549
+ const digestAvailable = digestStreamClass() !== undefined;
550
+ const existing = await inspectExisting(bucket, key, databaseId, run, encryption, digestAvailable, deadline);
551
+ if (existing.kind === "finished") {
552
+ return reusedResult(key, databaseId, createdAt, existing, encryption);
553
+ }
554
+ if (existing.kind === "other")
555
+ return fail("exists", false);
556
+ // The one download this answer allows: no poll before or after it.
557
+ const download = await deadline.bound(ready.download({ signal }));
558
+ if (!download.ok)
559
+ return fail(download.reason, download.retryable);
560
+ const metadata = {
561
+ [METADATA.marker]: "1",
562
+ [METADATA.bookmark]: ready.bookmark,
563
+ [METADATA.run]: run,
564
+ [METADATA.databaseId]: databaseId,
565
+ [METADATA.createdAt]: createdAt,
566
+ [METADATA.format]: exporter.format,
567
+ ...(encryption === null
568
+ ? {}
569
+ : { [METADATA.encryption]: encryption.scheme, [METADATA.keyId]: encryption.current }),
570
+ };
571
+ const httpMetadata = {
572
+ contentType: encryption === null ? "application/sql; charset=utf-8" : "application/octet-stream",
573
+ };
574
+ const { length } = download;
575
+ // Every read of the body is bounded by the deadline: on abort the stream errors.
576
+ const body = bounded(download.body, signal);
577
+ const timedOut = (result) => !result.ok && signal.aborted && result.reason !== "timeout"
578
+ ? fail("timeout", true)
579
+ : result;
580
+ if (length === 0) {
581
+ await body.cancel().catch(() => undefined);
582
+ return fail("empty", true);
583
+ }
584
+ // What the encrypted header binds the backup to: this database and this very key.
585
+ const backup = { databaseId, key };
586
+ // What R2 will hold: the encrypted length is a function of the plaintext length.
587
+ const stored = length === null || encryption === null
588
+ ? length
589
+ : encryptedSize(length, encryption.current, backup);
590
+ if (stored === null && length !== null) {
591
+ await body.cancel().catch(() => undefined);
592
+ return fail("too_large", false);
593
+ }
594
+ if (stored !== null && stored > partSize * MAX_PARTS) {
595
+ await body.cancel().catch(() => undefined);
596
+ return fail("too_large", false);
597
+ }
598
+ const digest = createDigest();
599
+ const source = storedBytes(body, length, encryption, backup, digest);
600
+ const fixed = stored === null || stored > singlePutLimit ? undefined : fixedLengthStream(stored);
601
+ let written;
602
+ try {
603
+ written =
604
+ stored !== null && fixed !== undefined
605
+ ? await putKnownLength(bucket, key, source, stored, fixed, deadline, {
606
+ customMetadata: { ...metadata, [METADATA.bytes]: String(stored) },
607
+ httpMetadata,
608
+ })
609
+ : await putInParts(bucket, key, source, partSize, stored, deadline, {
610
+ metadata,
611
+ httpMetadata,
612
+ });
613
+ }
614
+ catch (error) {
615
+ await digest.abort();
616
+ throw error;
617
+ }
618
+ const result = timedOut(written);
619
+ if (!result.ok) {
620
+ await digest.abort();
621
+ return result;
622
+ }
623
+ let sha256;
624
+ try {
625
+ sha256 = await deadline.bound(digest.finish());
626
+ }
627
+ catch (error) {
628
+ if (error instanceof DeadlinePassed)
629
+ throw error;
630
+ await discard(bucket, key, deadline);
631
+ return fail("write_failed", true);
632
+ }
633
+ if (sha256 !== null) {
634
+ // The sidecar comes last: its presence says the dump is complete and checked. It names the
635
+ // exact object it vouches for: a later write of the key (an earlier export's `put` landing
636
+ // late) is another object, which reuse refuses. Without an identity (a binding that returns
637
+ // neither `version` nor `etag`) it names none, and reuse never accepts it: a retry rewrites.
638
+ const sidecarMetadata = result.identity === null ? metadata : { ...metadata, [METADATA.dumpObject]: result.identity };
639
+ let put;
640
+ try {
641
+ put = await deadline.bound(bucket.put(digestKey(key), sha256, {
642
+ customMetadata: sidecarMetadata,
643
+ httpMetadata: { contentType: "text/plain; charset=utf-8" },
644
+ }));
645
+ }
646
+ catch (error) {
647
+ // Past the deadline the dump stays, without its sidecar: a retry writes it again.
648
+ if (error instanceof DeadlinePassed)
649
+ throw error;
650
+ put = null;
651
+ }
652
+ if (put === null) {
653
+ await discard(bucket, key, deadline);
654
+ return fail("write_failed", true);
655
+ }
656
+ }
657
+ return {
658
+ ok: true,
659
+ key,
660
+ size: result.size,
661
+ bookmark: ready.bookmark,
662
+ databaseId,
663
+ createdAt,
664
+ sha256,
665
+ reused: false,
666
+ ...encryptionInfo(encryption),
667
+ };
668
+ }
669
+ /**
670
+ * The download as R2 will store it. The plaintext is counted against the stated length and its
671
+ * start checked as SQL (an empty dump, an error page); then, with `encryption`, it is encrypted
672
+ * (re-chunked to 64 KiB, see `encryption.ts`); then what will be stored goes through the digest.
673
+ * Each stage is a `TransformStream`, so backpressure reaches the download: nothing is held
674
+ * beyond a chunk per stage.
675
+ */
676
+ function storedBytes(body, length, encryption, backup, digest) {
677
+ const sniffer = createSqlSniffer();
678
+ let count = 0;
679
+ let abort;
680
+ const stop = (reason) => {
681
+ abort = new CopyAbort(reason, true);
682
+ throw abort;
683
+ };
684
+ const check = new TransformStream({
685
+ transform(chunk, controller) {
686
+ if (!(chunk instanceof Uint8Array))
687
+ stop("read_failed");
688
+ count += chunk.byteLength;
689
+ if (length !== null && count > length)
690
+ stop("size_mismatch");
691
+ if (sniffer.feed(chunk) === "bad")
692
+ stop("not_sql");
693
+ controller.enqueue(chunk);
694
+ },
695
+ flush() {
696
+ if (sniffer.end() !== "ok")
697
+ stop(count === 0 ? "empty" : "not_sql");
698
+ if (length !== null && count !== length)
699
+ stop("size_mismatch");
700
+ },
701
+ });
702
+ let readable = body.pipeThrough(check);
703
+ if (encryption !== null) {
704
+ readable = readable.pipeThrough(createEncryptStream(encryption, backup));
705
+ }
706
+ if (digest.available) {
707
+ readable = readable.pipeThrough(new TransformStream({
708
+ async transform(chunk, controller) {
709
+ // The digest gets its own copy: the chunk goes on to R2.
710
+ await digest.write(chunk.slice());
711
+ controller.enqueue(chunk);
712
+ },
713
+ }));
714
+ }
715
+ return {
716
+ readable,
717
+ failure(error) {
718
+ if (abort !== undefined)
719
+ return abort;
720
+ if (error instanceof EncryptionTooLarge)
721
+ return new CopyAbort("too_large", false);
722
+ return undefined;
723
+ },
724
+ };
725
+ }
726
+ async function putKnownLength(bucket, key, source, length, fixed, deadline, options) {
727
+ const piping = source.readable.pipeTo(fixed.writable);
728
+ const putting = bucket.put(key, fixed.readable, options);
729
+ // A stalled `put` stops consuming the stream, so neither would ever settle: the race ends it.
730
+ // A put still in flight then may land later, holding the whole checked dump (no sidecar).
731
+ const [piped, put] = await deadline.bound(Promise.allSettled([piping, putting]));
732
+ if (piped.status === "rejected" || put.status === "rejected" || put.value === null) {
733
+ // A put that resolved although the stream failed would be a partial object: never kept.
734
+ if (put.status === "fulfilled" && put.value !== null)
735
+ await discard(bucket, key, deadline);
736
+ const abort = source.failure(piped.status === "rejected" ? piped.reason : undefined);
737
+ if (abort !== undefined)
738
+ return fail(abort.reason, abort.retryable);
739
+ return fail(piped.status === "rejected" ? "read_failed" : "write_failed", true);
740
+ }
741
+ if (put.value.size !== length) {
742
+ await discard(bucket, key, deadline);
743
+ return fail("size_mismatch", true);
744
+ }
745
+ return { ok: true, size: length, identity: objectIdentity(put.value) };
746
+ }
747
+ async function putInParts(bucket, key, source, partSize, length, deadline, { metadata, httpMetadata }) {
748
+ const reader = source.readable.getReader();
749
+ let buffer = new Uint8Array(partSize);
750
+ let filled = 0;
751
+ let total = 0;
752
+ let ended = false;
753
+ let upload;
754
+ const parts = [];
755
+ // A known length is recorded from the start, even for a multipart upload.
756
+ const uploadMetadata = length === null ? metadata : { ...metadata, [METADATA.bytes]: String(length) };
757
+ /** Runs an R2 call against the deadline: past it `timeout`, any other failure `write_failed`. */
758
+ async function write(call) {
759
+ try {
760
+ return await deadline.bound(call());
761
+ }
762
+ catch (error) {
763
+ throw new CopyAbort(error instanceof DeadlinePassed ? "timeout" : "write_failed", true);
764
+ }
765
+ }
766
+ /**
767
+ * Reads until the buffer is full or the stream ends. The checks (SQL, length, empty) run in
768
+ * the stream (`storedBytes`): a failed one errors the read, and its reason is kept.
769
+ */
770
+ async function fill() {
771
+ while (filled < partSize && !ended) {
772
+ let next;
773
+ try {
774
+ next = await reader.read();
775
+ }
776
+ catch (error) {
777
+ throw source.failure(error) ?? new CopyAbort("read_failed", true);
778
+ }
779
+ if (next.done) {
780
+ ended = true;
781
+ break;
782
+ }
783
+ const chunk = next.value;
784
+ if (!(chunk instanceof Uint8Array))
785
+ throw new CopyAbort("read_failed", true);
786
+ total += chunk.byteLength;
787
+ if (length !== null && total > length)
788
+ throw new CopyAbort("size_mismatch", true);
789
+ if (total > partSize * MAX_PARTS)
790
+ throw new CopyAbort("too_large", false);
791
+ let offset = 0;
792
+ while (offset < chunk.byteLength) {
793
+ if (filled === partSize) {
794
+ // The chunk spans parts: send the full buffer before copying the rest.
795
+ await sendPart();
796
+ }
797
+ const take = Math.min(partSize - filled, chunk.byteLength - offset);
798
+ buffer.set(chunk.subarray(offset, offset + take), filled);
799
+ filled += take;
800
+ offset += take;
801
+ }
802
+ }
803
+ }
804
+ async function sendPart() {
805
+ upload ??= await write(() => bucket.createMultipartUpload(key, { customMetadata: uploadMetadata, httpMetadata }));
806
+ const current = upload;
807
+ // A full buffer is handed over as it is (a new one replaces it); the last part is copied.
808
+ const part = filled === partSize ? buffer : buffer.slice(0, filled);
809
+ parts.push(await write(() => current.uploadPart(parts.length + 1, part)));
810
+ filled = 0;
811
+ buffer = new Uint8Array(partSize);
812
+ }
813
+ try {
814
+ await fill();
815
+ if (ended) {
816
+ if (length !== null && total !== length)
817
+ throw new CopyAbort("size_mismatch", true);
818
+ if (upload === undefined) {
819
+ // It fits in one part: one put of known size.
820
+ const object = await write(() => bucket.put(key, buffer.subarray(0, filled), {
821
+ customMetadata: { ...metadata, [METADATA.bytes]: String(total) },
822
+ httpMetadata,
823
+ }));
824
+ if (object === null)
825
+ throw new CopyAbort("write_failed", true);
826
+ if (object.size !== total) {
827
+ await discard(bucket, key, deadline);
828
+ throw new CopyAbort("size_mismatch", true);
829
+ }
830
+ return { ok: true, size: total, identity: objectIdentity(object) };
831
+ }
832
+ }
833
+ while (!ended || filled > 0) {
834
+ if (filled === partSize || (ended && filled > 0))
835
+ await sendPart();
836
+ if (!ended)
837
+ await fill();
838
+ }
839
+ if (length !== null && total !== length)
840
+ throw new CopyAbort("size_mismatch", true);
841
+ const current = upload;
842
+ if (current === undefined)
843
+ throw new CopyAbort("write_failed", true);
844
+ const object = await write(() => current.complete(parts));
845
+ upload = undefined; // completed: nothing to abort any more
846
+ if (object.size !== total) {
847
+ await discard(bucket, key, deadline);
848
+ throw new CopyAbort("size_mismatch", true);
849
+ }
850
+ return { ok: true, size: total, identity: objectIdentity(object) };
851
+ }
852
+ catch (error) {
853
+ // Not awaited: the source may be stalled (the bounded body errors on its own).
854
+ reader.cancel().catch(() => undefined);
855
+ // Bounded too: past the deadline, the abort gets a few seconds and no more.
856
+ if (upload !== undefined)
857
+ await settleWithin(upload.abort(), CLEANUP_GRACE_MS);
858
+ if (error instanceof CopyAbort)
859
+ return fail(error.reason, error.retryable);
860
+ return fail("write_failed", true);
861
+ }
862
+ }
863
+ //# sourceMappingURL=copy.js.map