@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
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Retention: which backups to keep (pure, `planRetention`) and the I/O around it (`listBackups`,
3
+ * `pruneBackups`). Periods are calendar days, ISO weeks (Monday to Sunday, ISO week-year) and
4
+ * calendar months, all in UTC, read from the key. The counts are of periods **that have a
5
+ * backup**, newest first, as in restic and Borg: `daily: 7` keeps the newest backup of each of the
6
+ * 7 most recent days with a backup, whatever today is. So backups that stopped a month ago are
7
+ * not pruned away by the passing of time.
8
+ */
9
+ import { isValidDatabaseId } from "./export.js";
10
+ import { assertValidPrefix, parseBackupKey } from "./keys.js";
11
+ import { DIGEST_SUFFIX, digestKey, METADATA } from "./metadata.js";
12
+ const MAX_COUNT = 10_000;
13
+ const RULES = ["daily", "weekly", "monthly"];
14
+ /** Throws a `TypeError` unless `keep` has whole counts from 0 to 10 000, at least one above 0. */
15
+ export function assertValidRetention(keep, where = "backups") {
16
+ if (typeof keep !== "object" || keep === null || Array.isArray(keep)) {
17
+ throw new TypeError(`${where}: keep must be an object { daily?, weekly?, monthly? }.`);
18
+ }
19
+ const record = keep;
20
+ for (const name of Object.keys(record)) {
21
+ if (!RULES.includes(name)) {
22
+ throw new TypeError(`${where}: keep accepts daily, weekly and monthly only.`);
23
+ }
24
+ }
25
+ let any = false;
26
+ for (const rule of RULES) {
27
+ const value = record[rule];
28
+ if (value === undefined)
29
+ continue;
30
+ if (typeof value !== "number" ||
31
+ !Number.isSafeInteger(value) ||
32
+ value < 0 ||
33
+ value > MAX_COUNT) {
34
+ throw new TypeError(`${where}: keep.${rule} must be a whole number from 0 to ${MAX_COUNT}.`);
35
+ }
36
+ if (value > 0)
37
+ any = true;
38
+ }
39
+ if (!any) {
40
+ throw new TypeError(`${where}: keep must keep something (e.g. { daily: 7 }); refusing a policy that keeps nothing.`);
41
+ }
42
+ }
43
+ const pad = (n, width = 2) => String(n).padStart(width, "0");
44
+ /** `2026-11-20` (UTC). */
45
+ export function dayOf(at) {
46
+ return at.toISOString().slice(0, 10);
47
+ }
48
+ /** `2026-11` (UTC). */
49
+ export function monthOf(at) {
50
+ return at.toISOString().slice(0, 7);
51
+ }
52
+ /**
53
+ * The ISO 8601 week of `at` in UTC, `2026-W47`: weeks start on Monday, and week 1 is the one with
54
+ * the year's first Thursday, so `2027-01-01` (a Friday) is in `2026-W53`.
55
+ */
56
+ export function isoWeekOf(at) {
57
+ const day = new Date(Date.UTC(at.getUTCFullYear(), at.getUTCMonth(), at.getUTCDate()));
58
+ const weekday = day.getUTCDay() === 0 ? 7 : day.getUTCDay(); // Monday 1 … Sunday 7
59
+ // The Thursday of this week decides the year.
60
+ day.setUTCDate(day.getUTCDate() + 4 - weekday);
61
+ const year = day.getUTCFullYear();
62
+ const firstDay = Date.UTC(year, 0, 1);
63
+ const week = Math.floor((day.getTime() - firstDay) / 86_400_000 / 7) + 1;
64
+ return `${pad(year, 4)}-W${pad(week)}`;
65
+ }
66
+ const PERIOD = {
67
+ daily: dayOf,
68
+ weekly: isoWeekOf,
69
+ monthly: monthOf,
70
+ };
71
+ /**
72
+ * Which entries to keep and which to remove. Pure: no clock, no I/O. Newest first by `at` (then
73
+ * key); for each rule, walks the entries and keeps the first (newest) of each new period until
74
+ * the count is reached. The newest entry is always kept, whatever the policy. Throws a
75
+ * `TypeError` for an invalid policy.
76
+ */
77
+ export function planRetention(entries, keep) {
78
+ assertValidRetention(keep, "planRetention");
79
+ const sorted = [...entries].sort((a, b) => b.at.getTime() - a.at.getTime() || (a.key < b.key ? 1 : a.key > b.key ? -1 : 0));
80
+ const kept = new Set();
81
+ const newest = sorted[0];
82
+ if (newest !== undefined)
83
+ kept.add(newest);
84
+ for (const rule of RULES) {
85
+ const count = keep[rule] ?? 0;
86
+ if (count === 0)
87
+ continue;
88
+ const periodOf = PERIOD[rule];
89
+ let last;
90
+ let taken = 0;
91
+ for (const entry of sorted) {
92
+ if (taken >= count)
93
+ break;
94
+ const period = periodOf(entry.at);
95
+ if (period === last)
96
+ continue;
97
+ last = period;
98
+ taken += 1;
99
+ kept.add(entry);
100
+ }
101
+ }
102
+ return {
103
+ keep: sorted.filter((entry) => kept.has(entry)),
104
+ remove: sorted.filter((entry) => !kept.has(entry)),
105
+ };
106
+ }
107
+ /** The `key-id`s of `backups`, sorted and unique. */
108
+ function keyIdsOf(backups) {
109
+ const ids = new Set();
110
+ for (const backup of backups) {
111
+ const id = backup.metadata[METADATA.keyId];
112
+ if (id !== undefined)
113
+ ids.add(id);
114
+ }
115
+ return [...ids].sort();
116
+ }
117
+ const PAGE = 1000;
118
+ /** Listing stops (with an error) past this many objects: a partial view is never acted on. */
119
+ const MAX_LISTED = 100_000;
120
+ /**
121
+ * Every backup under `prefix`: objects whose key matches the package's pattern exactly **and**
122
+ * that carry its metadata marker, with their digest sidecars (`<key>.sha256`, also marked),
123
+ * which are never backups themselves. Lists every page; throws when the prefix holds more than
124
+ * 100 000 objects rather than act on a partial list.
125
+ */
126
+ export async function listBackups(bucket, prefix) {
127
+ assertValidPrefix(prefix, "listBackups");
128
+ if (typeof bucket !== "object" || bucket === null || typeof bucket.list !== "function") {
129
+ throw new TypeError("listBackups: bucket must be an R2 binding.");
130
+ }
131
+ const dumps = [];
132
+ const digests = new Map();
133
+ let ignored = 0;
134
+ let listed = 0;
135
+ let cursor;
136
+ for (;;) {
137
+ const page = await bucket.list({
138
+ prefix: `${prefix}/`,
139
+ limit: PAGE,
140
+ include: ["customMetadata"],
141
+ ...(cursor === undefined ? {} : { cursor }),
142
+ });
143
+ for (const object of page.objects) {
144
+ listed += 1;
145
+ const metadata = { ...(object.customMetadata ?? {}) };
146
+ if (metadata[METADATA.marker] !== "1") {
147
+ ignored += 1;
148
+ continue;
149
+ }
150
+ const at = parseBackupKey(prefix, object.key);
151
+ if (at !== null) {
152
+ dumps.push({ key: object.key, at, size: object.size, metadata });
153
+ continue;
154
+ }
155
+ const dumpAt = object.key.endsWith(DIGEST_SUFFIX)
156
+ ? parseBackupKey(prefix, object.key.slice(0, -DIGEST_SUFFIX.length))
157
+ : null;
158
+ if (dumpAt !== null)
159
+ digests.set(object.key, { at: dumpAt, metadata });
160
+ else
161
+ ignored += 1;
162
+ }
163
+ if (listed > MAX_LISTED) {
164
+ throw new Error(`listBackups: more than ${MAX_LISTED} objects under the prefix; refusing a partial list.`);
165
+ }
166
+ if (!page.truncated)
167
+ break;
168
+ if (typeof page.cursor !== "string" || page.cursor === "" || page.cursor === cursor) {
169
+ throw new Error("listBackups: the listing is truncated without a new cursor.");
170
+ }
171
+ cursor = page.cursor;
172
+ }
173
+ const backups = dumps.map((dump) => {
174
+ const sidecar = digestKey(dump.key);
175
+ const found = digests.get(sidecar);
176
+ digests.delete(sidecar);
177
+ return found === undefined
178
+ ? { ...dump, digestKey: null, digestMetadata: null }
179
+ : { ...dump, digestKey: sidecar, digestMetadata: found.metadata };
180
+ });
181
+ backups.sort((a, b) => b.at.getTime() - a.at.getTime() || (a.key < b.key ? 1 : -1));
182
+ const orphanDigests = [...digests]
183
+ .map(([key, { at, metadata }]) => ({ key, at, metadata }))
184
+ .sort((a, b) => (a.key < b.key ? -1 : 1));
185
+ return { backups, orphanDigests, ignored, keyIds: keyIdsOf(backups) };
186
+ }
187
+ /**
188
+ * `pruneBackups` refused: nothing was deleted. The message names the reason and how many
189
+ * objects; never a key, an id or a value.
190
+ */
191
+ export class PruneRefusedError extends Error {
192
+ reason;
193
+ count;
194
+ constructor(reason, count) {
195
+ super(reason === "other_database"
196
+ ? `pruneBackups: the prefix holds ${count} object(s) of another database; use one prefix per database. Nothing was deleted.`
197
+ : `pruneBackups: ${count} backup(s) are dated more than a day in the future; they would push real backups out of retention. Nothing was deleted.`);
198
+ this.reason = reason;
199
+ this.count = count;
200
+ this.name = "PruneRefusedError";
201
+ }
202
+ }
203
+ /** R2 deletes at most 1000 keys per call. */
204
+ const DELETE_BATCH = 1000;
205
+ const DAY_MS = 86_400_000;
206
+ /**
207
+ * Deletes the backups of `databaseId` under `prefix` that `keep` does not keep (see
208
+ * `planRetention`), with their digest sidecars, and orphan sidecars dated more than a day before
209
+ * `now()`. Never deletes the newest backup, objects whose key does not match the package's
210
+ * pattern exactly, or objects without its marker. Refuses (throws a `PruneRefusedError`,
211
+ * deleting nothing) while the prefix holds a backup or sidecar of another database (or one with
212
+ * no database id) or a backup dated more than a day after `now()`; throws a `TypeError` for invalid
213
+ * options and an `Error` for a plan that would delete every backup. Deletes in batches of 1000
214
+ * keys; a failed batch throws (keys of earlier batches stay deleted; a rerun continues).
215
+ */
216
+ export async function pruneBackups(bucket, options) {
217
+ if (typeof options !== "object" || options === null) {
218
+ throw new TypeError("pruneBackups: options { prefix, databaseId, keep } are required.");
219
+ }
220
+ const { prefix, keep, databaseId } = options;
221
+ const dryRun = options.dryRun ?? false;
222
+ const now = options.now ?? (() => new Date());
223
+ assertValidPrefix(prefix, "pruneBackups");
224
+ if (!isValidDatabaseId(databaseId)) {
225
+ throw new TypeError("pruneBackups: databaseId must be the D1 database id (a lowercase UUID, exporter.databaseId).");
226
+ }
227
+ assertValidRetention(keep, "pruneBackups");
228
+ if (typeof dryRun !== "boolean")
229
+ throw new TypeError("pruneBackups: dryRun must be a boolean.");
230
+ if (typeof now !== "function")
231
+ throw new TypeError("pruneBackups: now must be a function.");
232
+ if (typeof bucket !== "object" || bucket === null || typeof bucket.delete !== "function") {
233
+ throw new TypeError("pruneBackups: bucket must be an R2 binding.");
234
+ }
235
+ const { backups, orphanDigests, ignored } = await listBackups(bucket, prefix);
236
+ const isOther = (metadata) => metadata !== null && metadata[METADATA.databaseId] !== databaseId;
237
+ const others = backups.filter((backup) => isOther(backup.metadata)).length +
238
+ backups.filter((backup) => isOther(backup.digestMetadata)).length +
239
+ orphanDigests.filter((digest) => isOther(digest.metadata)).length;
240
+ if (others > 0)
241
+ throw new PruneRefusedError("other_database", others);
242
+ const current = now();
243
+ if (!(current instanceof Date) || !Number.isFinite(current.getTime())) {
244
+ throw new TypeError("pruneBackups: now must return a valid Date.");
245
+ }
246
+ const limit = current.getTime() + DAY_MS;
247
+ const future = backups.filter((backup) => backup.at.getTime() > limit).length;
248
+ if (future > 0)
249
+ throw new PruneRefusedError("future_backups", future);
250
+ // A listing can cross a page boundary between a dump and its sidecar while a concurrent run
251
+ // writes both, so a recent orphan may be a live sidecar: only older ones are deleted.
252
+ const settled = current.getTime() - DAY_MS;
253
+ const orphans = orphanDigests.filter((digest) => digest.at.getTime() < settled);
254
+ const plan = planRetention(backups, keep);
255
+ assertKeepsSomething(backups.length, plan.keep.length);
256
+ const deleted = plan.remove.map((entry) => entry.key);
257
+ const deletedDigests = [
258
+ ...plan.remove.flatMap((entry) => (entry.digestKey === null ? [] : [entry.digestKey])),
259
+ ...orphans.map((digest) => digest.key),
260
+ ];
261
+ if (!dryRun) {
262
+ // Each dump before its sidecar: a batch that fails leaves at worst a sidecar without a dump,
263
+ // which the next run deletes, never a kept dump without its digest.
264
+ const keys = [
265
+ ...plan.remove.flatMap((entry) => entry.digestKey === null ? [entry.key] : [entry.key, entry.digestKey]),
266
+ ...orphans.map((digest) => digest.key),
267
+ ];
268
+ for (let i = 0; i < keys.length; i += DELETE_BATCH) {
269
+ try {
270
+ await bucket.delete(keys.slice(i, i + DELETE_BATCH));
271
+ }
272
+ catch (error) {
273
+ throw new Error(`pruneBackups: a delete batch failed after ${i} of ${keys.length} keys were deleted; the next run continues.`, { cause: error });
274
+ }
275
+ }
276
+ }
277
+ return {
278
+ dryRun,
279
+ kept: plan.keep.map((entry) => entry.key),
280
+ deleted,
281
+ deletedDigests,
282
+ ignored,
283
+ keyIds: keyIdsOf(plan.keep),
284
+ };
285
+ }
286
+ /**
287
+ * The last guard before deleting: a plan that keeps nothing of a non-empty list is refused.
288
+ * `planRetention` always keeps the newest, so this only fires if that ever changes.
289
+ */
290
+ export function assertKeepsSomething(total, kept) {
291
+ if (total > 0 && kept === 0) {
292
+ throw new Error("pruneBackups: refusing to delete every backup.");
293
+ }
294
+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AAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,CAAC,SAAS,CAAC,CACtE;YACD,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC;SACvC,CAAC;QACF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,YAAY,EAAE,CAAC;YACnD,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC;YACvD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,IAAI,KAAK,CACb,6CAA6C,CAAC,OAAO,IAAI,CAAC,MAAM,6CAA6C,EAC7G,EAAE,KAAK,EAAE,KAAK,EAAE,CACjB,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO;QACL,MAAM;QACN,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC;QACzC,OAAO;QACP,cAAc;QACd,OAAO;QACP,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC;KAC5B,CAAC;AACJ,CAAC;AACD;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAa,EAAE,IAAY;IAC9D,IAAI,KAAK,GAAG,CAAC,IAAI,IAAI,KAAK,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACpE,CAAC;AACH,CAAC"}
package/dist/run.d.ts ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The whole backup as one function, without a Workflow: for small databases (a cron handler that
3
+ * finishes within its time limit) and for tests. Nothing here retries a failed step: a failed run
4
+ * is a result, and the next scheduled run starts over. The one exception is an export Cloudflare
5
+ * says is not running any more (`not_exporting`, `export_lost`): a new one is started, at most
6
+ * `MAX_RESTARTS` times, within the same deadline.
7
+ */
8
+ import { type CopyFailureReason } from "./copy.js";
9
+ import { type BackupEncryption, type BackupEncryptionInfo, type BackupEncryptionOptions } from "./encryption.js";
10
+ import { type D1Exporter, type ExportFailureReason } from "./export.js";
11
+ import { type PruneRefusal, type Retention } from "./retention.js";
12
+ export interface RunBackupOptions {
13
+ readonly exporter: D1Exporter;
14
+ readonly bucket: R2Bucket;
15
+ /** Where the backups go, e.g. `"d1/main"`: one prefix per database. */
16
+ readonly prefix: string;
17
+ /** Prune after the copy with this policy; without it nothing is pruned. */
18
+ readonly keep?: Retention;
19
+ /** Between polls. 500 to 60 000 ms, default 2000. */
20
+ readonly pollIntervalMs?: number;
21
+ /**
22
+ * The export must be ready within this, counted from before `start` (restarted exports
23
+ * included). 1000 to 900 000 ms, default 240 000 (4 minutes).
24
+ */
25
+ readonly timeoutMs?: number;
26
+ /** See `copyExport`. */
27
+ readonly partSize?: number;
28
+ /**
29
+ * The whole copy must finish within this (`copyExport`'s `timeoutMs`: the download, every R2
30
+ * write and the sidecar). 1000 to 21 600 000 ms, default 480 000 (8 minutes).
31
+ *
32
+ * The defaults inside the 15 minutes a Cron Trigger may run: `start`, the polls and any
33
+ * restarted export take at most `timeoutMs` (4 min) plus one last request (30 s, `d1Export`'s
34
+ * `timeoutMs`);
35
+ * the copy at most `copyTimeoutMs` (8 min) plus 5 s to abort an open multipart upload. That
36
+ * is about 12.6 minutes, leaving over 2 minutes for listing and pruning (a list call per 1000
37
+ * objects under the prefix and a delete call per 1000 keys removed). Raise either only with
38
+ * that sum in mind.
39
+ */
40
+ readonly copyTimeoutMs?: number;
41
+ /**
42
+ * The clock the key is built from, the deadline measured with and future-dated backups judged
43
+ * by (see `pruneBackups`). Default `Date`.
44
+ */
45
+ readonly now?: () => Date;
46
+ /** For tests: how to wait between polls. Default `setTimeout`. */
47
+ readonly sleep?: (ms: number) => Promise<void>;
48
+ /**
49
+ * Encrypt the dump (`backupEncryption(…)` or its options), validated before anything starts.
50
+ * See `copyExport`.
51
+ */
52
+ readonly encryption?: BackupEncryption | BackupEncryptionOptions;
53
+ }
54
+ export type RunBackupResult = {
55
+ readonly ok: true;
56
+ readonly key: string;
57
+ /** The stored object's size (encrypted, for an encrypted backup). */
58
+ readonly size: number;
59
+ readonly bookmark: string;
60
+ /**
61
+ * The stored object's SHA-256 (of the encrypted bytes, for an encrypted backup), or `null`
62
+ * where the runtime cannot compute it (see `copyExport`).
63
+ */
64
+ readonly sha256: string | null;
65
+ /** Scheme and key id: only for an encrypted backup. */
66
+ readonly encryption?: BackupEncryptionInfo;
67
+ /** Counts, when `keep` was given. */
68
+ readonly pruned?: {
69
+ readonly kept: number;
70
+ readonly deleted: number;
71
+ };
72
+ } | {
73
+ readonly ok: false;
74
+ readonly stage: "start" | "poll" | "copy";
75
+ readonly reason: ExportFailureReason | CopyFailureReason | "deadline";
76
+ readonly retryable: boolean;
77
+ } | {
78
+ /** The backup was copied (`key`), but pruning refused: nothing was deleted. */
79
+ readonly ok: false;
80
+ readonly stage: "prune";
81
+ readonly reason: PruneRefusal;
82
+ readonly retryable: false;
83
+ readonly key: string;
84
+ };
85
+ /**
86
+ * Starts an export, polls it every `pollIntervalMs` until it is ready or `timeoutMs` passed,
87
+ * copies it into `bucket` from the answer that reported it complete (never polling again) and,
88
+ * with `keep`, prunes. An export Cloudflare stops running (`not_exporting`, `export_lost`) is
89
+ * started again, at most twice (`MAX_RESTARTS`); after that the result is that reason, at stage
90
+ * `"poll"` (or `"start"` if a start answered it). Results for every expected outcome; a
91
+ * `TypeError` for invalid options. The database may not serve queries while the export runs.
92
+ */
93
+ export declare function runBackup(options: RunBackupOptions): Promise<RunBackupResult>;
94
+ //# sourceMappingURL=run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../src/run.ts"],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,qEAAqE;IACrE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,uDAAuD;IACvD,QAAQ,CAAC,UAAU,CAAC,EAAE,oBAAoB,CAAC;IAC3C,qCAAqC;IACrC,QAAQ,CAAC,MAAM,CAAC,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;CACvE,GACD;IACE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IACnB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;IAC1C,QAAQ,CAAC,MAAM,EAAE,mBAAmB,GAAG,iBAAiB,GAAG,UAAU,CAAC;IACtE,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;CAC7B,GACD;IACE,+EAA+E;IAC/E,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IACnB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC;IAC1B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB,CAAC;AAMN;;;;;;;GAOG;AACH,wBAAsB,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC,CAuGnF"}
package/dist/run.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The whole backup as one function, without a Workflow: for small databases (a cron handler that
3
+ * finishes within its time limit) and for tests. Nothing here retries a failed step: a failed run
4
+ * is a result, and the next scheduled run starts over. The one exception is an export Cloudflare
5
+ * says is not running any more (`not_exporting`, `export_lost`): a new one is started, at most
6
+ * `MAX_RESTARTS` times, within the same deadline.
7
+ */
8
+ import { assertEncryptable, copyExport } from "./copy.js";
9
+ import { encryptionOption, } from "./encryption.js";
10
+ import { isRestartable, MAX_RESTARTS, } from "./export.js";
11
+ import { assertValidPrefix, backupKey } from "./keys.js";
12
+ import { assertValidRetention, PruneRefusedError, pruneBackups, } from "./retention.js";
13
+ function wholeIn(value, min, max) {
14
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max;
15
+ }
16
+ /**
17
+ * Starts an export, polls it every `pollIntervalMs` until it is ready or `timeoutMs` passed,
18
+ * copies it into `bucket` from the answer that reported it complete (never polling again) and,
19
+ * with `keep`, prunes. An export Cloudflare stops running (`not_exporting`, `export_lost`) is
20
+ * started again, at most twice (`MAX_RESTARTS`); after that the result is that reason, at stage
21
+ * `"poll"` (or `"start"` if a start answered it). Results for every expected outcome; a
22
+ * `TypeError` for invalid options. The database may not serve queries while the export runs.
23
+ */
24
+ export async function runBackup(options) {
25
+ if (typeof options !== "object" || options === null) {
26
+ throw new TypeError("runBackup: options { exporter, bucket, prefix } are required.");
27
+ }
28
+ const { exporter, bucket, prefix, keep, partSize } = options;
29
+ const copyTimeoutMs = options.copyTimeoutMs ?? 480_000;
30
+ const pollIntervalMs = options.pollIntervalMs ?? 2000;
31
+ const timeoutMs = options.timeoutMs ?? 240_000;
32
+ const now = options.now ?? (() => new Date());
33
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
34
+ if (typeof exporter !== "object" || exporter === null || typeof exporter.start !== "function") {
35
+ throw new TypeError("runBackup: exporter must be the client returned by d1Export.");
36
+ }
37
+ assertValidPrefix(prefix, "runBackup");
38
+ if (keep !== undefined)
39
+ assertValidRetention(keep, "runBackup");
40
+ if (!wholeIn(pollIntervalMs, 500, 60_000)) {
41
+ throw new TypeError("runBackup: pollIntervalMs must be 500 to 60000.");
42
+ }
43
+ if (!wholeIn(timeoutMs, 1000, 900_000)) {
44
+ throw new TypeError("runBackup: timeoutMs must be 1000 to 900000.");
45
+ }
46
+ if (!wholeIn(copyTimeoutMs, 1000, 21_600_000)) {
47
+ throw new TypeError("runBackup: copyTimeoutMs must be 1000 to 21600000.");
48
+ }
49
+ if (typeof now !== "function" || typeof sleep !== "function") {
50
+ throw new TypeError("runBackup: now and sleep must be functions.");
51
+ }
52
+ // Refused here, before an export starts, never at the copy.
53
+ const encryption = encryptionOption(options, "runBackup");
54
+ const at = now();
55
+ const key = backupKey(prefix, at);
56
+ // A hand-built exporter's id must fit the encrypted header: refused before the export starts.
57
+ assertEncryptable(encryption, exporter.databaseId, key, "runBackup");
58
+ // This call's identity in the object's metadata: never another run's object at the same key.
59
+ const run = crypto.randomUUID();
60
+ const deadline = at.getTime() + timeoutMs;
61
+ let stage = "start";
62
+ let restarts = 0;
63
+ let answer = await exporter.start();
64
+ // The answer that reports the export complete is the one copied from: Cloudflare hands the
65
+ // signed URL out once, so nothing polls after it.
66
+ while (answer.status !== "ready") {
67
+ if (answer.status === "failed") {
68
+ if (!isRestartable(answer.reason) || restarts >= MAX_RESTARTS) {
69
+ return { ok: false, stage, reason: answer.reason, retryable: answer.retryable };
70
+ }
71
+ if (now().getTime() > deadline) {
72
+ return { ok: false, stage: "poll", reason: "deadline", retryable: true };
73
+ }
74
+ // Cloudflare is not running this export any more (cancelled, say, or the answer was about
75
+ // another export): start a new one. Unlike the Workflow's poll step, nothing here looks
76
+ // for a finished copy first: this call copies once, after this loop, and never restarts
77
+ // after a copy, so no object of its run can exist yet.
78
+ restarts += 1;
79
+ stage = "start";
80
+ answer = await exporter.start();
81
+ continue;
82
+ }
83
+ if (now().getTime() + pollIntervalMs > deadline) {
84
+ return { ok: false, stage: "poll", reason: "deadline", retryable: true };
85
+ }
86
+ await sleep(pollIntervalMs);
87
+ stage = "poll";
88
+ answer = await exporter.poll(answer.bookmark);
89
+ }
90
+ const copied = await copyExport({
91
+ exporter,
92
+ ready: answer,
93
+ bucket,
94
+ key,
95
+ run,
96
+ timeoutMs: copyTimeoutMs,
97
+ ...(partSize === undefined ? {} : { partSize }),
98
+ ...(encryption === null ? {} : { encryption }),
99
+ });
100
+ if (!copied.ok) {
101
+ return { ok: false, stage: "copy", reason: copied.reason, retryable: copied.retryable };
102
+ }
103
+ const result = {
104
+ ok: true,
105
+ key: copied.key,
106
+ size: copied.size,
107
+ bookmark: copied.bookmark,
108
+ sha256: copied.sha256,
109
+ ...(copied.encryption === undefined ? {} : { encryption: copied.encryption }),
110
+ };
111
+ if (keep === undefined)
112
+ return result;
113
+ try {
114
+ const pruned = await pruneBackups(bucket, {
115
+ prefix,
116
+ databaseId: exporter.databaseId,
117
+ keep,
118
+ now,
119
+ });
120
+ return { ...result, pruned: { kept: pruned.kept.length, deleted: pruned.deleted.length } };
121
+ }
122
+ catch (error) {
123
+ if (error instanceof PruneRefusedError) {
124
+ return { ok: false, stage: "prune", reason: error.reason, retryable: false, key: copied.key };
125
+ }
126
+ throw error;
127
+ }
128
+ }
129
+ //# sourceMappingURL=run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,iBAAiB,EAA0B,UAAU,EAAE,MAAM,WAAW,CAAC;AAClF,OAAO,EAIL,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAIL,aAAa,EACb,YAAY,GACb,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EACL,oBAAoB,EAEpB,iBAAiB,EACjB,YAAY,GAEb,MAAM,gBAAgB,CAAC;AA6ExB,SAAS,OAAO,CAAC,KAAc,EAAE,GAAW,EAAE,GAAW;IACvD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,GAAG,IAAI,KAAK,IAAI,GAAG,CAAC;AAClG,CAAC;AAED;;;;;;;GAOG;AACH,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,CAAC;AACH,CAAC"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Whether a stream starts like a SQL dump, read chunk by chunk: an optional UTF-8 byte order
3
+ * mark and whitespace, then `PRAGMA`, `BEGIN`, `CREATE` or `INSERT` (any case) followed by a
4
+ * space, a tab or a line break. D1's own export starts with `PRAGMA defer_foreign_keys=TRUE;`.
5
+ * Only the first bytes are looked at: an error page (`<html>`, `<?xml`, `{"errors"`) is caught,
6
+ * a broken dump further on is not.
7
+ */
8
+ export interface SqlSniffer {
9
+ /** `"ok"` once the start matched, `"bad"` once it cannot, else `"more"`. */
10
+ feed(chunk: Uint8Array): "ok" | "bad" | "more";
11
+ /** The verdict at the end of the stream: `"more"` means the stream ended too soon. */
12
+ end(): "ok" | "bad" | "more";
13
+ }
14
+ export declare function createSqlSniffer(): SqlSniffer;
15
+ //# sourceMappingURL=sniff.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sniff.d.ts","sourceRoot":"","sources":["../src/sniff.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,MAAM,WAAW,UAAU;IACzB,4EAA4E;IAC5E,IAAI,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,GAAG,KAAK,GAAG,MAAM,CAAC;IAC/C,sFAAsF;IACtF,GAAG,IAAI,IAAI,GAAG,KAAK,GAAG,MAAM,CAAC;CAC9B;AAID,wBAAgB,gBAAgB,IAAI,UAAU,CAgC7C"}
package/dist/sniff.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Whether a stream starts like a SQL dump, read chunk by chunk: an optional UTF-8 byte order
3
+ * mark and whitespace, then `PRAGMA`, `BEGIN`, `CREATE` or `INSERT` (any case) followed by a
4
+ * space, a tab or a line break. D1's own export starts with `PRAGMA defer_foreign_keys=TRUE;`.
5
+ * Only the first bytes are looked at: an error page (`<html>`, `<?xml`, `{"errors"`) is caught,
6
+ * a broken dump further on is not.
7
+ */
8
+ const KEYWORDS = ["PRAGMA", "BEGIN", "CREATE", "INSERT"];
9
+ /** Leading whitespace allowed before the first keyword. */
10
+ const MAX_LEADING = 1024;
11
+ const isSpace = (b) => b === 0x20 || b === 0x09 || b === 0x0a || b === 0x0d;
12
+ export function createSqlSniffer() {
13
+ let verdict = "more";
14
+ let seen = 0; // bytes looked at so far
15
+ let word = ""; // the first word, upper case, once it started
16
+ function byte(b) {
17
+ seen += 1;
18
+ // A byte order mark (EF BB BF) at the very start.
19
+ if (word === "" && seen <= 3 && b === [0xef, 0xbb, 0xbf][seen - 1])
20
+ return;
21
+ if (word === "") {
22
+ if (isSpace(b)) {
23
+ if (seen > MAX_LEADING)
24
+ verdict = "bad";
25
+ return;
26
+ }
27
+ }
28
+ if (isSpace(b)) {
29
+ verdict = KEYWORDS.includes(word) ? "ok" : "bad";
30
+ return;
31
+ }
32
+ word += String.fromCharCode(b).toUpperCase();
33
+ if (!KEYWORDS.some((keyword) => keyword.startsWith(word)))
34
+ verdict = "bad";
35
+ }
36
+ return {
37
+ feed(chunk) {
38
+ for (let i = 0; i < chunk.byteLength && verdict === "more"; i++)
39
+ byte(chunk[i]);
40
+ return verdict;
41
+ },
42
+ end() {
43
+ return verdict === "more" && seen === 0 ? "more" : verdict === "more" ? "bad" : verdict;
44
+ },
45
+ };
46
+ }
47
+ //# sourceMappingURL=sniff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sniff.js","sourceRoot":"","sources":["../src/sniff.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,QAAQ,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;AACzD,2DAA2D;AAC3D,MAAM,WAAW,GAAG,IAAI,CAAC;AASzB,MAAM,OAAO,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC;AAEpF,MAAM,UAAU,gBAAgB;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