@softistx/mongo-backup 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +484 -2
- package/dist/backups/key-file.d.ts +30 -0
- package/dist/backups/key-file.d.ts.map +1 -0
- package/dist/backups/mongo-backups.d.ts +33 -0
- package/dist/backups/mongo-backups.d.ts.map +1 -0
- package/dist/backups/operations.d.ts +55 -0
- package/dist/backups/operations.d.ts.map +1 -0
- package/dist/backups/options.d.ts +60 -0
- package/dist/backups/options.d.ts.map +1 -0
- package/dist/backups/plan.d.ts +20 -0
- package/dist/backups/plan.d.ts.map +1 -0
- package/dist/chunks/index-j0tptz7w.js +97 -0
- package/dist/chunks/index-j0tptz7w.js.map +11 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +31 -0
- package/dist/cli.js.map +10 -0
- package/dist/errors.d.ts +43 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/format/bson-stream.d.ts +13 -0
- package/dist/format/bson-stream.d.ts.map +1 -0
- package/dist/format/change.d.ts +61 -0
- package/dist/format/change.d.ts.map +1 -0
- package/dist/format/document.d.ts +7 -0
- package/dist/format/document.d.ts.map +1 -0
- package/dist/format/metadata.d.ts +14 -0
- package/dist/format/metadata.d.ts.map +1 -0
- package/dist/format/names.d.ts +22 -0
- package/dist/format/names.d.ts.map +1 -0
- package/dist/format/position.d.ts +29 -0
- package/dist/format/position.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1340 -0
- package/dist/index.js.map +32 -0
- package/dist/restore/landing.d.ts +26 -0
- package/dist/restore/landing.d.ts.map +1 -0
- package/dist/restore/options.d.ts +59 -0
- package/dist/restore/options.d.ts.map +1 -0
- package/dist/restore/restore-collections.d.ts +12 -0
- package/dist/restore/restore-collections.d.ts.map +1 -0
- package/dist/source/catalog.d.ts +28 -0
- package/dist/source/catalog.d.ts.map +1 -0
- package/dist/source/changes.d.ts +12 -0
- package/dist/source/changes.d.ts.map +1 -0
- package/dist/source/collections.d.ts +20 -0
- package/dist/source/collections.d.ts.map +1 -0
- package/dist/source/events.d.ts +46 -0
- package/dist/source/events.d.ts.map +1 -0
- package/dist/source/followed.d.ts +13 -0
- package/dist/source/followed.d.ts.map +1 -0
- package/dist/source/mongo-source.d.ts +24 -0
- package/dist/source/mongo-source.d.ts.map +1 -0
- package/dist/source/snapshot.d.ts +17 -0
- package/dist/source/snapshot.d.ts.map +1 -0
- package/dist/target/changes.d.ts +8 -0
- package/dist/target/changes.d.ts.map +1 -0
- package/dist/target/collection.d.ts +20 -0
- package/dist/target/collection.d.ts.map +1 -0
- package/dist/target/mongo-target.d.ts +22 -0
- package/dist/target/mongo-target.d.ts.map +1 -0
- package/docs/README.md +28 -0
- package/docs/guide/errors.md +411 -0
- package/docs/guide/format.md +179 -0
- package/docs/guide/getting-started.md +716 -0
- package/docs/guide/incremental.md +323 -0
- package/docs/guide/operations.md +237 -0
- package/docs/guide/restore.md +684 -0
- package/docs/roadmap.md +61 -0
- package/docs/troubleshooting.md +1257 -0
- package/package.json +70 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,1340 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MongoBackupError2,
|
|
3
|
+
serverCode,
|
|
4
|
+
renamed,
|
|
5
|
+
generateKeyFile2,
|
|
6
|
+
readKeyFile2
|
|
7
|
+
} from "./chunks/index-j0tptz7w.js";
|
|
8
|
+
// src/backups/mongo-backups.ts
|
|
9
|
+
import {
|
|
10
|
+
defineBackup,
|
|
11
|
+
localRepository
|
|
12
|
+
} from "@softistx/backup";
|
|
13
|
+
|
|
14
|
+
// src/backups/operations.ts
|
|
15
|
+
import {
|
|
16
|
+
bindBackup
|
|
17
|
+
} from "@softistx/backup";
|
|
18
|
+
|
|
19
|
+
// src/source/catalog.ts
|
|
20
|
+
import {
|
|
21
|
+
BSON as BSON2
|
|
22
|
+
} from "mongodb";
|
|
23
|
+
|
|
24
|
+
// src/source/collections.ts
|
|
25
|
+
import { BSON } from "mongodb";
|
|
26
|
+
function takes(filter, name) {
|
|
27
|
+
if (name.startsWith("system."))
|
|
28
|
+
return false;
|
|
29
|
+
if (filter === undefined)
|
|
30
|
+
return true;
|
|
31
|
+
return typeof filter === "function" ? filter(name) : filter.includes(name);
|
|
32
|
+
}
|
|
33
|
+
async function listed(db, filter) {
|
|
34
|
+
const all = await db.listCollections({}, { nameOnly: false }).toArray();
|
|
35
|
+
const found = [];
|
|
36
|
+
for (const info of all) {
|
|
37
|
+
if (!takes(filter, info.name))
|
|
38
|
+
continue;
|
|
39
|
+
if (info.type !== "collection" && info.type !== "view") {
|
|
40
|
+
throw new MongoBackupError2("mongoSource: a collection is of a type this version does not back up " + "(a time-series one); leave it out with collections", "UNSUPPORTED");
|
|
41
|
+
}
|
|
42
|
+
found.push({
|
|
43
|
+
name: info.name,
|
|
44
|
+
type: info.type,
|
|
45
|
+
options: info.options ?? {},
|
|
46
|
+
uuid: BSON.EJSON.stringify(info.info?.uuid ?? null)
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(filter)) {
|
|
50
|
+
const names = new Set(found.map((c) => c.name));
|
|
51
|
+
if (!filter.every((name) => names.has(name))) {
|
|
52
|
+
throw new TypeError("mongoSource: a collection named in collections is not in the database");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return found.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/source/catalog.ts
|
|
59
|
+
var NAMESPACE_NOT_FOUND = 26;
|
|
60
|
+
var ATTEMPTS = 5;
|
|
61
|
+
async function indexesOf(db, collection) {
|
|
62
|
+
if (collection.type === "view")
|
|
63
|
+
return [];
|
|
64
|
+
const indexes = await db.collection(collection.name).listIndexes().toArray();
|
|
65
|
+
return indexes.filter((index) => index["name"] !== "_id_").map(({ v: _v, ns: _ns, ...index }) => index);
|
|
66
|
+
}
|
|
67
|
+
async function describe(db, filter) {
|
|
68
|
+
const found = [];
|
|
69
|
+
try {
|
|
70
|
+
for (const collection of await listed(db, filter)) {
|
|
71
|
+
const indexes = await indexesOf(db, collection);
|
|
72
|
+
found.push({
|
|
73
|
+
...collection,
|
|
74
|
+
metadata: {
|
|
75
|
+
type: collection.type,
|
|
76
|
+
options: collection.options,
|
|
77
|
+
indexes
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (serverCode(error) === NAMESPACE_NOT_FOUND)
|
|
83
|
+
return;
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
return found;
|
|
87
|
+
}
|
|
88
|
+
async function pin(db) {
|
|
89
|
+
const session = db.client.startSession({ snapshot: true });
|
|
90
|
+
try {
|
|
91
|
+
await db.collection(`nxgt-snapshot-${crypto.randomUUID()}`).distinct("_id", {}, { session });
|
|
92
|
+
const at = session.snapshotTime;
|
|
93
|
+
if (!at) {
|
|
94
|
+
throw new MongoBackupError2("mongoSource: the server gave no snapshot time; a backup needs a " + "replica set or a sharded cluster", "UNSUPPORTED");
|
|
95
|
+
}
|
|
96
|
+
return { session, at };
|
|
97
|
+
} catch (error) {
|
|
98
|
+
await session.endSession();
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
var same = (a, b) => a !== undefined && b !== undefined && BSON2.EJSON.stringify(a, { relaxed: false }) === BSON2.EJSON.stringify(b, { relaxed: false });
|
|
103
|
+
async function pinnedCatalog(db, filter) {
|
|
104
|
+
for (let attempt = 0;attempt < ATTEMPTS; attempt++) {
|
|
105
|
+
const before = await describe(db, filter);
|
|
106
|
+
const pinned = await pin(db);
|
|
107
|
+
const after = await describe(db, filter).catch(async (error) => {
|
|
108
|
+
await pinned.session.endSession();
|
|
109
|
+
throw error;
|
|
110
|
+
});
|
|
111
|
+
if (same(before, after)) {
|
|
112
|
+
return { ...pinned, catalog: after };
|
|
113
|
+
}
|
|
114
|
+
await pinned.session.endSession();
|
|
115
|
+
}
|
|
116
|
+
throw new MongoBackupError2("mongoSource: the collections or their indexes kept changing while the " + "snapshot was taken; try again when they settle", "CHANGING");
|
|
117
|
+
}
|
|
118
|
+
function after(at) {
|
|
119
|
+
return at.i === 4294967295 ? new BSON2.Timestamp({ t: at.t + 1, i: 0 }) : new BSON2.Timestamp({ t: at.t, i: at.i + 1 });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// src/target/mongo-target.ts
|
|
123
|
+
import { tmpdir } from "node:os";
|
|
124
|
+
import { isAbsolute } from "node:path";
|
|
125
|
+
|
|
126
|
+
// src/format/metadata.ts
|
|
127
|
+
import { BSON as BSON3 } from "mongodb";
|
|
128
|
+
|
|
129
|
+
// src/format/document.ts
|
|
130
|
+
function isDocument(value) {
|
|
131
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && !("_bsontype" in value);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/format/metadata.ts
|
|
135
|
+
var METADATA_FORMAT = "nxgt-mongo-backup-metadata/1";
|
|
136
|
+
function writeMetadata(metadata) {
|
|
137
|
+
return BSON3.EJSON.stringify({ format: METADATA_FORMAT, ...metadata }, { relaxed: false });
|
|
138
|
+
}
|
|
139
|
+
function readMetadata(text) {
|
|
140
|
+
let value;
|
|
141
|
+
try {
|
|
142
|
+
value = BSON3.EJSON.parse(text, { relaxed: false });
|
|
143
|
+
} catch {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (!isDocument(value) || value["format"] !== METADATA_FORMAT) {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const { type, options, indexes } = value;
|
|
150
|
+
if (type !== "collection" && type !== "view" || !isDocument(options) || !Array.isArray(indexes) || !indexes.every((index) => isDocument(index) && typeof index["name"] === "string")) {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
return { type, options, indexes };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// src/format/names.ts
|
|
157
|
+
var METADATA = "metadata/";
|
|
158
|
+
var DOCUMENTS = "documents/";
|
|
159
|
+
var CHANGES = "changes/";
|
|
160
|
+
function parseName(name) {
|
|
161
|
+
for (const [prefix, kind] of [
|
|
162
|
+
[METADATA, "metadata"],
|
|
163
|
+
[DOCUMENTS, "documents"]
|
|
164
|
+
]) {
|
|
165
|
+
if (name.startsWith(prefix) && name.length > prefix.length) {
|
|
166
|
+
return { kind, collection: name.slice(prefix.length) };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (name.startsWith(CHANGES)) {
|
|
170
|
+
const digits = name.slice(CHANGES.length);
|
|
171
|
+
if (/^\d{6,9}$/.test(digits)) {
|
|
172
|
+
return { kind: "changes", sequence: Number.parseInt(digits, 10) };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
function changesName(sequence) {
|
|
178
|
+
return `${CHANGES}${String(sequence).padStart(6, "0")}`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// src/target/changes.ts
|
|
182
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
183
|
+
import { join } from "node:path";
|
|
184
|
+
|
|
185
|
+
// src/format/bson-stream.ts
|
|
186
|
+
var DOCUMENT_MAX_BYTES = 17 * 1024 * 1024;
|
|
187
|
+
async function* bsonDocuments(stream, where) {
|
|
188
|
+
const malformed = () => new MongoBackupError2(`${where}: an entry is not a sequence of BSON documents`, "MALFORMED");
|
|
189
|
+
let carry = new Uint8Array(0);
|
|
190
|
+
let document;
|
|
191
|
+
let filled = 0;
|
|
192
|
+
for await (const chunk of stream) {
|
|
193
|
+
const data = carry.length === 0 ? chunk : concat(carry, chunk);
|
|
194
|
+
carry = new Uint8Array(0);
|
|
195
|
+
let offset = 0;
|
|
196
|
+
while (offset < data.length) {
|
|
197
|
+
if (document) {
|
|
198
|
+
const n = Math.min(document.length - filled, data.length - offset);
|
|
199
|
+
document.set(data.subarray(offset, offset + n), filled);
|
|
200
|
+
filled += n;
|
|
201
|
+
offset += n;
|
|
202
|
+
if (filled === document.length) {
|
|
203
|
+
yield document;
|
|
204
|
+
document = undefined;
|
|
205
|
+
}
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (data.length - offset < 4) {
|
|
209
|
+
carry = data.slice(offset);
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
const length = new DataView(data.buffer, data.byteOffset + offset, 4).getInt32(0, true);
|
|
213
|
+
if (length < 5 || length > DOCUMENT_MAX_BYTES)
|
|
214
|
+
throw malformed();
|
|
215
|
+
document = new Uint8Array(length);
|
|
216
|
+
filled = 0;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (document || carry.length > 0)
|
|
220
|
+
throw malformed();
|
|
221
|
+
}
|
|
222
|
+
function concat(a, b) {
|
|
223
|
+
const joined = new Uint8Array(a.length + b.length);
|
|
224
|
+
joined.set(a);
|
|
225
|
+
joined.set(b, a.length);
|
|
226
|
+
return joined;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// src/format/change.ts
|
|
230
|
+
import { BSON as BSON4 } from "mongodb";
|
|
231
|
+
var EXACT = { promoteValues: false, bsonRegExp: true };
|
|
232
|
+
function writeChange(change) {
|
|
233
|
+
return BSON4.serialize(change);
|
|
234
|
+
}
|
|
235
|
+
var isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
236
|
+
function readChange(bytes) {
|
|
237
|
+
const value = BSON4.deserialize(bytes, EXACT);
|
|
238
|
+
const { op, coll } = value;
|
|
239
|
+
if (op === "dropDatabase")
|
|
240
|
+
return { op };
|
|
241
|
+
if (typeof coll !== "string" || coll.length === 0)
|
|
242
|
+
return;
|
|
243
|
+
switch (op) {
|
|
244
|
+
case "insert":
|
|
245
|
+
case "replace":
|
|
246
|
+
return isDocument(value["key"]) && isDocument(value["doc"]) ? { op, coll, key: value["key"], doc: value["doc"] } : undefined;
|
|
247
|
+
case "update":
|
|
248
|
+
return readUpdate(coll, value);
|
|
249
|
+
case "delete":
|
|
250
|
+
return isDocument(value["key"]) ? { op, coll, key: value["key"] } : undefined;
|
|
251
|
+
case "create":
|
|
252
|
+
return isDocument(value["options"]) ? { op, coll, options: value["options"] } : undefined;
|
|
253
|
+
case "createIndexes": {
|
|
254
|
+
const indexes = value["indexes"];
|
|
255
|
+
return Array.isArray(indexes) && indexes.every(isDocument) ? { op, coll, indexes } : undefined;
|
|
256
|
+
}
|
|
257
|
+
case "dropIndexes":
|
|
258
|
+
return isStrings(value["names"]) ? { op, coll, names: value["names"] } : undefined;
|
|
259
|
+
case "modify":
|
|
260
|
+
return isDocument(value["changes"]) ? { op, coll, changes: value["changes"] } : undefined;
|
|
261
|
+
case "drop":
|
|
262
|
+
return { op, coll };
|
|
263
|
+
case "rename":
|
|
264
|
+
return typeof value["to"] === "string" && typeof value["dropTarget"] === "boolean" ? { op, coll, to: value["to"], dropTarget: value["dropTarget"] } : undefined;
|
|
265
|
+
default:
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function readUpdate(coll, value) {
|
|
270
|
+
const { key, set, unset, truncated } = value;
|
|
271
|
+
if (!isDocument(key) || !isDocument(set) || !isStrings(unset) || !Array.isArray(truncated)) {
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const cuts = [];
|
|
275
|
+
for (const cut of truncated) {
|
|
276
|
+
const size = Number(cut?.newSize);
|
|
277
|
+
if (typeof cut?.field !== "string" || !Number.isSafeInteger(size)) {
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
cuts.push({ field: cut.field, newSize: size });
|
|
281
|
+
}
|
|
282
|
+
return { op: "update", coll, key, set, unset, truncated: cuts };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// src/target/collection.ts
|
|
286
|
+
import { BSON as BSON5 } from "mongodb";
|
|
287
|
+
var NAMESPACE_EXISTS = 48;
|
|
288
|
+
var NAMESPACE_NOT_FOUND2 = 26;
|
|
289
|
+
var BATCH_DOCUMENTS = 1000;
|
|
290
|
+
var BATCH_BYTES = 8 * 1024 * 1024;
|
|
291
|
+
function exists(db, name) {
|
|
292
|
+
return db.listCollections({ name }, { nameOnly: true }).toArray().then((found) => found.length > 0);
|
|
293
|
+
}
|
|
294
|
+
async function isView(db, name) {
|
|
295
|
+
const [found] = await db.listCollections({ name }, { nameOnly: true }).toArray();
|
|
296
|
+
return found?.type === "view";
|
|
297
|
+
}
|
|
298
|
+
function taken() {
|
|
299
|
+
return new MongoBackupError2("mongoTarget: a collection or view the backup holds is already in the " + "database; restore into another one, or pass replace: true", "EXISTS");
|
|
300
|
+
}
|
|
301
|
+
async function dropIfThere(db, name) {
|
|
302
|
+
await db.dropCollection(name).catch((error) => {
|
|
303
|
+
if (serverCode(error) !== NAMESPACE_NOT_FOUND2)
|
|
304
|
+
throw error;
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
async function restoreView(db, name, metadata, replace) {
|
|
308
|
+
if (await exists(db, name)) {
|
|
309
|
+
if (!replace)
|
|
310
|
+
throw taken();
|
|
311
|
+
await dropIfThere(db, name);
|
|
312
|
+
}
|
|
313
|
+
await db.createCollection(name, metadata.options);
|
|
314
|
+
}
|
|
315
|
+
async function insertAll(db, staging, stream) {
|
|
316
|
+
const collection = db.collection(staging);
|
|
317
|
+
let batch = [];
|
|
318
|
+
let bytes = 0;
|
|
319
|
+
const flush = async () => {
|
|
320
|
+
if (batch.length === 0)
|
|
321
|
+
return;
|
|
322
|
+
await collection.insertMany(batch, {
|
|
323
|
+
bypassDocumentValidation: true,
|
|
324
|
+
ordered: true
|
|
325
|
+
});
|
|
326
|
+
batch = [];
|
|
327
|
+
bytes = 0;
|
|
328
|
+
};
|
|
329
|
+
for await (const raw of bsonDocuments(stream, "mongoTarget")) {
|
|
330
|
+
batch.push(BSON5.deserialize(raw, EXACT));
|
|
331
|
+
bytes += raw.length;
|
|
332
|
+
if (batch.length >= BATCH_DOCUMENTS || bytes >= BATCH_BYTES)
|
|
333
|
+
await flush();
|
|
334
|
+
}
|
|
335
|
+
await flush();
|
|
336
|
+
}
|
|
337
|
+
async function restoreCollection(db, name, metadata, stream, replace) {
|
|
338
|
+
if (!replace && await exists(db, name)) {
|
|
339
|
+
await stream.cancel();
|
|
340
|
+
throw taken();
|
|
341
|
+
}
|
|
342
|
+
const staging = `nxgt-restore-${crypto.randomUUID()}`;
|
|
343
|
+
try {
|
|
344
|
+
await db.createCollection(staging, metadata.options);
|
|
345
|
+
await insertAll(db, staging, stream);
|
|
346
|
+
if (metadata.indexes.length > 0) {
|
|
347
|
+
await db.collection(staging).createIndexes(metadata.indexes);
|
|
348
|
+
}
|
|
349
|
+
if (replace && await isView(db, name))
|
|
350
|
+
await dropIfThere(db, name);
|
|
351
|
+
await db.collection(staging).rename(name, { dropTarget: replace }).catch((error) => {
|
|
352
|
+
throw serverCode(error) === NAMESPACE_EXISTS ? taken() : error;
|
|
353
|
+
});
|
|
354
|
+
} catch (error) {
|
|
355
|
+
await dropIfThere(db, staging).catch(() => {
|
|
356
|
+
return;
|
|
357
|
+
});
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// src/target/changes.ts
|
|
363
|
+
var NAMESPACE_NOT_FOUND3 = 26;
|
|
364
|
+
var BATCH = 1000;
|
|
365
|
+
function operationsOf(change) {
|
|
366
|
+
switch (change.op) {
|
|
367
|
+
case "insert":
|
|
368
|
+
case "replace":
|
|
369
|
+
return [
|
|
370
|
+
{
|
|
371
|
+
replaceOne: {
|
|
372
|
+
filter: change.key,
|
|
373
|
+
replacement: change.doc,
|
|
374
|
+
upsert: true
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
];
|
|
378
|
+
case "delete":
|
|
379
|
+
return [{ deleteOne: { filter: change.key } }];
|
|
380
|
+
case "update": {
|
|
381
|
+
const cuts = change.truncated.map((cut) => ({
|
|
382
|
+
updateOne: {
|
|
383
|
+
filter: change.key,
|
|
384
|
+
update: {
|
|
385
|
+
$push: { [cut.field]: { $each: [], $slice: cut.newSize } }
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}));
|
|
389
|
+
const update = {};
|
|
390
|
+
if (Object.keys(change.set).length > 0)
|
|
391
|
+
update["$set"] = change.set;
|
|
392
|
+
if (change.unset.length > 0) {
|
|
393
|
+
update["$unset"] = Object.fromEntries(change.unset.map((f) => [f, ""]));
|
|
394
|
+
}
|
|
395
|
+
return Object.keys(update).length === 0 ? cuts : [...cuts, { updateOne: { filter: change.key, update } }];
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
var NAMESPACE_EXISTS2 = 48;
|
|
400
|
+
var INDEX_NOT_FOUND = 27;
|
|
401
|
+
var ignoring = (...codes) => (error) => {
|
|
402
|
+
if (!codes.includes(serverCode(error) ?? 0))
|
|
403
|
+
throw error;
|
|
404
|
+
};
|
|
405
|
+
async function applyToCollection(db, change, replace) {
|
|
406
|
+
switch (change.op) {
|
|
407
|
+
case "create":
|
|
408
|
+
if (await exists(db, change.coll)) {
|
|
409
|
+
if (!replace)
|
|
410
|
+
throw taken();
|
|
411
|
+
await dropIfThere(db, change.coll);
|
|
412
|
+
}
|
|
413
|
+
await db.createCollection(change.coll, change.options);
|
|
414
|
+
return;
|
|
415
|
+
case "createIndexes":
|
|
416
|
+
await db.collection(change.coll).createIndexes(change.indexes);
|
|
417
|
+
return;
|
|
418
|
+
case "dropIndexes":
|
|
419
|
+
for (const name of change.names) {
|
|
420
|
+
await db.collection(change.coll).dropIndex(name).catch(ignoring(INDEX_NOT_FOUND, NAMESPACE_NOT_FOUND3));
|
|
421
|
+
}
|
|
422
|
+
return;
|
|
423
|
+
case "modify":
|
|
424
|
+
await db.command({ collMod: change.coll, ...change.changes }).catch(ignoring(NAMESPACE_NOT_FOUND3));
|
|
425
|
+
return;
|
|
426
|
+
case "drop":
|
|
427
|
+
return dropIfThere(db, change.coll);
|
|
428
|
+
case "rename":
|
|
429
|
+
await db.renameCollection(change.coll, change.to, {
|
|
430
|
+
dropTarget: change.dropTarget || replace
|
|
431
|
+
}).catch((error) => {
|
|
432
|
+
if (serverCode(error) === NAMESPACE_EXISTS2)
|
|
433
|
+
throw taken();
|
|
434
|
+
ignoring(NAMESPACE_NOT_FOUND3)(error);
|
|
435
|
+
});
|
|
436
|
+
return;
|
|
437
|
+
case "dropDatabase":
|
|
438
|
+
await db.dropDatabase();
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
async function applyFile(db, file, replace) {
|
|
443
|
+
let coll = "";
|
|
444
|
+
let pending = [];
|
|
445
|
+
const flush = async () => {
|
|
446
|
+
if (pending.length > 0) {
|
|
447
|
+
await db.collection(coll).bulkWrite(pending, { ordered: true, bypassDocumentValidation: true });
|
|
448
|
+
}
|
|
449
|
+
pending = [];
|
|
450
|
+
};
|
|
451
|
+
for await (const bytes of bsonDocuments(Bun.file(file).stream(), "mongoTarget")) {
|
|
452
|
+
const change = readChange(bytes);
|
|
453
|
+
if (!change) {
|
|
454
|
+
throw new MongoBackupError2("mongoTarget: a change is not one this version wrote", "MALFORMED");
|
|
455
|
+
}
|
|
456
|
+
if (!("key" in change)) {
|
|
457
|
+
await flush();
|
|
458
|
+
await applyToCollection(db, change, replace);
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
if (change.coll !== coll || pending.length >= BATCH)
|
|
462
|
+
await flush();
|
|
463
|
+
coll = change.coll;
|
|
464
|
+
pending.push(...operationsOf(change));
|
|
465
|
+
}
|
|
466
|
+
await flush();
|
|
467
|
+
}
|
|
468
|
+
async function restoreChanges(db, stream, tmpDir, replace) {
|
|
469
|
+
const folder = await mkdtemp(join(tmpDir, "nxgt-mongo-changes-"));
|
|
470
|
+
try {
|
|
471
|
+
const file = join(folder, "changes.bson");
|
|
472
|
+
await Bun.write(file, new Response(stream));
|
|
473
|
+
await applyFile(db, file, replace);
|
|
474
|
+
} finally {
|
|
475
|
+
await rm(folder, { recursive: true, force: true });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// src/target/mongo-target.ts
|
|
480
|
+
var METADATA_MAX_BYTES = 16 * 1024 * 1024;
|
|
481
|
+
var malformed = (what) => new MongoBackupError2(`mongoTarget: ${what}`, "MALFORMED");
|
|
482
|
+
async function metadataFrom(stream) {
|
|
483
|
+
const chunks = [];
|
|
484
|
+
let size = 0;
|
|
485
|
+
for await (const chunk of stream) {
|
|
486
|
+
size += chunk.length;
|
|
487
|
+
if (size > METADATA_MAX_BYTES) {
|
|
488
|
+
await stream.cancel().catch(() => {
|
|
489
|
+
return;
|
|
490
|
+
});
|
|
491
|
+
throw malformed("a metadata entry is larger than 16 MiB");
|
|
492
|
+
}
|
|
493
|
+
chunks.push(chunk);
|
|
494
|
+
}
|
|
495
|
+
const metadata = readMetadata(new TextDecoder().decode(Buffer.concat(chunks)));
|
|
496
|
+
if (!metadata)
|
|
497
|
+
throw malformed("a metadata entry is not one this version wrote");
|
|
498
|
+
return metadata;
|
|
499
|
+
}
|
|
500
|
+
function checkOptions(options) {
|
|
501
|
+
const db = options?.db;
|
|
502
|
+
if (typeof db?.collection !== "function" || typeof db.databaseName !== "string") {
|
|
503
|
+
throw new TypeError("mongoTarget: db must be a MongoDB Db");
|
|
504
|
+
}
|
|
505
|
+
if (options.tmpDir !== undefined && !isAbsolute(options.tmpDir)) {
|
|
506
|
+
throw new TypeError("mongoTarget: tmpDir must be an absolute path");
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
function mongoTarget(options) {
|
|
510
|
+
checkOptions(options);
|
|
511
|
+
const { db } = options;
|
|
512
|
+
const replace = options.replace === true;
|
|
513
|
+
const tmpDir = options.tmpDir ?? tmpdir();
|
|
514
|
+
const metadata = new Map;
|
|
515
|
+
return {
|
|
516
|
+
async write(name, stream) {
|
|
517
|
+
const parsed = parseName(name);
|
|
518
|
+
if (!parsed) {
|
|
519
|
+
await stream.cancel();
|
|
520
|
+
throw malformed("an entry name is not one this version writes");
|
|
521
|
+
}
|
|
522
|
+
if (parsed.kind === "changes") {
|
|
523
|
+
return restoreChanges(db, stream, tmpDir, replace);
|
|
524
|
+
}
|
|
525
|
+
if (parsed.kind === "metadata") {
|
|
526
|
+
const read = await metadataFrom(stream);
|
|
527
|
+
metadata.set(parsed.collection, read);
|
|
528
|
+
if (read.type === "view") {
|
|
529
|
+
await restoreView(db, parsed.collection, read, replace);
|
|
530
|
+
}
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
const known = metadata.get(parsed.collection);
|
|
534
|
+
if (!known) {
|
|
535
|
+
await stream.cancel();
|
|
536
|
+
throw malformed("a collection’s documents came before its metadata");
|
|
537
|
+
}
|
|
538
|
+
await restoreCollection(db, parsed.collection, known, stream, replace);
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// src/restore/landing.ts
|
|
544
|
+
var NAMESPACE_EXISTS3 = 48;
|
|
545
|
+
function taken2(where) {
|
|
546
|
+
return new MongoBackupError2(`${where}: a collection or view to restore is already in the ` + "database; restore it under another name, or pass replace: true", "EXISTS");
|
|
547
|
+
}
|
|
548
|
+
async function landWhole(scratch, db, chosen, replace, where) {
|
|
549
|
+
if (!replace) {
|
|
550
|
+
for (const { as } of chosen)
|
|
551
|
+
if (await exists(db, as))
|
|
552
|
+
throw taken2(where);
|
|
553
|
+
}
|
|
554
|
+
const renamed = new Map(chosen.map((c) => [c.described.name, c.as]));
|
|
555
|
+
const admin = db.client.db("admin");
|
|
556
|
+
for (const { described, as } of chosen) {
|
|
557
|
+
if (described.type === "view")
|
|
558
|
+
continue;
|
|
559
|
+
if (replace && await isView(db, as))
|
|
560
|
+
await dropIfThere(db, as);
|
|
561
|
+
await admin.command({
|
|
562
|
+
renameCollection: `${scratch.databaseName}.${described.name}`,
|
|
563
|
+
to: `${db.databaseName}.${as}`,
|
|
564
|
+
dropTarget: replace
|
|
565
|
+
}).catch((error) => {
|
|
566
|
+
throw serverCode(error) === NAMESPACE_EXISTS3 ? taken2(where) : error;
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
for (const { described, as } of chosen) {
|
|
570
|
+
if (described.type !== "view")
|
|
571
|
+
continue;
|
|
572
|
+
const { viewOn, ...options } = described.metadata.options;
|
|
573
|
+
if (replace)
|
|
574
|
+
await dropIfThere(db, as);
|
|
575
|
+
await db.createCollection(as, {
|
|
576
|
+
...options,
|
|
577
|
+
viewOn: renamed.get(viewOn) ?? viewOn
|
|
578
|
+
}).catch((error) => {
|
|
579
|
+
throw serverCode(error) === NAMESPACE_EXISTS3 ? taken2(where) : error;
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
async function landDocuments(scratch, db, chosen, selection) {
|
|
584
|
+
const counts = new Map;
|
|
585
|
+
for (const { described, as } of chosen) {
|
|
586
|
+
if (described.type === "view")
|
|
587
|
+
continue;
|
|
588
|
+
if (!await exists(db, as))
|
|
589
|
+
await createLike(db, as, described);
|
|
590
|
+
const from = scratch.collection(described.name);
|
|
591
|
+
counts.set(described.name, await from.countDocuments(selection.filter));
|
|
592
|
+
await from.aggregate([
|
|
593
|
+
{ $match: selection.filter },
|
|
594
|
+
{
|
|
595
|
+
$merge: {
|
|
596
|
+
into: { db: db.databaseName, coll: as },
|
|
597
|
+
on: "_id",
|
|
598
|
+
whenMatched: selection.existing === "replace" ? "replace" : "keepExisting",
|
|
599
|
+
whenNotMatched: "insert"
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
], { bypassDocumentValidation: true }).toArray();
|
|
603
|
+
}
|
|
604
|
+
return counts;
|
|
605
|
+
}
|
|
606
|
+
async function createLike(db, as, described) {
|
|
607
|
+
await db.createCollection(as, described.metadata.options).catch((error) => {
|
|
608
|
+
if (serverCode(error) !== NAMESPACE_EXISTS3)
|
|
609
|
+
throw error;
|
|
610
|
+
});
|
|
611
|
+
const { indexes } = described.metadata;
|
|
612
|
+
if (indexes.length > 0) {
|
|
613
|
+
await db.collection(as).createIndexes(indexes);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/restore/options.ts
|
|
618
|
+
var NAME = /^[^$\0]+$/;
|
|
619
|
+
function destinationOf(as, name, where = "restoreCollections") {
|
|
620
|
+
const to = as === undefined ? name : typeof as === "function" ? as(name) : Object.hasOwn(as, name) ? as[name] : name;
|
|
621
|
+
if (typeof to !== "string" || !NAME.test(to) || to.startsWith("system.")) {
|
|
622
|
+
throw new TypeError(`${where}: as must give a collection name`);
|
|
623
|
+
}
|
|
624
|
+
return to;
|
|
625
|
+
}
|
|
626
|
+
function checkAs(as, where) {
|
|
627
|
+
if (as === undefined || typeof as === "function")
|
|
628
|
+
return;
|
|
629
|
+
const names = Object.keys(as);
|
|
630
|
+
const targets = names.map((name) => destinationOf(as, name, where));
|
|
631
|
+
if (new Set(targets).size !== targets.length) {
|
|
632
|
+
throw new TypeError(`${where}: as gives two collections one name`);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
function isDb(value) {
|
|
636
|
+
const db = value;
|
|
637
|
+
return typeof db?.collection === "function" && typeof db.databaseName === "string";
|
|
638
|
+
}
|
|
639
|
+
function checkOptions2(options, where) {
|
|
640
|
+
if (!isDb(options?.db)) {
|
|
641
|
+
throw new TypeError(`${where}: db must be a MongoDB Db`);
|
|
642
|
+
}
|
|
643
|
+
if (options.scratch !== undefined && !isDb(options.scratch)) {
|
|
644
|
+
throw new TypeError(`${where}: scratch must be a MongoDB Db`);
|
|
645
|
+
}
|
|
646
|
+
if (options.scratch !== undefined && options.scratch.client !== options.db.client) {
|
|
647
|
+
throw new TypeError(`${where}: scratch must be on db's client`);
|
|
648
|
+
}
|
|
649
|
+
if (options.scratch?.databaseName === options.db.databaseName) {
|
|
650
|
+
throw new TypeError(`${where}: scratch must be another database`);
|
|
651
|
+
}
|
|
652
|
+
checkAs(options.as, where);
|
|
653
|
+
const { documents } = options;
|
|
654
|
+
if (documents !== undefined && (!isDocument(documents?.filter) || documents.existing !== "replace" && documents.existing !== "keep")) {
|
|
655
|
+
throw new TypeError(`${where}: documents must be { filter, existing: 'replace' | 'keep' }`);
|
|
656
|
+
}
|
|
657
|
+
if (documents !== undefined && options.replace !== undefined) {
|
|
658
|
+
throw new TypeError(`${where}: replace is for whole collections; documents says what happens to those there`);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// src/restore/restore-collections.ts
|
|
663
|
+
async function checkEmpty(scratch, where) {
|
|
664
|
+
const held = await scratch.listCollections({}, { nameOnly: true }).toArray();
|
|
665
|
+
if (held.some((info) => !info.name.startsWith("system."))) {
|
|
666
|
+
throw new MongoBackupError2(`${where}: the scratch database holds collections; give an empty one`, "EXISTS");
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
function checkAsKeys(as, described, where) {
|
|
670
|
+
if (as === undefined || typeof as === "function")
|
|
671
|
+
return;
|
|
672
|
+
const names = new Set(described.map((d) => d.name));
|
|
673
|
+
if (!Object.keys(as).every((key) => names.has(key))) {
|
|
674
|
+
throw new TypeError(`${where}: as names a collection not restored`);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
async function choose(scratch, options, where) {
|
|
678
|
+
const { collections } = options;
|
|
679
|
+
if (Array.isArray(collections)) {
|
|
680
|
+
const held = await scratch.listCollections({}, { nameOnly: true }).toArray();
|
|
681
|
+
const names = new Set(held.map((info) => info.name).filter((n) => !n.startsWith("system.")));
|
|
682
|
+
if (!collections.every((name) => names.has(name))) {
|
|
683
|
+
throw new MongoBackupError2(`${where}: a collection named in collections is not in the backup`, "NOT_FOUND");
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
const described = (await describe(scratch, collections) ?? []).filter((d) => !options.documents || d.type !== "view");
|
|
687
|
+
checkAsKeys(options.as, described, where);
|
|
688
|
+
const chosen = described.map((d) => ({
|
|
689
|
+
described: d,
|
|
690
|
+
as: destinationOf(options.as, d.name, where)
|
|
691
|
+
}));
|
|
692
|
+
if (new Set(chosen.map((c) => c.as)).size !== chosen.length) {
|
|
693
|
+
throw new TypeError(`${where}: as gives two collections one name`);
|
|
694
|
+
}
|
|
695
|
+
return chosen;
|
|
696
|
+
}
|
|
697
|
+
function restoreCollections(backups, id, options) {
|
|
698
|
+
return renamed(restoreSome(backups, id, options, "restoreCollections"), "restoreCollections");
|
|
699
|
+
}
|
|
700
|
+
async function restoreSome(backups, id, options, where) {
|
|
701
|
+
checkOptions2(options, where);
|
|
702
|
+
const { db } = options;
|
|
703
|
+
const scratch = options.scratch ?? db.client.db(`nxgt-restore-${crypto.randomUUID()}`);
|
|
704
|
+
if (options.scratch)
|
|
705
|
+
await checkEmpty(scratch, where);
|
|
706
|
+
try {
|
|
707
|
+
const restored = await backups.restore(id, mongoTarget({ db: scratch, tmpDir: options.tmpDir }), { identities: options.identities, from: options.from });
|
|
708
|
+
const chosen = await choose(scratch, options, where);
|
|
709
|
+
let counts;
|
|
710
|
+
if (options.documents) {
|
|
711
|
+
counts = await landDocuments(scratch, db, chosen, options.documents);
|
|
712
|
+
} else {
|
|
713
|
+
await landWhole(scratch, db, chosen, options.replace === true, where);
|
|
714
|
+
}
|
|
715
|
+
return {
|
|
716
|
+
...restored,
|
|
717
|
+
collections: chosen.map(({ described, as }) => {
|
|
718
|
+
const documents = counts?.get(described.name);
|
|
719
|
+
return documents === undefined ? { name: described.name, as } : { name: described.name, as, documents };
|
|
720
|
+
})
|
|
721
|
+
};
|
|
722
|
+
} finally {
|
|
723
|
+
await scratch.dropDatabase().catch(() => {
|
|
724
|
+
return;
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// src/format/position.ts
|
|
730
|
+
import { BSON as BSON6 } from "mongodb";
|
|
731
|
+
var POSITION_FORMAT = "nxgt-mongo-backup-position/1";
|
|
732
|
+
function writePosition(position) {
|
|
733
|
+
return BSON6.EJSON.stringify({
|
|
734
|
+
format: POSITION_FORMAT,
|
|
735
|
+
...position.resume,
|
|
736
|
+
added: [...position.added].sort(),
|
|
737
|
+
removed: [...position.removed].sort()
|
|
738
|
+
}, { relaxed: false });
|
|
739
|
+
}
|
|
740
|
+
var isNames = (value) => Array.isArray(value) && value.every((name) => typeof name === "string");
|
|
741
|
+
function resumeOf(record) {
|
|
742
|
+
const at = record["startAtOperationTime"];
|
|
743
|
+
if (at instanceof BSON6.Timestamp)
|
|
744
|
+
return { startAtOperationTime: at };
|
|
745
|
+
const after = record["startAfter"];
|
|
746
|
+
if (isDocument(after))
|
|
747
|
+
return { startAfter: after };
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
function readPosition(text) {
|
|
751
|
+
if (text === undefined)
|
|
752
|
+
return;
|
|
753
|
+
let value;
|
|
754
|
+
try {
|
|
755
|
+
value = BSON6.EJSON.parse(text, { relaxed: false });
|
|
756
|
+
} catch {
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
if (!isDocument(value) || value["format"] !== POSITION_FORMAT) {
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
const resume = resumeOf(value);
|
|
763
|
+
const { added, removed } = value;
|
|
764
|
+
if (!resume || !isNames(added) || !isNames(removed))
|
|
765
|
+
return;
|
|
766
|
+
return { resume, added, removed };
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// src/source/events.ts
|
|
770
|
+
var unsupported = (what) => new MongoBackupError2(`mongoSource: ${what}`, "UNSUPPORTED");
|
|
771
|
+
function updateOf(event, coll, key) {
|
|
772
|
+
if (event.fullDocument) {
|
|
773
|
+
return { op: "replace", coll, key, doc: event.fullDocument };
|
|
774
|
+
}
|
|
775
|
+
const update = event.updateDescription ?? {};
|
|
776
|
+
if (Object.keys(update.disambiguatedPaths ?? {}).length > 0) {
|
|
777
|
+
throw unsupported("an update touched a field whose name holds a dot or is a number, " + "which a change cannot say without its post-image; turn on " + "changeStreamPreAndPostImages for that collection, or make a full backup");
|
|
778
|
+
}
|
|
779
|
+
return {
|
|
780
|
+
op: "update",
|
|
781
|
+
coll,
|
|
782
|
+
key,
|
|
783
|
+
set: update.updatedFields ?? {},
|
|
784
|
+
unset: update.removedFields ?? [],
|
|
785
|
+
truncated: (update.truncatedArrays ?? []).map((cut) => ({
|
|
786
|
+
field: cut.field,
|
|
787
|
+
newSize: Number(cut.newSize)
|
|
788
|
+
}))
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
function ddlOf(event, coll, db) {
|
|
792
|
+
const described = event.operationDescription ?? {};
|
|
793
|
+
switch (event.operationType) {
|
|
794
|
+
case "create": {
|
|
795
|
+
if (event.nsType === "timeseries") {
|
|
796
|
+
throw unsupported("a collection is of a type this version does not back up " + "(a time-series one); leave it out with collections");
|
|
797
|
+
}
|
|
798
|
+
const { idIndex: _idIndex, ...options } = described;
|
|
799
|
+
return { op: "create", coll, options };
|
|
800
|
+
}
|
|
801
|
+
case "createIndexes":
|
|
802
|
+
return {
|
|
803
|
+
op: "createIndexes",
|
|
804
|
+
coll,
|
|
805
|
+
indexes: (described["indexes"] ?? []).map(({ v: _v, ns: _ns, ...index }) => index)
|
|
806
|
+
};
|
|
807
|
+
case "dropIndexes":
|
|
808
|
+
return {
|
|
809
|
+
op: "dropIndexes",
|
|
810
|
+
coll,
|
|
811
|
+
names: (described["indexes"] ?? []).map((index) => String(index["name"]))
|
|
812
|
+
};
|
|
813
|
+
case "modify":
|
|
814
|
+
return { op: "modify", coll, changes: described };
|
|
815
|
+
case "drop":
|
|
816
|
+
return { op: "drop", coll };
|
|
817
|
+
case "rename":
|
|
818
|
+
return event.to?.db === db ? {
|
|
819
|
+
op: "rename",
|
|
820
|
+
coll,
|
|
821
|
+
to: event.to.coll,
|
|
822
|
+
dropTarget: described["dropTarget"] !== undefined
|
|
823
|
+
} : { op: "drop", coll };
|
|
824
|
+
default:
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
function changeOf(event, db) {
|
|
829
|
+
const coll = event.ns?.coll ?? "";
|
|
830
|
+
const key = event.documentKey ?? {};
|
|
831
|
+
switch (event.operationType) {
|
|
832
|
+
case "insert":
|
|
833
|
+
case "replace":
|
|
834
|
+
return {
|
|
835
|
+
op: event.operationType,
|
|
836
|
+
coll,
|
|
837
|
+
key,
|
|
838
|
+
doc: event.fullDocument ?? {}
|
|
839
|
+
};
|
|
840
|
+
case "update":
|
|
841
|
+
return updateOf(event, coll, key);
|
|
842
|
+
case "delete":
|
|
843
|
+
return { op: "delete", coll, key };
|
|
844
|
+
case "dropDatabase":
|
|
845
|
+
return { op: "dropDatabase" };
|
|
846
|
+
default:
|
|
847
|
+
return ddlOf(event, coll, db);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
function passedOver(event, held, filter) {
|
|
851
|
+
const coll = event.ns?.coll;
|
|
852
|
+
if (coll === undefined || event.operationType === "rename")
|
|
853
|
+
return false;
|
|
854
|
+
return event.operationType === "create" ? !takes(filter, coll) : !held.has(coll);
|
|
855
|
+
}
|
|
856
|
+
function followed(change, held, filter) {
|
|
857
|
+
switch (change.op) {
|
|
858
|
+
case "dropDatabase":
|
|
859
|
+
held.clear();
|
|
860
|
+
return change;
|
|
861
|
+
case "create":
|
|
862
|
+
held.add(change.coll);
|
|
863
|
+
return change;
|
|
864
|
+
case "drop":
|
|
865
|
+
held.delete(change.coll);
|
|
866
|
+
return change;
|
|
867
|
+
case "rename":
|
|
868
|
+
return renamed2(change, held, filter);
|
|
869
|
+
default:
|
|
870
|
+
return change;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
function renamed2(change, held, filter) {
|
|
874
|
+
const from = held.has(change.coll);
|
|
875
|
+
const to = takes(filter, change.to);
|
|
876
|
+
if (from)
|
|
877
|
+
held.delete(change.coll);
|
|
878
|
+
if (from && to) {
|
|
879
|
+
held.add(change.to);
|
|
880
|
+
return change;
|
|
881
|
+
}
|
|
882
|
+
if (from)
|
|
883
|
+
return { op: "drop", coll: change.coll };
|
|
884
|
+
if (to) {
|
|
885
|
+
throw unsupported("a collection was renamed into those backed up, with documents an " + "incremental backup never read; make a full backup");
|
|
886
|
+
}
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// src/source/changes.ts
|
|
891
|
+
var HISTORY_LOST = new Set([286, 280]);
|
|
892
|
+
function lost(error) {
|
|
893
|
+
return HISTORY_LOST.has(serverCode(error) ?? 0) ? new MongoBackupError2("mongoSource: the change stream cannot resume where the last backup " + "stopped: the oplog no longer reaches back there; make a full backup", "HISTORY_LOST", { cause: error }) : error;
|
|
894
|
+
}
|
|
895
|
+
function changesOf(db, from, held, until, filter, record) {
|
|
896
|
+
let stream;
|
|
897
|
+
let resume = from;
|
|
898
|
+
const finish = async (controller) => {
|
|
899
|
+
await stream?.close();
|
|
900
|
+
record(resume);
|
|
901
|
+
controller.close();
|
|
902
|
+
};
|
|
903
|
+
return new ReadableStream({
|
|
904
|
+
async pull(controller) {
|
|
905
|
+
try {
|
|
906
|
+
stream ??= db.watch([], {
|
|
907
|
+
...from,
|
|
908
|
+
fullDocument: "whenAvailable",
|
|
909
|
+
showExpandedEvents: true,
|
|
910
|
+
...EXACT
|
|
911
|
+
});
|
|
912
|
+
for (;; ) {
|
|
913
|
+
const event = await stream.tryNext();
|
|
914
|
+
if (event === null) {
|
|
915
|
+
resume = { startAfter: stream.resumeToken };
|
|
916
|
+
return await finish(controller);
|
|
917
|
+
}
|
|
918
|
+
if (event.operationType === "invalidate") {
|
|
919
|
+
resume = { startAfter: event._id };
|
|
920
|
+
return await finish(controller);
|
|
921
|
+
}
|
|
922
|
+
if (event.clusterTime?.greaterThan(until)) {
|
|
923
|
+
return await finish(controller);
|
|
924
|
+
}
|
|
925
|
+
resume = { startAfter: event._id };
|
|
926
|
+
if (passedOver(event, held, filter))
|
|
927
|
+
continue;
|
|
928
|
+
const change = changeOf(event, db.databaseName);
|
|
929
|
+
const kept = change && followed(change, held, filter);
|
|
930
|
+
if (kept) {
|
|
931
|
+
controller.enqueue(writeChange(kept));
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
} catch (error) {
|
|
936
|
+
await stream?.close().catch(() => {
|
|
937
|
+
return;
|
|
938
|
+
});
|
|
939
|
+
controller.error(lost(error));
|
|
940
|
+
}
|
|
941
|
+
},
|
|
942
|
+
async cancel() {
|
|
943
|
+
await stream?.close();
|
|
944
|
+
}
|
|
945
|
+
});
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
// src/source/followed.ts
|
|
949
|
+
function heldByFull(since) {
|
|
950
|
+
const names = new Set;
|
|
951
|
+
for (const name of since.entries.keys()) {
|
|
952
|
+
if (name.startsWith(METADATA))
|
|
953
|
+
names.add(name.slice(METADATA.length));
|
|
954
|
+
}
|
|
955
|
+
return names;
|
|
956
|
+
}
|
|
957
|
+
function followedFrom(full, position) {
|
|
958
|
+
const held = new Set([...full, ...position.added]);
|
|
959
|
+
for (const name of position.removed)
|
|
960
|
+
held.delete(name);
|
|
961
|
+
return held;
|
|
962
|
+
}
|
|
963
|
+
function differenceOf(full, held) {
|
|
964
|
+
return {
|
|
965
|
+
added: [...held].filter((name) => !full.has(name)),
|
|
966
|
+
removed: [...full].filter((name) => !held.has(name))
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
var POSITION_MAX_BYTES = 64 * 1024;
|
|
970
|
+
function fitting(text) {
|
|
971
|
+
if (Buffer.byteLength(text) > POSITION_MAX_BYTES) {
|
|
972
|
+
throw new MongoBackupError2("mongoSource: the collections created, renamed or dropped since the " + "full backup are too many to record; make a full backup", "UNSUPPORTED");
|
|
973
|
+
}
|
|
974
|
+
return text;
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// src/source/snapshot.ts
|
|
978
|
+
var SNAPSHOT_TOO_OLD = 239;
|
|
979
|
+
async function operationTime(db) {
|
|
980
|
+
const session = db.client.startSession();
|
|
981
|
+
try {
|
|
982
|
+
await db.command({ ping: 1 }, { session });
|
|
983
|
+
const time = session.operationTime;
|
|
984
|
+
if (!time) {
|
|
985
|
+
throw new MongoBackupError2("mongoSource: the server gave no operation time; a backup needs a " + "replica set or a sharded cluster", "UNSUPPORTED");
|
|
986
|
+
}
|
|
987
|
+
return time;
|
|
988
|
+
} finally {
|
|
989
|
+
await session.endSession();
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
function textStream(text) {
|
|
993
|
+
return new Response(text).body;
|
|
994
|
+
}
|
|
995
|
+
function documentsOf(db, name, session) {
|
|
996
|
+
const cursor = db.collection(name).find({}, { session, raw: true, batchSize: 1000 });
|
|
997
|
+
return new ReadableStream({
|
|
998
|
+
async pull(controller) {
|
|
999
|
+
try {
|
|
1000
|
+
const next = await cursor.next();
|
|
1001
|
+
if (next === null)
|
|
1002
|
+
controller.close();
|
|
1003
|
+
else
|
|
1004
|
+
controller.enqueue(next);
|
|
1005
|
+
} catch (error) {
|
|
1006
|
+
controller.error(serverCode(error) === SNAPSHOT_TOO_OLD ? new MongoBackupError2("mongoSource: the snapshot outlived the history the server keeps; " + "raise minSnapshotHistoryWindowInSeconds, or back up fewer " + "collections at a time", "SNAPSHOT_TOO_OLD", { cause: error }) : error);
|
|
1007
|
+
}
|
|
1008
|
+
},
|
|
1009
|
+
async cancel() {
|
|
1010
|
+
await cursor.close();
|
|
1011
|
+
}
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
async function* snapshotEntries(db, filter, record) {
|
|
1015
|
+
const { session, at, catalog } = await pinnedCatalog(db, filter);
|
|
1016
|
+
const fingerprint = `snapshot:${at.toString()}`;
|
|
1017
|
+
try {
|
|
1018
|
+
for (const collection of catalog) {
|
|
1019
|
+
const metadata = writeMetadata(collection.metadata);
|
|
1020
|
+
yield {
|
|
1021
|
+
name: `${METADATA}${collection.name}`,
|
|
1022
|
+
fingerprint,
|
|
1023
|
+
open: () => textStream(metadata)
|
|
1024
|
+
};
|
|
1025
|
+
if (collection.type === "collection") {
|
|
1026
|
+
yield {
|
|
1027
|
+
name: `${DOCUMENTS}${collection.name}`,
|
|
1028
|
+
fingerprint,
|
|
1029
|
+
open: () => documentsOf(db, collection.name, session)
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
record(after(at));
|
|
1034
|
+
} finally {
|
|
1035
|
+
await session.endSession();
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// src/source/mongo-source.ts
|
|
1040
|
+
function checkOptions3(options) {
|
|
1041
|
+
const db = options?.db;
|
|
1042
|
+
if (typeof db?.watch !== "function" || typeof db.databaseName !== "string") {
|
|
1043
|
+
throw new TypeError("mongoSource: db must be a MongoDB Db");
|
|
1044
|
+
}
|
|
1045
|
+
const filter = options.collections;
|
|
1046
|
+
if (filter !== undefined && typeof filter !== "function" && !(Array.isArray(filter) && filter.every((n) => typeof n === "string"))) {
|
|
1047
|
+
throw new TypeError("mongoSource: collections must be a list of names or a function");
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
async function* changesEntries(options, since, record) {
|
|
1051
|
+
const from = readPosition(since.position);
|
|
1052
|
+
if (!from) {
|
|
1053
|
+
throw new MongoBackupError2("mongoSource: the backup built on recorded no position this version " + "reads; make a full backup", "MALFORMED");
|
|
1054
|
+
}
|
|
1055
|
+
const full = heldByFull(since);
|
|
1056
|
+
const held = followedFrom(full, from);
|
|
1057
|
+
const until = await operationTime(options.db);
|
|
1058
|
+
let changes = 0;
|
|
1059
|
+
for (const [name, known] of since.entries) {
|
|
1060
|
+
if (name.startsWith(CHANGES))
|
|
1061
|
+
changes++;
|
|
1062
|
+
yield {
|
|
1063
|
+
name,
|
|
1064
|
+
fingerprint: known.fingerprint,
|
|
1065
|
+
open: () => {
|
|
1066
|
+
throw new MongoBackupError2("mongoSource: an entry of the backup built on was asked for again; " + "it has no fingerprint, so make a full backup", "MALFORMED");
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
const name = changesName(changes + 1);
|
|
1071
|
+
yield {
|
|
1072
|
+
name,
|
|
1073
|
+
fingerprint: `changes:${since.id}:${name}`,
|
|
1074
|
+
open: () => changesOf(options.db, from.resume, held, until, options.collections, (resume) => record({ resume, ...differenceOf(full, held) }))
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
function mongoSource(options) {
|
|
1078
|
+
checkOptions3(options);
|
|
1079
|
+
let position;
|
|
1080
|
+
const record = (at) => {
|
|
1081
|
+
position = fitting(writePosition(at));
|
|
1082
|
+
};
|
|
1083
|
+
return {
|
|
1084
|
+
kind: "mongo",
|
|
1085
|
+
entries(since) {
|
|
1086
|
+
position = undefined;
|
|
1087
|
+
return since ? changesEntries(options, since, record) : snapshotEntries(options.db, options.collections, (start) => record({
|
|
1088
|
+
resume: { startAtOperationTime: start },
|
|
1089
|
+
added: [],
|
|
1090
|
+
removed: []
|
|
1091
|
+
}));
|
|
1092
|
+
},
|
|
1093
|
+
position: () => position
|
|
1094
|
+
};
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// src/backups/options.ts
|
|
1098
|
+
import { isAbsolute as isAbsolute2 } from "node:path";
|
|
1099
|
+
var HOUR = 60 * 60 * 1000;
|
|
1100
|
+
var DAY = 24 * HOUR;
|
|
1101
|
+
var DEFAULT_FULL_EVERY = 7 * DAY;
|
|
1102
|
+
var DEFAULT_KEEP = {
|
|
1103
|
+
last: 24,
|
|
1104
|
+
daily: 14,
|
|
1105
|
+
weekly: 8,
|
|
1106
|
+
monthly: 12
|
|
1107
|
+
};
|
|
1108
|
+
var RULES = [
|
|
1109
|
+
"last",
|
|
1110
|
+
"hourly",
|
|
1111
|
+
"daily",
|
|
1112
|
+
"weekly",
|
|
1113
|
+
"monthly",
|
|
1114
|
+
"yearly",
|
|
1115
|
+
"within",
|
|
1116
|
+
"maxTotalSize"
|
|
1117
|
+
];
|
|
1118
|
+
function checkKeep(keep) {
|
|
1119
|
+
if (keep === undefined || keep === false)
|
|
1120
|
+
return;
|
|
1121
|
+
const policy = keep;
|
|
1122
|
+
const named = typeof policy === "object" && policy !== null && RULES.some((rule) => policy[rule] !== undefined) && RULES.every((rule) => {
|
|
1123
|
+
const value = policy[rule];
|
|
1124
|
+
return value === undefined || Number.isSafeInteger(value) && value >= 1;
|
|
1125
|
+
});
|
|
1126
|
+
if (!named) {
|
|
1127
|
+
throw new TypeError("mongoBackups: keep must be false, or name rules each a whole number, 1 or more");
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
function checkRestore(at, where) {
|
|
1131
|
+
const into = at?.into;
|
|
1132
|
+
if (typeof into?.collection !== "function" || typeof into.databaseName !== "string") {
|
|
1133
|
+
throw new TypeError(`${where}: into must be a MongoDB Db`);
|
|
1134
|
+
}
|
|
1135
|
+
const when = at?.at;
|
|
1136
|
+
if (when instanceof Date && Number.isNaN(when.getTime())) {
|
|
1137
|
+
throw new TypeError(`${where}: at must be a backup's id or a valid Date`);
|
|
1138
|
+
}
|
|
1139
|
+
if (at?.documents !== undefined && at.replace !== undefined) {
|
|
1140
|
+
throw new TypeError(`${where}: replace is for whole collections; documents says what happens to those there`);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
function checkOptions4(options) {
|
|
1144
|
+
const db = options?.db;
|
|
1145
|
+
if (typeof db?.collection !== "function" || typeof db.databaseName !== "string") {
|
|
1146
|
+
throw new TypeError("mongoBackups: db must be a MongoDB Db");
|
|
1147
|
+
}
|
|
1148
|
+
if (typeof options.keyFile !== "string" || !isAbsolute2(options.keyFile)) {
|
|
1149
|
+
throw new TypeError("mongoBackups: keyFile must be an absolute path");
|
|
1150
|
+
}
|
|
1151
|
+
const { repository } = options;
|
|
1152
|
+
const isRepository = (r) => typeof r?.name === "string";
|
|
1153
|
+
if (typeof repository === "string" ? !isAbsolute2(repository) : Array.isArray(repository) ? !repository.every(isRepository) : !isRepository(repository)) {
|
|
1154
|
+
throw new TypeError("mongoBackups: repository must be an absolute folder, or repositories");
|
|
1155
|
+
}
|
|
1156
|
+
checkKeep(options.keep);
|
|
1157
|
+
if (Array.isArray(repository)) {
|
|
1158
|
+
const names = new Set(repository.map((r) => r?.name));
|
|
1159
|
+
if (repository.length === 0 || names.size !== repository.length) {
|
|
1160
|
+
throw new TypeError("mongoBackups: repository must list repositories, each under a name of its own");
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
if (options.tmpDir !== undefined && !isAbsolute2(options.tmpDir)) {
|
|
1164
|
+
throw new TypeError("mongoBackups: tmpDir must be an absolute path");
|
|
1165
|
+
}
|
|
1166
|
+
const every = options.fullEvery;
|
|
1167
|
+
if (every !== undefined && (!Number.isSafeInteger(every) || every < HOUR)) {
|
|
1168
|
+
throw new TypeError("mongoBackups: fullEvery must be a whole number of milliseconds, an hour or more");
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
// src/backups/plan.ts
|
|
1173
|
+
function kindFor(backups, now, fullEvery) {
|
|
1174
|
+
const recent = backups.some((backup) => backup.kind === "full" && now.getTime() - backup.createdAt.getTime() < fullEvery);
|
|
1175
|
+
return recent ? "incremental" : "full";
|
|
1176
|
+
}
|
|
1177
|
+
function chosenBackup(backups, at, where) {
|
|
1178
|
+
if (typeof at === "string")
|
|
1179
|
+
return at;
|
|
1180
|
+
const before = backups.filter((b) => at === undefined || b.createdAt.getTime() <= at.getTime()).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()).at(-1);
|
|
1181
|
+
if (!before) {
|
|
1182
|
+
throw new MongoBackupError2(at === undefined ? `${where}: the repository holds no backup yet` : `${where}: no backup was made at or before that time`, "NOT_FOUND");
|
|
1183
|
+
}
|
|
1184
|
+
return before.id;
|
|
1185
|
+
}
|
|
1186
|
+
async function countsOf(db) {
|
|
1187
|
+
const listed = await db.listCollections({}, { nameOnly: true }).toArray();
|
|
1188
|
+
const counts = [];
|
|
1189
|
+
for (const info of listed.sort((a, b) => a.name < b.name ? -1 : 1)) {
|
|
1190
|
+
if (info.type !== "collection" || info.name.startsWith("system."))
|
|
1191
|
+
continue;
|
|
1192
|
+
counts.push({
|
|
1193
|
+
name: info.name,
|
|
1194
|
+
documents: await db.collection(info.name).countDocuments()
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
return counts;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
// src/backups/operations.ts
|
|
1201
|
+
var named = (ctx, call) => `${call} on "${ctx.definition.name}"`;
|
|
1202
|
+
function asCalled(p, ctx, call) {
|
|
1203
|
+
return renamed(p, named(ctx, call));
|
|
1204
|
+
}
|
|
1205
|
+
function bindingOf(ctx) {
|
|
1206
|
+
if (!ctx.ready) {
|
|
1207
|
+
const { options } = ctx;
|
|
1208
|
+
const ready = readKeyFile2(options.keyFile, named(ctx, "mongoBackups")).then((keys) => ({
|
|
1209
|
+
keys,
|
|
1210
|
+
backups: bindBackup(ctx.definition, {
|
|
1211
|
+
repositories: ctx.repositories,
|
|
1212
|
+
recipients: [keys.recipient],
|
|
1213
|
+
signing: { key: keys.signingKey },
|
|
1214
|
+
tmpDir: options.tmpDir
|
|
1215
|
+
})
|
|
1216
|
+
}));
|
|
1217
|
+
ready.catch(() => {
|
|
1218
|
+
if (ctx.ready === ready)
|
|
1219
|
+
ctx.ready = undefined;
|
|
1220
|
+
});
|
|
1221
|
+
ctx.ready = ready;
|
|
1222
|
+
}
|
|
1223
|
+
return ctx.ready;
|
|
1224
|
+
}
|
|
1225
|
+
async function listOf(ctx) {
|
|
1226
|
+
return (await (await bindingOf(ctx)).backups.list()).backups;
|
|
1227
|
+
}
|
|
1228
|
+
async function runOnce(ctx, now = new Date) {
|
|
1229
|
+
if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
|
|
1230
|
+
throw new TypeError(`${named(ctx, "run")}: now must be a valid Date`);
|
|
1231
|
+
}
|
|
1232
|
+
const { options } = ctx;
|
|
1233
|
+
const { backups, keys } = await bindingOf(ctx);
|
|
1234
|
+
const identities = [keys.identity];
|
|
1235
|
+
const source = () => mongoSource({ db: options.db, collections: options.collections });
|
|
1236
|
+
const due = kindFor(await listOf(ctx), now, options.fullEvery ?? DEFAULT_FULL_EVERY);
|
|
1237
|
+
let fellBack = false;
|
|
1238
|
+
const created = due === "full" ? await backups.create(source()) : await backups.create(source(), { kind: "incremental", identities }).catch((error) => {
|
|
1239
|
+
if (!(error instanceof MongoBackupError2))
|
|
1240
|
+
throw error;
|
|
1241
|
+
if (error.code !== "HISTORY_LOST")
|
|
1242
|
+
throw error;
|
|
1243
|
+
fellBack = true;
|
|
1244
|
+
return backups.create(source());
|
|
1245
|
+
});
|
|
1246
|
+
const verified = await backups.verify(created.id, { identities });
|
|
1247
|
+
const keep = options.keep ?? DEFAULT_KEEP;
|
|
1248
|
+
const removed = keep === false ? [] : (await backups.prune({ keep })).removed;
|
|
1249
|
+
return {
|
|
1250
|
+
id: created.id,
|
|
1251
|
+
kind: created.kind === "full" ? "full" : "incremental",
|
|
1252
|
+
fellBack,
|
|
1253
|
+
entries: created.entries,
|
|
1254
|
+
storedSize: created.storedSize,
|
|
1255
|
+
chain: verified.chain.length,
|
|
1256
|
+
removed: removed.map((decision) => decision.id)
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
async function restoreAt(ctx, at) {
|
|
1260
|
+
const where = named(ctx, "restore");
|
|
1261
|
+
checkRestore(at, where);
|
|
1262
|
+
const { tmpDir } = ctx.options;
|
|
1263
|
+
const { backups, keys } = await bindingOf(ctx);
|
|
1264
|
+
const id = chosenBackup(await listOf(ctx), at.at, where);
|
|
1265
|
+
const identities = [keys.identity];
|
|
1266
|
+
const part = at.collections !== undefined || at.as !== undefined || at.documents !== undefined;
|
|
1267
|
+
if (!part) {
|
|
1268
|
+
return backups.restore(id, mongoTarget({ db: at.into, replace: at.replace, tmpDir }), { identities });
|
|
1269
|
+
}
|
|
1270
|
+
return restoreSome(backups, id, {
|
|
1271
|
+
identities,
|
|
1272
|
+
db: at.into,
|
|
1273
|
+
collections: at.collections,
|
|
1274
|
+
as: at.as,
|
|
1275
|
+
tmpDir,
|
|
1276
|
+
...at.documents === undefined ? { replace: at.replace } : { documents: at.documents }
|
|
1277
|
+
}, where);
|
|
1278
|
+
}
|
|
1279
|
+
async function drillNewest(ctx) {
|
|
1280
|
+
const { db, tmpDir } = ctx.options;
|
|
1281
|
+
const { backups, keys } = await bindingOf(ctx);
|
|
1282
|
+
const id = chosenBackup(await listOf(ctx), undefined, named(ctx, "drill"));
|
|
1283
|
+
const drill = db.client.db(`nxgt-drill-${crypto.randomUUID()}`);
|
|
1284
|
+
try {
|
|
1285
|
+
await backups.restore(id, mongoTarget({ db: drill, tmpDir }), {
|
|
1286
|
+
identities: [keys.identity]
|
|
1287
|
+
});
|
|
1288
|
+
return { id, collections: await countsOf(drill) };
|
|
1289
|
+
} finally {
|
|
1290
|
+
await drill.dropDatabase().catch(() => {
|
|
1291
|
+
return;
|
|
1292
|
+
});
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
// src/backups/mongo-backups.ts
|
|
1297
|
+
function repositoriesOf(repository) {
|
|
1298
|
+
if (typeof repository === "string")
|
|
1299
|
+
return [localRepository({ path: repository })];
|
|
1300
|
+
if (Array.isArray(repository))
|
|
1301
|
+
return repository;
|
|
1302
|
+
return [repository];
|
|
1303
|
+
}
|
|
1304
|
+
function definitionOf(options) {
|
|
1305
|
+
try {
|
|
1306
|
+
return defineBackup({ name: options.name ?? options.db.databaseName });
|
|
1307
|
+
} catch (cause) {
|
|
1308
|
+
const rule = String(cause.message).replace(/^defineBackup: the name must be /, "");
|
|
1309
|
+
throw new TypeError(options.name === undefined ? `mongoBackups: the database's name cannot name a backup; give name: ${rule}` : `mongoBackups: name must be ${rule}`, { cause });
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
function mongoBackups(options) {
|
|
1313
|
+
checkOptions4(options);
|
|
1314
|
+
const ctx = {
|
|
1315
|
+
options,
|
|
1316
|
+
definition: definitionOf(options),
|
|
1317
|
+
repositories: repositoriesOf(options.repository)
|
|
1318
|
+
};
|
|
1319
|
+
return {
|
|
1320
|
+
binding: () => bindingOf(ctx),
|
|
1321
|
+
list: () => listOf(ctx),
|
|
1322
|
+
run: (now) => asCalled(runOnce(ctx, now), ctx, "run"),
|
|
1323
|
+
restore: (at) => asCalled(restoreAt(ctx, at), ctx, "restore"),
|
|
1324
|
+
drill: () => asCalled(drillNewest(ctx), ctx, "drill")
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
export {
|
|
1328
|
+
DEFAULT_FULL_EVERY,
|
|
1329
|
+
DEFAULT_KEEP,
|
|
1330
|
+
MongoBackupError2 as MongoBackupError,
|
|
1331
|
+
generateKeyFile2 as generateKeyFile,
|
|
1332
|
+
mongoBackups,
|
|
1333
|
+
mongoSource,
|
|
1334
|
+
mongoTarget,
|
|
1335
|
+
readKeyFile2 as readKeyFile,
|
|
1336
|
+
restoreCollections
|
|
1337
|
+
};
|
|
1338
|
+
|
|
1339
|
+
//# debugId=97E3E95757FED5EF64756E2164756E21
|
|
1340
|
+
//# sourceMappingURL=index.js.map
|