@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.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +484 -2
  3. package/dist/backups/key-file.d.ts +30 -0
  4. package/dist/backups/key-file.d.ts.map +1 -0
  5. package/dist/backups/mongo-backups.d.ts +33 -0
  6. package/dist/backups/mongo-backups.d.ts.map +1 -0
  7. package/dist/backups/operations.d.ts +55 -0
  8. package/dist/backups/operations.d.ts.map +1 -0
  9. package/dist/backups/options.d.ts +60 -0
  10. package/dist/backups/options.d.ts.map +1 -0
  11. package/dist/backups/plan.d.ts +20 -0
  12. package/dist/backups/plan.d.ts.map +1 -0
  13. package/dist/chunks/index-j0tptz7w.js +97 -0
  14. package/dist/chunks/index-j0tptz7w.js.map +11 -0
  15. package/dist/cli.d.ts +3 -0
  16. package/dist/cli.d.ts.map +1 -0
  17. package/dist/cli.js +31 -0
  18. package/dist/cli.js.map +10 -0
  19. package/dist/errors.d.ts +43 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/format/bson-stream.d.ts +13 -0
  22. package/dist/format/bson-stream.d.ts.map +1 -0
  23. package/dist/format/change.d.ts +61 -0
  24. package/dist/format/change.d.ts.map +1 -0
  25. package/dist/format/document.d.ts +7 -0
  26. package/dist/format/document.d.ts.map +1 -0
  27. package/dist/format/metadata.d.ts +14 -0
  28. package/dist/format/metadata.d.ts.map +1 -0
  29. package/dist/format/names.d.ts +22 -0
  30. package/dist/format/names.d.ts.map +1 -0
  31. package/dist/format/position.d.ts +29 -0
  32. package/dist/format/position.d.ts.map +1 -0
  33. package/dist/index.d.ts +17 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +1340 -0
  36. package/dist/index.js.map +32 -0
  37. package/dist/restore/landing.d.ts +26 -0
  38. package/dist/restore/landing.d.ts.map +1 -0
  39. package/dist/restore/options.d.ts +59 -0
  40. package/dist/restore/options.d.ts.map +1 -0
  41. package/dist/restore/restore-collections.d.ts +12 -0
  42. package/dist/restore/restore-collections.d.ts.map +1 -0
  43. package/dist/source/catalog.d.ts +28 -0
  44. package/dist/source/catalog.d.ts.map +1 -0
  45. package/dist/source/changes.d.ts +12 -0
  46. package/dist/source/changes.d.ts.map +1 -0
  47. package/dist/source/collections.d.ts +20 -0
  48. package/dist/source/collections.d.ts.map +1 -0
  49. package/dist/source/events.d.ts +46 -0
  50. package/dist/source/events.d.ts.map +1 -0
  51. package/dist/source/followed.d.ts +13 -0
  52. package/dist/source/followed.d.ts.map +1 -0
  53. package/dist/source/mongo-source.d.ts +24 -0
  54. package/dist/source/mongo-source.d.ts.map +1 -0
  55. package/dist/source/snapshot.d.ts +17 -0
  56. package/dist/source/snapshot.d.ts.map +1 -0
  57. package/dist/target/changes.d.ts +8 -0
  58. package/dist/target/changes.d.ts.map +1 -0
  59. package/dist/target/collection.d.ts +20 -0
  60. package/dist/target/collection.d.ts.map +1 -0
  61. package/dist/target/mongo-target.d.ts +22 -0
  62. package/dist/target/mongo-target.d.ts.map +1 -0
  63. package/docs/README.md +28 -0
  64. package/docs/guide/errors.md +411 -0
  65. package/docs/guide/format.md +179 -0
  66. package/docs/guide/getting-started.md +716 -0
  67. package/docs/guide/incremental.md +323 -0
  68. package/docs/guide/operations.md +237 -0
  69. package/docs/guide/restore.md +684 -0
  70. package/docs/roadmap.md +61 -0
  71. package/docs/troubleshooting.md +1257 -0
  72. package/package.json +70 -5
@@ -0,0 +1,684 @@
1
+ # Restore
2
+
3
+ This page covers bringing a database back from a backup with `mongoTarget`:
4
+ its options, the order things land in, what `replace` does, how changes
5
+ are applied, and what a failure leaves — then bringing back only some
6
+ collections, or some documents, with `restoreCollections`.
7
+
8
+ `mongoBackups(…).restore()` calls one or the other for you — `mongoTarget`
9
+ for a whole restore, `restoreCollections` when `collections`, `as` or
10
+ `documents` is given — so what this page says of them holds for it too.
11
+ Its own options are in [getting started](getting-started.md#restore).
12
+
13
+ ```ts
14
+ import { bindBackup, defineBackup, localRepository } from '@softistx/backup';
15
+ import { mongoTarget } from '@softistx/mongo-backup';
16
+ import { MongoClient } from 'mongodb';
17
+
18
+ const client = await MongoClient.connect(process.env.MONGO_URL as string);
19
+ const backups = bindBackup(defineBackup({ name: 'shop-db' }), {
20
+ repositories: [localRepository({ path: '/mnt/backups' })],
21
+ recipients: [process.env.BACKUP_RECIPIENT as string],
22
+ });
23
+
24
+ const latest = (await backups.list()).backups.at(-1);
25
+ if (!latest) throw new Error('no backup to restore');
26
+
27
+ const restored = await backups.restore(latest.id, mongoTarget({ db: client.db('shop-restored') }), {
28
+ identities: [process.env.BACKUP_IDENTITY as string],
29
+ });
30
+ // { id, repository: 'local', entries: ['metadata/customers', 'documents/customers', …], size }
31
+ ```
32
+
33
+ `restore` itself — `identities`, `from`, `only`, and the checks it makes on
34
+ every object before a byte is decrypted — is `@softistx/backup`'s.
35
+
36
+ ## `mongoTarget`
37
+
38
+ ```ts
39
+ interface MongoTargetOptions {
40
+ db: Db;
41
+ replace?: boolean | undefined;
42
+ tmpDir?: string | undefined;
43
+ }
44
+
45
+ function mongoTarget(options: MongoTargetOptions): RestoreTarget;
46
+ ```
47
+
48
+ | Option | Type | Default | Effect |
49
+ | --- | --- | --- | --- |
50
+ | `db` | `Db` | required | the database to restore into: the one backed up, or another |
51
+ | `replace` | `boolean` | `false` | replace a collection or view that is already there. By default one there is refused with `EXISTS`, and nothing of it is touched |
52
+ | `tmpDir` | `string` | the system's temporary folder | where a `changes/<n>` entry is staged before it is applied. An absolute path |
53
+
54
+ `mongoTarget` checks its options at once, and touches nothing:
55
+
56
+ ```ts
57
+ mongoTarget({ db: client.db('shop'), tmpDir: 'tmp' });
58
+ // TypeError: mongoTarget: tmpDir must be an absolute path
59
+
60
+ mongoTarget({ db: 'shop' as never });
61
+ // TypeError: mongoTarget: db must be a MongoDB Db
62
+ ```
63
+
64
+ **A target serves one restore.** It remembers the metadata entries it has
65
+ read, so that each collection's documents land with their options and
66
+ indexes; a second `restore` through the same object would find the first
67
+ one's. Make a new `mongoTarget` for each `restore`:
68
+
69
+ ```ts
70
+ for (const id of ids) {
71
+ const db = client.db(`drill-${id}`);
72
+ await backups.restore(id, mongoTarget({ db }), { identities }); // a new target each time
73
+ }
74
+ ```
75
+
76
+ ## The order
77
+
78
+ `restore` gives the target the backup's entries in the backup's order,
79
+ one after the other:
80
+
81
+ 1. for each collection, by name, `metadata/<name>` — a **view** is created
82
+ from it there and then — then `documents/<name>`, which lands the
83
+ collection;
84
+ 2. then, for an incremental or a differential, each `changes/<n>` in turn.
85
+
86
+ A collection's documents need its metadata first: an entry that comes
87
+ without it is refused with
88
+ `MongoBackupError (MALFORMED): mongoTarget: a collection’s documents came before its metadata`.
89
+ That only happens when `only` picks one without the other —
90
+ [one collection](#one-collection-with-only).
91
+
92
+ ## Each collection, whole or not at all
93
+
94
+ A collection is never written in place:
95
+
96
+ 1. its name is checked: **one already there is refused with `EXISTS`**
97
+ before a document is read, unless `replace`;
98
+ 2. a staging collection, `nxgt-restore-<uuid>`, is created with the
99
+ collection's options — validator, collation, capped size, … ;
100
+ 3. the documents are inserted into it, in ordered batches of up to 1000
101
+ documents or 8 MiB, with **`bypassDocumentValidation`**;
102
+ 4. its indexes are built;
103
+ 5. only once the entry's stream has ended cleanly — `@softistx/backup` checks
104
+ every byte against what it recorded, and can only say so at the end — it
105
+ is **renamed into place**.
106
+
107
+ Anything that fails on the way — a damaged entry, a write the server
108
+ refuses, an index that cannot be built — drops the staging collection and
109
+ lands nothing of that collection.
110
+
111
+ - **Indexes are built after the documents**, on the staging collection: on
112
+ a large collection that takes a while, and the collection appears only
113
+ once they are done.
114
+ - **A document the validator would refuse comes back as it was.** That is
115
+ a backup's job, but it needs the privilege: the restoring user needs the
116
+ `bypassDocumentValidation` action, which the built-in `restore` and
117
+ `dbAdmin` roles have.
118
+ - **A view** is created from its metadata — `viewOn` and `pipeline` — at
119
+ once; it holds no documents.
120
+
121
+ ## `EXISTS` and `replace`
122
+
123
+ ```ts
124
+ import { MongoBackupError, mongoTarget } from '@softistx/mongo-backup';
125
+
126
+ try {
127
+ await backups.restore(id, mongoTarget({ db: client.db('shop') }), { identities });
128
+ } catch (error) {
129
+ if (!(error instanceof MongoBackupError && error.code === 'EXISTS')) throw error;
130
+ // MongoBackupError (EXISTS): mongoTarget: a collection or view the backup holds is
131
+ // already in the database; restore into another one, or pass replace: true
132
+ }
133
+ ```
134
+
135
+ Without `replace`, a collection or view already in the database is refused,
136
+ and nothing of it is touched. The check runs before the documents are read,
137
+ and again at the rename: a collection created meanwhile is refused there
138
+ too. A collection a `create` change would make is refused the same way, and
139
+ so is the new name of a recorded rename that **replaced nothing at the
140
+ source** — [changes](#changes).
141
+
142
+ With `replace: true`:
143
+
144
+ | What is there | What happens |
145
+ | --- | --- |
146
+ | a collection the backup holds | the restored one is built apart and **replaces it at the rename**: until then the old one is untouched |
147
+ | a view the backup holds | it is dropped, then created again from its metadata |
148
+ | a view where the backup holds a collection | it is dropped once the restored collection is built, just before the rename — the server renames over a collection, never over a view |
149
+ | a collection a `create` change makes | it is dropped, then created with the recorded options |
150
+ | a collection a recorded rename lands on | it is replaced by the renamed one |
151
+ | a collection the backup does not hold | it is left alone — unless a change drops it, or renames over it |
152
+
153
+ ```ts
154
+ await backups.restore(id, mongoTarget({ db: client.db('shop'), replace: true }), { identities });
155
+ ```
156
+
157
+ ## Changes
158
+
159
+ A `changes/<n>` entry is not applied as it streams in. It is written to
160
+ `<tmpDir>/nxgt-mongo-changes-XXXXXX/changes.bson` — a folder of its own,
161
+ made with `mkdtemp` and readable only by the user that runs the restore,
162
+ since the changes hold whole documents in the clear — until its stream has
163
+ ended cleanly; then it is applied, in order, and the folder removed. A
164
+ change applied cannot be taken back, so none is applied before
165
+ `@softistx/backup` has checked the whole entry.
166
+
167
+ - **Document changes** to one collection go as ordered bulk writes of up
168
+ to 1000, with `bypassDocumentValidation`. An insert or a replace is a
169
+ `replaceOne` with `upsert`; an update cuts arrays first, then sets and
170
+ unsets fields; a delete is a `deleteOne`.
171
+ - **Collection changes** apply between them, in their place:
172
+ `createCollection`, `createIndexes`, `dropIndex`, `collMod`,
173
+ `renameCollection`, `dropCollection`, `dropDatabase`. A drop, an index
174
+ drop, a `collMod` or a rename of something already gone is not an error.
175
+ - **A rename records whether it replaced a collection at the source**
176
+ (`dropTarget`). One that did replaces the collection of the new name
177
+ here too. One that did not refuses a collection already there under the
178
+ new name with `EXISTS`, and touches nothing of it — unless `replace: true`,
179
+ which replaces it:
180
+
181
+ ```ts
182
+ // at the source: orders renamed to orders-2026, where no orders-2026 was
183
+ await backups.restore(next.id, mongoTarget({ db: client.db('shop-restored') }), { identities });
184
+ // MongoBackupError (EXISTS) if shop-restored already holds an orders-2026
185
+ ```
186
+
187
+ - **`dropDatabase` drops the database restored into**, whatever else it
188
+ holds — [incremental](incremental.md#a-dropped-database).
189
+ - **`tmpDir` needs room for the largest changes entry**, decrypted and
190
+ decompressed — on top of the room `@softistx/backup`'s own `tmpDir` needs for
191
+ each object. `tmpDir: '/var/tmp'` when `/tmp` is a small tmpfs.
192
+
193
+ What each recorded change is is on the
194
+ [incremental](incremental.md#what-the-change-stream-records) page.
195
+
196
+ ## One collection with `only`
197
+
198
+ From a **full** backup, a collection's two entries restore it alone, as the
199
+ backup read it:
200
+
201
+ ```ts
202
+ await backups.restore(
203
+ full.id,
204
+ mongoTarget({ db: client.db('shop-restored') }),
205
+ { identities, only: ['metadata/orders', 'documents/orders'] },
206
+ );
207
+ ```
208
+
209
+ From an incremental, the same two entries give the collection as the
210
+ **full** backup read it, without the changes since. A `changes/<n>` entry
211
+ holds the changes to every collection the chain follows, so picking one
212
+ applies them all — to collections that are not there, too, which an insert
213
+ then creates without their options. To get one collection as an
214
+ incremental left it, use `restoreCollections`, which replays the whole
215
+ chain apart and takes the collection from there —
216
+ [restoring part of a backup](#restoring-part-of-a-backup).
217
+
218
+ ## Into another database
219
+
220
+ The backup does not record the database's name: the same backup restores
221
+ into the database it came from, or any other, on the same server or
222
+ another one. Restoring into a fresh database, then pointing the
223
+ application at it, is the safest way back:
224
+
225
+ ```ts
226
+ // restore.ts — `bun run restore.ts <backup id> <database>`
227
+ import { bindBackup, defineBackup, localRepository } from '@softistx/backup';
228
+ import { mongoTarget } from '@softistx/mongo-backup';
229
+ import { MongoClient } from 'mongodb';
230
+
231
+ const [id, database] = Bun.argv.slice(2);
232
+ if (!id || !database) throw new TypeError('usage: bun run restore.ts <backup id> <database>');
233
+
234
+ const client = await MongoClient.connect(process.env.MONGO_URL as string);
235
+ try {
236
+ const backups = bindBackup(defineBackup({ name: 'shop-db' }), {
237
+ repositories: [localRepository({ path: '/mnt/backups' })],
238
+ recipients: [process.env.BACKUP_RECIPIENT as string],
239
+ tmpDir: '/var/tmp',
240
+ });
241
+ const db = client.db(database);
242
+ const there = await db.listCollections({}, { nameOnly: true }).toArray();
243
+ if (there.length > 0) throw new Error('restore into an empty database');
244
+
245
+ const restored = await backups.restore(id, mongoTarget({ db, tmpDir: '/var/tmp' }), {
246
+ identities: [(await Bun.file('/etc/backup/identity.txt').text()).trim()],
247
+ });
248
+ console.log(`restored ${restored.entries.length} entries into ${database}`);
249
+ } finally {
250
+ await client.close();
251
+ }
252
+ ```
253
+
254
+ ## What a failure leaves
255
+
256
+ A restore stops at its first error, and is whole **per collection**, not
257
+ per backup:
258
+
259
+ - **the collections already restored stay**, and so do the views already
260
+ created;
261
+ - **the collection being restored lands nothing**: its staging collection
262
+ is dropped;
263
+ - **changes already applied stay applied**: a change entry that fails
264
+ halfway — a write the server refuses — leaves the ones before it.
265
+
266
+ A process killed mid-restore cannot clean up: it can leave a staging
267
+ collection behind, and a staged changes folder in `tmpDir`. Drop them by
268
+ name once nothing runs:
269
+
270
+ ```ts
271
+ const db = client.db('shop-restored');
272
+ for (const { name } of await db.listCollections({}, { nameOnly: true }).toArray()) {
273
+ if (name.startsWith('nxgt-restore-')) await db.dropCollection(name);
274
+ }
275
+ ```
276
+
277
+ ```sh
278
+ rm -rf /var/tmp/nxgt-mongo-changes-*
279
+ ```
280
+
281
+ Then drop the database and restore again — or restore into another one.
282
+
283
+ ## Restoring into the database you back up
284
+
285
+ A restore lands each collection under `nxgt-restore-<uuid>` and renames it
286
+ into place. Into the database a `mongoSource` backs up — with
287
+ `replace: true`, say — those renames reach its change stream as renames
288
+ into the collections the chain follows, and the next incremental fails
289
+ `UNSUPPORTED` ([renames](incremental.md#renames)). Make a full backup right
290
+ after such a restore:
291
+
292
+ ```ts
293
+ await backups.restore(id, mongoTarget({ db: client.db('shop'), replace: true }), { identities });
294
+ await backups.create(mongoSource({ db: client.db('shop') })); // the chain starts again here
295
+ ```
296
+
297
+ ## Restoring part of a backup
298
+
299
+ `restoreCollections` brings back some collections and views — whole, or
300
+ only the documents a query takes — from a backup, chain included, under
301
+ their own names or others, into a database that already holds other data.
302
+
303
+ ```ts
304
+ import { bindBackup, defineBackup, localRepository } from '@softistx/backup';
305
+ import { restoreCollections } from '@softistx/mongo-backup';
306
+ import { MongoClient } from 'mongodb';
307
+
308
+ const client = await MongoClient.connect(process.env.MONGO_URL as string);
309
+ const backups = bindBackup(defineBackup({ name: 'shop-db' }), {
310
+ repositories: [localRepository({ path: '/mnt/backups' })],
311
+ recipients: [process.env.BACKUP_RECIPIENT as string],
312
+ });
313
+ const identities = [process.env.BACKUP_IDENTITY as string];
314
+
315
+ const done = await restoreCollections(backups, id, {
316
+ identities,
317
+ db: client.db('shop'),
318
+ collections: ['orders'],
319
+ as: { orders: 'orders-before' },
320
+ });
321
+ // done.collections: [{ name: 'orders', as: 'orders-before' }]
322
+ ```
323
+
324
+ ### How it runs
325
+
326
+ 1. It checks its options. A wrong one rejects with a `TypeError` before
327
+ anything is read — but for what only the backup's names can tell,
328
+ below — and a `scratch` that is not empty with `EXISTS`.
329
+ 2. It **rebuilds the whole backup**, chain included, in a scratch
330
+ database, through `mongoTarget` — every entry `restore` would land,
331
+ every change applied.
332
+ 3. It takes what was asked for from the scratch database into `db`.
333
+ 4. It **drops the scratch database**, whether that worked or not.
334
+
335
+ **The cost is the whole backup's**, even for one document: every
336
+ collection is downloaded, decrypted, written to the scratch database and
337
+ indexed, and every change applied, before one byte reaches `db`. Plan for
338
+ the time, and for the room on the server, of a full restore.
339
+
340
+ The rebuild is an ordinary `restore`: a `BackupError` from `@softistx/backup`
341
+ or a driver error passes through as it is; a refusal of the `mongoTarget`
342
+ behind it is told as `restoreCollections: …`, same class and code, the
343
+ `mongoTarget:` original as its `cause` ([errors](errors.md)). The scratch
344
+ database is dropped all the same.
345
+
346
+ ### Its signature
347
+
348
+ ```ts
349
+ function restoreCollections(
350
+ backups: Restorer,
351
+ id: string,
352
+ options: RestoreCollectionsOptions,
353
+ ): Promise<RestoredCollections>;
354
+
355
+ /** What it needs of a bound backup: its `restore`. */
356
+ interface Restorer {
357
+ restore(id: string, target: RestoreTarget, options: RestoreOptions): Promise<Restored>;
358
+ }
359
+
360
+ /** Some documents of each collection, merged into what is there. */
361
+ interface DocumentSelection {
362
+ filter: Document;
363
+ existing: 'replace' | 'keep';
364
+ }
365
+
366
+ type RestoreCollectionsOptions =
367
+ | (Common & { documents?: undefined; replace?: boolean | undefined }) // whole
368
+ | (Common & { documents: DocumentSelection; replace?: never }); // documents
369
+
370
+ interface RestoredCollections extends Restored {
371
+ collections: { name: string; as: string; documents?: number }[];
372
+ }
373
+ ```
374
+
375
+ `backups` is anything with a `restore` of that shape — what `bindBackup`
376
+ returns, or a fake in a test. `Common` stands for the options both modes
377
+ share, below; it is not exported. `Restorer`, `DocumentSelection`,
378
+ `RestoreCollectionsOptions` and `RestoredCollections` are.
379
+
380
+ ### Options
381
+
382
+ | Option | Type | Default | Effect |
383
+ | --- | --- | --- | --- |
384
+ | `identities` | `readonly string[]` | required | the age secret keys that open the backup, as `restore` takes them |
385
+ | `from` | `string` | the first repository | the repository to read from, by name |
386
+ | `db` | `Db` | required | the database to restore into |
387
+ | `collections` | `readonly string[] \| ((name: string) => boolean)` | every collection and view but `system.*` | what to restore, by its name **at the backup's time** |
388
+ | `as` | `Record<string, string> \| ((name: string) => string)` | each keeps its own name | the name each one lands under |
389
+ | `scratch` | `Db` | a fresh `nxgt-restore-<uuid>` on `db.client` | where the backup is rebuilt; dropped afterwards |
390
+ | `tmpDir` | `string` | the system's temporary folder | where a `changes/<n>` entry is staged during the rebuild — [`mongoTarget`](#mongotarget) |
391
+ | `replace` | `boolean` | `false` | whole mode only: replace a collection or view already there |
392
+ | `documents` | `DocumentSelection` | none: whole mode | restore only the documents `filter` takes, merged into what is there |
393
+
394
+ ### `collections`: names at the backup's time
395
+
396
+ The names are those the collections had **when the backup was made**,
397
+ after the chain has replayed every rename up to it — not those the source
398
+ database has today. A collection renamed from `a` to `orders` before an
399
+ incremental is `orders` in that incremental, and `a` in the full backup
400
+ before it.
401
+
402
+ A **list** must name what the backup holds: a name it lacks rejects the
403
+ call with `NOT_FOUND`, after the rebuild and before anything reaches `db`.
404
+ A typo would otherwise restore nothing, and say nothing.
405
+
406
+ ```ts
407
+ await restoreCollections(backups, id, { identities, db, collections: ['a'] });
408
+ // MongoBackupError (NOT_FOUND): restoreCollections: a collection named in collections is not in the backup
409
+ ```
410
+
411
+ A **function** is asked about each name, and picks what it returns `true`
412
+ for; it never fails for a name it does not see. Either way, `system.*` is
413
+ never restored, and a view is picked like a collection.
414
+
415
+ ### `as`: the name each one lands under
416
+
417
+ A **record** renames those it lists; the others keep their own name. A
418
+ **function** is asked for every name `collections` picked, views
419
+ included:
420
+
421
+ ```ts
422
+ await restoreCollections(backups, id, {
423
+ identities,
424
+ db: client.db('shop'),
425
+ collections: ['orders', 'orders-open'], // orders-open is a view on orders
426
+ as: (name) => `${name}-restored`,
427
+ });
428
+ // orders → orders-restored, and the view orders-open-restored reads orders-restored
429
+ ```
430
+
431
+ A name it gives must be one MongoDB takes. Each of these rejects with a
432
+ `TypeError` before anything reaches `db`. A map is checked before the
433
+ backup is read, for its names and for two of its keys given one name; a
434
+ clash with a collection that keeps its own name, a key that names nothing
435
+ restored, and anything a function gives, once the rebuild has given the
436
+ names:
437
+
438
+ | `as` gives | Message |
439
+ | --- | --- |
440
+ | an empty name, a name holding `$` or a NUL, a name starting with `system.`, or not a string | `TypeError: restoreCollections: as must give a collection name` |
441
+ | the same name to two collections or views | `TypeError: restoreCollections: as gives two collections one name` |
442
+ | a map key that names no collection or view restored — a typo, or a view when `documents` is given | `TypeError: restoreCollections: as names a collection not restored` |
443
+
444
+ ### The scratch database
445
+
446
+ By default the backup is rebuilt in a fresh database,
447
+ `nxgt-restore-<uuid>`, on the same client as `db`. **The user that runs
448
+ the restore needs the right to create that database**, write to it and
449
+ drop it — and, in whole mode, to rename a collection from it into `db`.
450
+
451
+ `scratch` names another one — on a server where that user may only use
452
+ certain databases, say:
453
+
454
+ ```ts
455
+ await restoreCollections(backups, id, {
456
+ identities,
457
+ db: client.db('shop'),
458
+ scratch: client.db('restore-scratch'), // must be empty; it is dropped afterwards
459
+ collections: ['orders'],
460
+ as: { orders: 'orders-before' },
461
+ });
462
+ ```
463
+
464
+ - It must be **empty** — `system.*` aside — since it is dropped
465
+ afterwards. One that holds a collection is refused before anything is
466
+ read, and left as it is:
467
+ `MongoBackupError (EXISTS): restoreCollections: the scratch database holds collections; give an empty one`.
468
+ - It must be **another database than `db`**:
469
+ `TypeError: restoreCollections: scratch must be another database`.
470
+ - It must be **on `db`'s client**: a collection moves from it with a
471
+ rename across databases, and documents with a `$merge`, and both name
472
+ `db` on the server they run on — from another client, documents would
473
+ land in a database of that name on the other server:
474
+ `TypeError: restoreCollections: scratch must be on db's client`.
475
+
476
+ A process killed mid-restore cannot drop it, and a drop that fails — a
477
+ lost connection — leaves it without failing the restore: drop any
478
+ database named `nxgt-restore-…` once nothing runs.
479
+
480
+ ```ts
481
+ const { databases } = await client.db('admin').admin().listDatabases();
482
+ for (const { name } of databases) {
483
+ if (name.startsWith('nxgt-restore-')) await client.db(name).dropDatabase();
484
+ }
485
+ ```
486
+
487
+ ### Whole collections
488
+
489
+ Without `documents`, each collection and view lands whole, as it was at
490
+ the backup's time:
491
+
492
+ - **A collection is moved** from the scratch database into `db` with a
493
+ `renameCollection` across databases, so it keeps its options —
494
+ validator, collation, capped size — and its indexes.
495
+ - **A view is made again** in `db`, after the collections. When the
496
+ collection it reads is restored too, it reads that collection's **new
497
+ name**; otherwise it reads the name it had.
498
+ - **A name already taken is refused** with `EXISTS`, every one checked
499
+ **before anything moves**. A collection created under one of those names
500
+ in the meantime is refused by the server at its rename, with the same
501
+ `EXISTS`, rather than replaced.
502
+ - **With `replace: true`**, what stands under the name is replaced — a
503
+ view too: the server renames over a collection, never over a view, so a
504
+ view there is dropped first.
505
+
506
+ ```ts
507
+ import { MongoBackupError, restoreCollections } from '@softistx/mongo-backup';
508
+
509
+ try {
510
+ await restoreCollections(backups, id, { identities, db: client.db('shop'), collections: ['orders'] });
511
+ } catch (error) {
512
+ if (!(error instanceof MongoBackupError && error.code === 'EXISTS')) throw error;
513
+ // MongoBackupError (EXISTS): restoreCollections: a collection or view to restore is
514
+ // already in the database; restore it under another name, or pass replace: true
515
+ }
516
+ ```
517
+
518
+ - **`replace: true` replaces instead**: a collection there is dropped by
519
+ the rename itself (`dropTarget`), a view there is dropped and made again.
520
+
521
+ ```ts
522
+ await restoreCollections(backups, id, {
523
+ identities,
524
+ db: client.db('shop'),
525
+ collections: ['orders'],
526
+ replace: true, // orders as it was at the backup, in place of today's
527
+ });
528
+ ```
529
+
530
+ The result says what landed where, in name order:
531
+
532
+ ```ts
533
+ // { id, repository, entries, size, collections: [
534
+ // { name: 'ones', as: 'ones' },
535
+ // { name: 'orders', as: 'orders-then' },
536
+ // ] }
537
+ ```
538
+
539
+ ### Some documents
540
+
541
+ `documents` takes, from each collection picked, the documents `filter`
542
+ matches — any query `find` takes: `{ _id: id }`, `{ _id: { $in: ids } }`,
543
+ `{ customer: 'c-42' }` — and merges them into the collection `db` has
544
+ under its `as` name, matched on `_id` (a `$merge`). Documents there that
545
+ the filter does not reach are left alone, and so are those the backup no
546
+ longer holds: nothing is deleted.
547
+
548
+ ```ts
549
+ const done = await restoreCollections(backups, id, {
550
+ identities,
551
+ db: client.db('shop'),
552
+ collections: ['customers'],
553
+ documents: { filter: { _id: { $in: [1, 2] } }, existing: 'keep' },
554
+ });
555
+ // done.collections: [{ name: 'customers', as: 'customers', documents: 2 }]
556
+ ```
557
+
558
+ `existing` is **required**: it says what a document already in `db` with
559
+ the same `_id` becomes.
560
+
561
+ | `existing` | A document there with the same `_id` | One not there |
562
+ | --- | --- | --- |
563
+ | `'replace'` | becomes the backup's | is inserted |
564
+ | `'keep'` | stays as it is | is inserted |
565
+
566
+ - **A collection `db` lacks is made first**, with the backup's options and
567
+ indexes, then the documents merged into it.
568
+ - **Views are left out**: they hold no documents, and do not appear in
569
+ the result. An `as` map naming one is refused like any name not
570
+ restored.
571
+ - **`documents` in the result** is the number of documents the filter
572
+ matched **in the backup**, not the number written: with `'keep'`, a
573
+ document already there counts though it was not touched.
574
+ - **Documents are written with `bypassDocumentValidation`**, as a whole
575
+ restore writes them.
576
+ - **`replace` has no meaning here**, and is refused: by the types, and at
577
+ runtime with
578
+ `TypeError: restoreCollections: replace is for whole collections; documents says what happens to those there`.
579
+
580
+ ```ts
581
+ restoreCollections(backups, id, {
582
+ identities,
583
+ db,
584
+ documents: { filter: {}, existing: 'keep' },
585
+ replace: true, // type error: replace is for whole collections
586
+ });
587
+ ```
588
+
589
+ A `documents` that is not `{ filter, existing }` — a `filter` that is an
590
+ array or a BSON value, an `existing` other than the two — is
591
+ `TypeError: restoreCollections: documents must be { filter, existing: 'replace' | 'keep' }`.
592
+
593
+ ### Into the database you back up
594
+
595
+ Documents merged into the database a `mongoSource` backs up are recorded
596
+ by the next incremental like any other write. A whole collection moved
597
+ there is too — **unless the chain follows a filter that does not take
598
+ `tmpXXXXX.renameCollection`**, as a list of names never does: the server
599
+ moves a collection across databases through that temporary one, so the next
600
+ incremental refuses the rename into it with `UNSUPPORTED` —
601
+ `mongoSource: a collection was renamed into those backed up, with
602
+ documents an incremental backup never read; make a full backup`. Make a
603
+ full backup after such a restore, or let the chain follow every
604
+ collection — measured on mongod 8.2.
605
+
606
+ ### Bringing back one deleted document
607
+
608
+ A function an admin route or a job calls to restore one customer as the
609
+ last backup had them, without touching anything else:
610
+
611
+ ```ts
612
+ import { bindBackup, defineBackup, localRepository } from '@softistx/backup';
613
+ import { MongoBackupError, restoreCollections } from '@softistx/mongo-backup';
614
+ import { MongoClient } from 'mongodb';
615
+
616
+ const client = await MongoClient.connect(process.env.MONGO_URL as string);
617
+ const backups = bindBackup(defineBackup({ name: 'shop-db' }), {
618
+ repositories: [localRepository({ path: '/mnt/backups' })],
619
+ recipients: [process.env.BACKUP_RECIPIENT as string],
620
+ });
621
+ const identities = [process.env.BACKUP_IDENTITY as string];
622
+
623
+ /** The customer as the last backup had them, put back unless they are there. Whether the backup held them. */
624
+ export async function restoreCustomer(customerId: string): Promise<boolean> {
625
+ const latest = (await backups.list()).backups.at(-1);
626
+ if (!latest) return false;
627
+ try {
628
+ const { collections } = await restoreCollections(backups, latest.id, {
629
+ identities,
630
+ db: client.db('shop'),
631
+ collections: ['customers'],
632
+ documents: { filter: { _id: customerId }, existing: 'keep' },
633
+ tmpDir: '/var/tmp',
634
+ });
635
+ return (collections[0]?.documents ?? 0) > 0;
636
+ } catch (error) {
637
+ if (error instanceof MongoBackupError && error.code === 'NOT_FOUND') return false; // no customers then
638
+ throw error;
639
+ }
640
+ }
641
+ ```
642
+
643
+ It takes as long as a full restore: call it from a job queue rather than
644
+ inside a request when the backup is large.
645
+
646
+ ### What a failure leaves
647
+
648
+ The scratch database is always dropped — except when a given `scratch`
649
+ is refused for not being empty, which leaves it as it was. In `db`:
650
+
651
+ - a `TypeError` from the options, `NOT_FOUND`, a `TypeError` from `as`, a
652
+ failed rebuild and, in whole mode without `replace`, the `EXISTS` check
653
+ all come **before anything reaches `db`**: it is untouched;
654
+ - a failure while landing — a rename the server refuses, a lost
655
+ connection — keeps what landed before it: the collections already
656
+ moved, or the documents already merged. In whole mode the views come
657
+ last, so a failure among the collections leaves none of them made.
658
+
659
+ ### Limits
660
+
661
+ - **A sharded collection cannot be restored whole**: MongoDB does not
662
+ rename a sharded collection across databases. A sharded cluster is
663
+ untested anyway — [install](../../README.md#install).
664
+ - **A view's `$lookup` is not renamed.** A view made again reads its
665
+ restored collection's new name, but a `$lookup`, `$graphLookup` or
666
+ `$unionWith` inside its pipeline still names the collection it named.
667
+ - **The whole backup is rebuilt** for any part of it — [how it runs](#how-it-runs).
668
+
669
+ ## Errors
670
+
671
+ | Thrown | When |
672
+ | --- | --- |
673
+ | `TypeError: mongoTarget: db must be a MongoDB Db` | `db` is not a driver `Db` |
674
+ | `TypeError: mongoTarget: tmpDir must be an absolute path` | a relative `tmpDir` |
675
+ | `MongoBackupError` `EXISTS` | a collection or view is already there, or a recorded rename that replaced nothing at the source lands on one, without `replace` |
676
+ | `MongoBackupError` `MALFORMED` | an entry, a metadata record or a change this version did not write; documents before their metadata |
677
+ | `TypeError: restoreCollections: …` | `restoreCollections` given options it cannot use — [the messages](errors.md#the-bare-typeerrors) |
678
+ | `MongoBackupError` `EXISTS`, from `restoreCollections` | a collection or view to restore is already in `db`, without `replace`; or the `scratch` given holds collections — [whole collections](#whole-collections) |
679
+ | `MongoBackupError` `NOT_FOUND` | a name in `restoreCollections`' `collections` list is not in the backup — [`collections`](#collections-names-at-the-backups-time) |
680
+ | `BackupError` `INTEGRITY`, `DECRYPT`, … | the backup itself — `@softistx/backup`'s, passed through |
681
+ | a driver error — `MongoServerError: E11000 duplicate key error …`, a refused write, a lost connection | passed through unchanged; its message may quote collection names and values |
682
+
683
+ Every message is in [errors](errors.md) and in
684
+ [troubleshooting](../troubleshooting.md).