@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,716 @@
1
+ # Getting started
2
+
3
+ This page takes you from a MongoDB database to a first backup, a first
4
+ restore and a first drill with `mongoBackups`, with every option and what
5
+ each method returns and throws. The lower-level `mongoSource` it is built
6
+ on comes after, from [Lower level](#lower-level).
7
+
8
+ ```sh
9
+ bunx nxgt-mongo-backup keygen /etc/backup/shop.key
10
+ ```
11
+
12
+ ```ts
13
+ import { mongoBackups } from '@softistx/mongo-backup';
14
+ import { MongoClient } from 'mongodb';
15
+
16
+ const client = await MongoClient.connect(process.env.MONGO_URL as string); // a replica set
17
+ const backups = mongoBackups({
18
+ db: client.db('shop'),
19
+ repository: '/mnt/backups',
20
+ keyFile: '/etc/backup/shop.key',
21
+ });
22
+
23
+ const report = await backups.run();
24
+ // { id: '20261004T221500123Z-9f3a61c0', kind: 'full', fellBack: false, entries: 12, storedSize: 48213, chain: 1, removed: [] }
25
+
26
+ await backups.restore({ into: client.db('shop-restored') });
27
+ // { id: '20261004T221500123Z-9f3a61c0', repository: 'local', entries: ['metadata/customers', …], size: 912345 }
28
+
29
+ await backups.drill();
30
+ // { id: '20261004T221500123Z-9f3a61c0', collections: [{ name: 'customers', documents: 1204 }, …] }
31
+ ```
32
+
33
+ ## What you need
34
+
35
+ - **Bun**, as `@softistx/backup` needs — the `nxgt-mongo-backup` bin runs on it
36
+ too.
37
+ - **A replica set.** A full backup is a snapshot read, and an incremental
38
+ reads the change stream: a standalone `mongod` serves neither. A
39
+ single-node replica set is enough — `mongod --replSet rs0`, then
40
+ `rs.initiate()` once. A sharded cluster serves both too, but is untested:
41
+ the specs run against a replica set, and a restore does not shard a
42
+ collection.
43
+ - **A `Db` from the `mongodb` driver**, 7.x. Not a database name, and not a
44
+ model: the backup takes the whole database.
45
+
46
+ ```sh
47
+ bun add @softistx/mongo-backup @softistx/backup mongodb
48
+ ```
49
+
50
+ ## The key file
51
+
52
+ One file holds every secret a backup job needs: an **age identity**, which
53
+ every backup is encrypted for and which an incremental reads its parent
54
+ with, and an **Ed25519 signing key**, which signs every manifest. Write it
55
+ once, with the bin or from code:
56
+
57
+ ```sh
58
+ bunx nxgt-mongo-backup keygen /etc/backup/shop.key
59
+ # key file written: /etc/backup/shop.key
60
+ # recipient: age1…
61
+ # keep a copy of it away from the backups
62
+ ```
63
+
64
+ ```ts
65
+ import { generateKeyFile } from '@softistx/mongo-backup';
66
+
67
+ const { recipient } = await generateKeyFile('/etc/backup/shop.key');
68
+ // recipient: 'age1…' — the public half, safe to print
69
+ ```
70
+
71
+ - **Mode `0600`**, readable by its owner alone, and synced to disk with
72
+ its folder before the promise resolves.
73
+ - **Never overwritten**: a file already at that path rejects with Node's
74
+ `EEXIST`, and leaves it as it was — the backups made with it would be
75
+ lost with it. A write that fails halfway removes the file it created, so
76
+ trying again is not refused with `EEXIST`. The bin prints `<path> is already there: it is never
77
+ overwritten` and exits 1.
78
+ - **The bin prints only the recipient**, never a secret. A relative path is
79
+ resolved against the current folder. `nxgt-mongo-backup --help` prints
80
+ the usage and exits 0; a wrong command prints it and exits 2; any other
81
+ failure prints `keygen failed: <message>` and exits 1.
82
+ - **Keep a copy away from the backups** — a password manager, a safe.
83
+ Without the identity, the backups are noise.
84
+
85
+ `readKeyFile` reads it back — `mongoBackups` calls it on first use:
86
+
87
+ ```ts
88
+ import { readKeyFile } from '@softistx/mongo-backup';
89
+
90
+ const keys = await readKeyFile('/etc/backup/shop.key');
91
+ // { identity: 'AGE-SECRET-KEY-1…', recipient: 'age1…', signingKey: '-----BEGIN PRIVATE KEY-----…', publicKey: '-----BEGIN PUBLIC KEY-----…' }
92
+ ```
93
+
94
+ ```ts
95
+ interface BackupKeys {
96
+ identity: string; // the age secret key: reads backups
97
+ recipient: string; // its public half, age1…: every backup is encrypted to it
98
+ signingKey: string; // the Ed25519 private key, PEM: signs every manifest
99
+ publicKey: string; // its public half, PEM: a manifest must be signed by it to be read
100
+ }
101
+
102
+ function generateKeyFile(path: string): Promise<{ recipient: string }>;
103
+ function readKeyFile(path: string, where?: string): Promise<BackupKeys>; // where: 'readKeyFile' by default
104
+ ```
105
+
106
+ It opens the file once, and checks its mode and reads it through that one
107
+ descriptor. It refuses, with `MongoBackupError` code `KEY_FILE` — the
108
+ messages start with `readKeyFile:` when you call it, and with
109
+ `mongoBackups on "<name>":` — the backup's name — when `mongoBackups` does:
110
+
111
+ | Message | When |
112
+ | --- | --- |
113
+ | `readKeyFile: there is no key file there; write one with nxgt-mongo-backup keygen` | nothing at that path; the `ENOENT` is its `cause`. Any other failure to open it — `EACCES`, `ENOTDIR` — is the system's error, as it is |
114
+ | `readKeyFile: others than its owner can read or write the key file; chmod 600 it` | its group or others have any right on it — as ssh refuses such a key |
115
+ | `readKeyFile: the key file is not one keygen wrote` | it lacks the identity or the signing key, or either does not parse — an identity with a bad checksum, or a private key that is not Ed25519 (an RSA one, say), among them. No `cause`: the parsers' own errors quote the key |
116
+
117
+ No message quotes the file's content. The public key and the recipient are
118
+ derived from the secrets, so the file holds only those two.
119
+
120
+ ## `mongoBackups`
121
+
122
+ ```ts
123
+ interface MongoBackupsOptions {
124
+ db: Db;
125
+ repository: string | Repository | readonly [Repository, ...Repository[]];
126
+ keyFile: string;
127
+ name?: string | undefined;
128
+ collections?: CollectionFilter | undefined;
129
+ fullEvery?: number | undefined;
130
+ keep?: KeepPolicy | false | undefined;
131
+ tmpDir?: string | undefined;
132
+ }
133
+
134
+ function mongoBackups(options: MongoBackupsOptions): MongoBackups;
135
+ ```
136
+
137
+ | Option | Type | Default | Effect |
138
+ | --- | --- | --- | --- |
139
+ | `db` | `Db` | required | the database backed up; its client must reach a replica set or a sharded cluster. A drill's database is made on the same client |
140
+ | `repository` | `string \| Repository \| [Repository, …]` | required | an absolute folder — a `localRepository` — or `@softistx/backup` repositories, `s3Repository` among them; every backup is written to each |
141
+ | `keyFile` | `string` | required | the absolute path of the file `keygen` wrote |
142
+ | `name` | `string` | `db.databaseName` | the backup's name in the repository: lowercase letters, digits, `.`, `_` and `-` |
143
+ | `collections` | `readonly string[] \| ((name: string) => boolean)` | every collection and view but `system.*` | which to back up — [choosing collections](#choosing-collections) |
144
+ | `fullEvery` | `number` (ms) | `DEFAULT_FULL_EVERY`, a week | how old the newest full backup may grow before `run` makes another; an hour at least |
145
+ | `keep` | `KeepPolicy \| false` | `DEFAULT_KEEP` | what `run` keeps after each backup; `false` keeps everything |
146
+ | `tmpDir` | `string` | the system's temporary folder | where objects and changes are staged; absolute |
147
+
148
+ ```ts
149
+ import { DEFAULT_FULL_EVERY, DEFAULT_KEEP } from '@softistx/mongo-backup';
150
+
151
+ DEFAULT_FULL_EVERY; // 604_800_000 — 7 days
152
+ DEFAULT_KEEP; // { last: 24, daily: 14, weekly: 8, monthly: 12 }
153
+ ```
154
+
155
+ `DEFAULT_KEEP` keeps a day hour by hour, two weeks day by day, two months
156
+ week by week and a year month by month. A rotation never breaks a chain: a
157
+ kept incremental keeps what it builds on —
158
+ [`@softistx/backup`'s rotation](https://github.com/softistx/nxgt-data/blob/develop/packages/backup/docs/guide/rotation.md).
159
+
160
+ **`mongoBackups` checks its options at once**, and throws a bare
161
+ `TypeError`:
162
+
163
+ ```ts
164
+ import { mongoBackups } from '@softistx/mongo-backup';
165
+
166
+ mongoBackups({ db: client.db('shop'), repository: 'backups', keyFile: '/etc/backup/shop.key' });
167
+ // TypeError: mongoBackups: repository must be an absolute folder, or repositories
168
+ ```
169
+
170
+ | Message | When |
171
+ | --- | --- |
172
+ | `mongoBackups: db must be a MongoDB Db` | `db` is missing, or is not a driver `Db` |
173
+ | `mongoBackups: keyFile must be an absolute path` | `keyFile` is missing or relative |
174
+ | `mongoBackups: repository must be an absolute folder, or repositories` | `repository` is a relative path |
175
+ | `mongoBackups: keep must be false, or name rules each a whole number, 1 or more` | `keep` names no rule (`{}`), or a rule — `last`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, `within`, `maxTotalSize` — that is not a whole number of 1 or more. Checked here, not after a backup is stored |
176
+ | `mongoBackups: fullEvery must be a whole number of milliseconds, an hour or more` | `fullEvery` under 3 600 000, or not a whole number |
177
+ | `mongoBackups: repository must list repositories, each under a name of its own` | `repository` is an empty list, or two repositories in it have the same name |
178
+ | `mongoBackups: tmpDir must be an absolute path` | a relative `tmpDir` |
179
+ | `mongoBackups: name must be 1 to 100 characters, lowercase letters, digits, ".", "_" and "-", starting with a letter or a digit, without ".partial-"` | `name` is given, and is not a backup name; `defineBackup`'s `TypeError` is its `cause` |
180
+ | `mongoBackups: the database's name cannot name a backup; give name: 1 to 100 characters, lowercase letters, digits, ".", "_" and "-", starting with a letter or a digit, without ".partial-"` | no `name`, and the database's name is not a backup name — `client.db('MyShop')`: pass `name: 'myshop'`. `defineBackup`'s `TypeError` is its `cause` |
181
+
182
+ **A database whose name is not a backup name needs `name`.** A backup
183
+ name is lowercase: `client.db('MyShop')` throws the last of these until
184
+ you pass one.
185
+
186
+ ```ts
187
+ mongoBackups({ db: client.db('MyShop'), name: 'myshop', repository: '/mnt/backups', keyFile: '/etc/backup/shop.key' });
188
+ ```
189
+
190
+ **The key file is read on first use**, not here: `mongoBackups` touches
191
+ neither the file nor the database. The first `run`, `restore`, `drill`,
192
+ `list` or `binding` reads it, and keeps the keys for the next. A read that
193
+ fails is tried again on the next call, so a key file put in place later is
194
+ picked up without a restart.
195
+
196
+ ### The repository
197
+
198
+ A string is a local folder. Anything else is `@softistx/backup`'s — an S3
199
+ bucket, or several repositories at once, each written by every backup:
200
+
201
+ ```ts
202
+ import { localRepository, s3Repository } from '@softistx/backup';
203
+ import { mongoBackups } from '@softistx/mongo-backup';
204
+ import { S3Client } from 'bun';
205
+
206
+ const backups = mongoBackups({
207
+ db: client.db('shop'),
208
+ repository: [
209
+ localRepository({ path: '/mnt/backups' }),
210
+ s3Repository({ client: new S3Client({ bucket: 'shop-backups' }), prefix: 'mongo' }),
211
+ ],
212
+ keyFile: '/etc/backup/shop.key',
213
+ });
214
+ ```
215
+
216
+ Reads — `list`, `restore`, `drill` — use the first.
217
+
218
+ ## What it returns
219
+
220
+ ```ts
221
+ interface MongoBackups {
222
+ run(now?: Date): Promise<RunReport>;
223
+ restore(options: RestoreAtOptions): Promise<RestoreReport>;
224
+ drill(): Promise<DrillReport>;
225
+ list(): Promise<BackupInfo[]>;
226
+ binding(): Promise<{ backups: BoundBackup; keys: BackupKeys }>;
227
+ }
228
+ ```
229
+
230
+ ### `run`
231
+
232
+ One scheduled run:
233
+
234
+ 1. **a full backup when none is younger than `fullEvery`**, an incremental
235
+ on the newest backup otherwise;
236
+ 2. **a full backup after all on `HISTORY_LOST`** — the oplog no longer
237
+ reaches the last backup, and every incremental would fail alike until
238
+ one — with `fellBack: true`. Any other error rejects the run, nothing
239
+ pruned;
240
+ 3. **`verify` with the identity**: the new backup read back, decrypted,
241
+ every digest and the signature checked;
242
+ 4. **the rotation**, with `keep` — unless `keep: false`.
243
+
244
+ ```ts
245
+ interface RunReport {
246
+ id: string;
247
+ kind: 'full' | 'incremental';
248
+ fellBack: boolean; // an incremental was due, but the oplog no longer reached the last backup
249
+ entries: number;
250
+ storedSize: number;
251
+ chain: number; // how many backups a restore of this one reads: itself and those it builds on
252
+ removed: string[]; // the ids the rotation removed
253
+ }
254
+ ```
255
+
256
+ ```ts
257
+ const report = await backups.run();
258
+ if (report.fellBack) console.warn('the oplog window is shorter than the interval between runs');
259
+ console.log(JSON.stringify(report)); // ids and sizes: never a key nor a document
260
+ ```
261
+
262
+ `now` decides between a full and an incremental backup, nothing else.
263
+ The backup and the rotation go by the machine's clock: a backup carries
264
+ the time it was made, and a later `now` given to the rotation would remove
265
+ the backup just made. So a `now` a `fullEvery` ahead makes a full backup
266
+ today, and keeps it — for a spec, or to
267
+ [force a full backup](operations.md#forcing-a-full-backup):
268
+
269
+ ```ts
270
+ import { DEFAULT_FULL_EVERY } from '@softistx/mongo-backup';
271
+
272
+ await backups.run(new Date(Date.now() + DEFAULT_FULL_EVERY)); // { kind: 'full', chain: 1, … }
273
+ ```
274
+
275
+ A `now` that is not a valid `Date` rejects before anything is read, with
276
+ a bare `TypeError`: `run on "shop": now must be a valid Date`.
277
+
278
+ **The messages name the call.** What `mongoSource` throws when called
279
+ directly — `mongoSource: the snapshot outlived the history the server
280
+ keeps; …` — `run` throws as `run on "shop": the snapshot outlived the
281
+ history the server keeps; …`: same class, same `code`, the original as
282
+ `cause`. `restore` and `drill` do the same with `restore on "shop":` and
283
+ `drill on "shop":` for `mongoTarget:` and `restoreCollections:` —
284
+ [errors](errors.md#through-mongobackups).
285
+
286
+ A run that overlaps another fails on the repository's lock, and an error
287
+ `run` does not handle — `UNSUPPORTED`, `CHANGING`, a driver error — is
288
+ thrown as it is: [running it in production](operations.md#the-job) and
289
+ [errors](errors.md).
290
+
291
+ ### `restore`
292
+
293
+ ```ts
294
+ interface RestoreCommon {
295
+ into: Db;
296
+ at?: string | Date | undefined;
297
+ collections?: CollectionFilter | undefined;
298
+ as?: Readonly<Record<string, string>> | ((name: string) => string) | undefined;
299
+ }
300
+
301
+ type RestoreAtOptions =
302
+ | (RestoreCommon & { documents?: undefined; replace?: boolean | undefined }) // collections whole
303
+ | (RestoreCommon & { documents: { filter: Document; existing: 'replace' | 'keep' }; replace?: never }); // some documents
304
+
305
+ type RestoreReport = Restored & {
306
+ collections?: { name: string; as: string; documents?: number }[];
307
+ };
308
+ ```
309
+
310
+ | Option | Type | Default | Effect |
311
+ | --- | --- | --- | --- |
312
+ | `into` | `Db` | required | the database restored into: another, or the one backed up |
313
+ | `at` | `string \| Date` | the newest backup | a backup's id, or a time: the newest backup made at or before it |
314
+ | `collections` | `readonly string[] \| ((name: string) => boolean)` | all | some collections and views only, by their name at the backup's time |
315
+ | `as` | `Record<string, string> \| ((name: string) => string)` | their own names | other names to restore them under |
316
+ | `documents` | `{ filter, existing }` | — | only the documents `filter` matches, merged on `_id` into what is there; `existing: 'keep'` or `'replace'` says what happens to one already there |
317
+ | `replace` | `boolean` | `false` | replace collections and views already there, rather than refuse them with `EXISTS` — on a whole restore, or a part by `collections` or `as`. Refused with `documents`, by the types and at run time |
318
+
319
+ **Whole or part.** With none of `collections`, `as` and `documents`, the
320
+ restore is whole, through `mongoTarget`, and the report is `@softistx/backup`'s
321
+ `Restored` — `{ id, repository, entries, size }`. With any of them it goes
322
+ through `restoreCollections`: the whole backup is rebuilt in a scratch
323
+ database `nxgt-restore-<uuid>` on `into`'s client, then what was asked for
324
+ moves into `into`, and the report has `collections`:
325
+
326
+ ```ts
327
+ // the database as it was this morning, into another one
328
+ const back = await backups.restore({ into: client.db('shop-restored'), at: new Date('2026-10-04T09:00:00Z') });
329
+ back.collections; // undefined: a whole restore
330
+
331
+ // every collection beside the live one, under another name
332
+ const part = await backups.restore({ into: client.db('shop'), as: (name) => `${name}-before` });
333
+ // part.collections: [{ name: 'customers', as: 'customers-before' }, { name: 'orders', as: 'orders-before' }]
334
+
335
+ // one deleted document, back where it was
336
+ const some = await backups.restore({
337
+ into: client.db('shop'),
338
+ collections: ['orders'],
339
+ documents: { filter: { _id: 'o-1001' }, existing: 'keep' },
340
+ });
341
+ // some.collections: [{ name: 'orders', as: 'orders', documents: 1 }]
342
+ ```
343
+
344
+ **Picking the backup.** A `Date` takes the newest backup made at or before
345
+ it, an incremental included: it holds the database as it was then, its
346
+ chain replayed. A string is taken as an id, as `list` gives it.
347
+
348
+ ```ts
349
+ await backups.restore({ into: client.db('shop-restored') });
350
+ // MongoBackupError (NOT_FOUND): restore on "shop": the repository holds no backup yet
351
+
352
+ await backups.restore({ into: client.db('shop-restored'), at: new Date('2020-01-01') });
353
+ // MongoBackupError (NOT_FOUND): restore on "shop": no backup was made at or before that time
354
+ ```
355
+
356
+ `"shop"` is the backup's name: `name`, or the database's. Three options
357
+ are refused before anything is read, the key file included, with a bare
358
+ `TypeError`: an `into` that is not a driver `Db`
359
+ (`restore on "shop": into must be a MongoDB Db`), and these two:
360
+
361
+ ```ts
362
+ await backups.restore({ into: client.db('shop-restored'), at: new Date('yesterday') });
363
+ // TypeError: restore on "shop": at must be a backup's id or a valid Date
364
+
365
+ const documents = { filter: { _id: 'o-1001' }, existing: 'keep' } as const;
366
+ // @ts-expect-error — the types refuse it too
367
+ await backups.restore({ into: client.db('shop'), documents, replace: true });
368
+ // TypeError: restore on "shop": replace is for whole collections; documents says what happens to those there
369
+ ```
370
+
371
+ An id the repository does not hold rejects with `@softistx/backup`'s
372
+ `BackupError` `NOT_FOUND`. Everything else a restore throws — `EXISTS`, a
373
+ name in `collections` the backup lacks, an `as` that names nothing — is
374
+ `mongoTarget`'s and `restoreCollections`'s, on [restore](restore.md). A
375
+ partial restore's refusals name the call: where `restoreCollections` says
376
+ `restoreCollections: as names a collection not restored`, `restore` says
377
+ `restore on "shop": as names a collection not restored`.
378
+
379
+ ### `drill`
380
+
381
+ ```ts
382
+ interface DrillReport {
383
+ id: string;
384
+ collections: { name: string; documents: number }[];
385
+ }
386
+ ```
387
+
388
+ The newest backup, chain included, restored through `mongoTarget` into a
389
+ database of its own, `nxgt-drill-<uuid>` on `db`'s client; each collection
390
+ counted, in name order — views and `system.*` apart; then the database
391
+ dropped, failed or not. It rejects with `NOT_FOUND`
392
+ (`drill on "shop": the repository holds no backup yet`) on an empty
393
+ repository, and with whatever the restore threw otherwise.
394
+
395
+ ```ts
396
+ const { id, collections } = await backups.drill();
397
+ const orders = collections.find((c) => c.name === 'orders');
398
+ if (!orders || orders.documents === 0) throw new Error(`drill of ${id}: no orders`);
399
+ ```
400
+
401
+ The user needs the right to create that database, and the server the room
402
+ for a whole copy for as long as the drill runs. A process killed mid-drill
403
+ leaves the `nxgt-drill-<uuid>` database behind: drop it by hand.
404
+
405
+ ### `list`
406
+
407
+ The backups the repository holds, oldest first, as `@softistx/backup` lists
408
+ them: `{ id, createdAt, kind, parent, entries, storedSize, held }`. It
409
+ decrypts nothing, but reads the key file all the same: a manifest is
410
+ listed only when it is signed with the key file's signing key, so a backup
411
+ made with other keys — or by hand, unsigned — is not in it.
412
+
413
+ ```ts
414
+ const newest = (await backups.list()).at(-1);
415
+ const hours = newest ? (Date.now() - newest.createdAt.getTime()) / 3_600_000 : Infinity;
416
+ if (hours > 2) console.error('no backup for two hours');
417
+ ```
418
+
419
+ ### `binding`
420
+
421
+ The `@softistx/backup` binding `mongoBackups` uses — bound to the repository,
422
+ the recipient and the signing key — and the keys, for what it does not do:
423
+ a differential backup, a legal hold, a restore with `only`, a full backup
424
+ on demand.
425
+
426
+ ```ts
427
+ import { mongoSource } from '@softistx/mongo-backup';
428
+
429
+ const { backups: bound, keys } = await backups.binding();
430
+ const full = await bound.create(mongoSource({ db: client.db('shop') }));
431
+ await bound.verify(full.id, { identities: [keys.identity] });
432
+ ```
433
+
434
+ Give the source the same `collections` as `mongoBackups`, or the next
435
+ incremental follows another set.
436
+
437
+ ## A drill in a spec
438
+
439
+ A backup nobody restored is a hope. With `bun test`, against the backups a
440
+ job made:
441
+
442
+ ```ts
443
+ import { afterAll, expect, test } from 'bun:test';
444
+ import { mongoBackups } from '@softistx/mongo-backup';
445
+ import { MongoClient } from 'mongodb';
446
+
447
+ const client = await MongoClient.connect(process.env.MONGO_URL as string);
448
+ afterAll(() => client.close());
449
+
450
+ test('the newest backup restores', async () => {
451
+ const backups = mongoBackups({
452
+ db: client.db('shop'),
453
+ repository: '/mnt/backups',
454
+ keyFile: '/etc/backup/shop.key',
455
+ });
456
+ const { collections } = await backups.drill();
457
+ expect(collections.find((c) => c.name === 'orders')?.documents).toBeGreaterThan(0);
458
+ }, 600_000);
459
+ ```
460
+
461
+ ## Lower level
462
+
463
+ `mongoBackups` is `@softistx/backup`'s `bindBackup`, with `mongoSource` to back
464
+ up and `mongoTarget` or `restoreCollections` to restore. Reach for them
465
+ when you keep the keys apart rather than in one file, make differential
466
+ backups, or decide the schedule yourself. The rest of this page is
467
+ `mongoSource`; the targets are on [restore](restore.md).
468
+
469
+ ```ts
470
+ import { bindBackup, defineBackup, localRepository } from '@softistx/backup';
471
+ import { mongoSource, mongoTarget } from '@softistx/mongo-backup';
472
+ import { MongoClient } from 'mongodb';
473
+
474
+ const client = await MongoClient.connect(process.env.MONGO_URL as string); // a replica set
475
+ const backups = bindBackup(defineBackup({ name: 'shop-db' }), {
476
+ repositories: [localRepository({ path: '/mnt/backups' })],
477
+ recipients: [process.env.BACKUP_RECIPIENT as string], // age1… — a public key
478
+ });
479
+
480
+ const created = await backups.create(mongoSource({ db: client.db('shop') }));
481
+ // { id: '20261004T221500123Z-9f3a61c0', kind: 'full', parent: null, entries: 12, … }
482
+
483
+ await backups.verify(created.id); // every object against the manifest, no key
484
+
485
+ await backups.restore(created.id, mongoTarget({ db: client.db('shop-restored') }), {
486
+ identities: [process.env.BACKUP_IDENTITY as string], // AGE-SECRET-KEY-1…
487
+ });
488
+ ```
489
+
490
+ `defineBackup`, `bindBackup`, the keys and the repositories are
491
+ `@softistx/backup`'s; its
492
+ [getting started](https://github.com/softistx/nxgt-data/blob/develop/packages/backup/docs/guide/getting-started.md)
493
+ covers them.
494
+
495
+ ## `mongoSource`
496
+
497
+ ```ts
498
+ type CollectionFilter = readonly string[] | ((name: string) => boolean);
499
+
500
+ interface MongoSourceOptions {
501
+ db: Db;
502
+ collections?: CollectionFilter | undefined;
503
+ }
504
+
505
+ function mongoSource(options: MongoSourceOptions): BackupSource; // kind: 'mongo'
506
+ ```
507
+
508
+ | Option | Type | Default | Effect |
509
+ | --- | --- | --- | --- |
510
+ | `db` | `Db` | required | the database to back up. Its client must reach a replica set or a sharded cluster |
511
+ | `collections` | `readonly string[] \| ((name: string) => boolean)` | every collection and view but `system.*` | which collections and views to read: their names, or a test on each name |
512
+
513
+ `mongoSource` checks its options at once, and touches nothing:
514
+
515
+ ```ts
516
+ mongoSource({ db: 'shop' as never });
517
+ // TypeError: mongoSource: db must be a MongoDB Db
518
+
519
+ mongoSource({ db: client.db('shop'), collections: 'orders' as never });
520
+ // TypeError: mongoSource: collections must be a list of names or a function
521
+ ```
522
+
523
+ The types refuse both before they run. The source keeps nothing between
524
+ backups — where the next incremental resumes is recorded in the backup
525
+ itself — so a new process makes the next backup with a new `mongoSource`.
526
+ Give one `create` at a time a given source object: it holds the position of
527
+ the backup it is reading until `@softistx/backup` asks for it.
528
+
529
+ ## What a full backup holds
530
+
531
+ For each collection, in name order:
532
+
533
+ | Entry | Holds |
534
+ | --- | --- |
535
+ | `metadata/<name>` | its options as `listCollections` gives them — validator, collation, capped size, … — and its indexes as `listIndexes` gives them, `_id` apart |
536
+ | `documents/<name>` | every document, as concatenated BSON: the bytes `mongodump` writes to a `.bson` file |
537
+
538
+ - **A view** has its metadata only — `viewOn` and `pipeline` among its
539
+ options — and is created from it on restore.
540
+ - **A GridFS bucket** is two plain collections, `<bucket>.files` and
541
+ `<bucket>.chunks`, backed up and restored like the others. With a list,
542
+ name both: `collections: ['orders', 'fs.files', 'fs.chunks']`.
543
+ - **`system.*` is never read**, whatever `collections` says: neither
544
+ `system.views` (views come back from their metadata), nor `system.js`, nor
545
+ `system.profile`. Users and roles live in the `admin` database, not in
546
+ the one backed up.
547
+ - **Numbers keep their kind.** Documents are read raw and written back raw:
548
+ an `Int32`, a `Long`, a `Double` and a `Decimal128` come back as they
549
+ were, as do dates, binaries and regular expressions.
550
+
551
+ The byte layout is on the [format](format.md) page.
552
+
553
+ ## Choosing collections
554
+
555
+ `mongoBackups`' `collections` is passed to `mongoSource` as it is, so what
556
+ follows holds for both. A list names exactly what to back up:
557
+
558
+ ```ts
559
+ const source = mongoSource({ db: client.db('shop'), collections: ['orders', 'customers'] });
560
+ ```
561
+
562
+ **A name in the list that the database lacks rejects the backup** — a typo
563
+ would otherwise back up nothing, and say nothing. The check runs when the
564
+ full backup starts reading, so it is `create` that rejects, before any entry
565
+ is stored:
566
+
567
+ ```ts
568
+ await backups.create(mongoSource({ db: client.db('shop'), collections: ['ordres'] }));
569
+ // TypeError: mongoSource: a collection named in collections is not in the database
570
+ ```
571
+
572
+ A test picks what it returns `true` for, and never complains about a
573
+ collection that is not there — the way to leave something out:
574
+
575
+ ```ts
576
+ const source = mongoSource({
577
+ db: client.db('shop'),
578
+ collections: (name) => !name.startsWith('cache.') && name !== 'metrics',
579
+ });
580
+ ```
581
+
582
+ Either form applies to views as to collections, and to the changes an
583
+ [incremental](incremental.md#the-collections-a-chain-follows) backup
584
+ records: a change to a collection the chain does not follow is not
585
+ recorded. A change to
586
+ `collections` takes effect at the **next full backup**: an incremental
587
+ follows the collections its full backup held, plus those created since that
588
+ the filter takes.
589
+
590
+ **A time-series collection is refused**, not skipped: a full backup that
591
+ meets one rejects with `UNSUPPORTED`, and the way out is to leave it out:
592
+
593
+ ```ts
594
+ await backups.create(mongoSource({ db: client.db('shop') }));
595
+ // MongoBackupError (UNSUPPORTED): mongoSource: a collection is of a type this version
596
+ // does not back up (a time-series one); leave it out with collections
597
+
598
+ await backups.create(mongoSource({ db: client.db('shop'), collections: (name) => name !== 'metrics' }));
599
+ ```
600
+
601
+ ## One cluster time
602
+
603
+ A full backup opens **one snapshot session** before it gives its first
604
+ entry, and reads every collection in it. Every document it holds is as it
605
+ was at that one cluster time, however long the backup runs: a write that
606
+ lands after the snapshot opened is not in it, even in a collection read an
607
+ hour later. That is what makes the collections agree with each other — an
608
+ order and its customer, a GridFS file and its chunks.
609
+
610
+ The collections, their options and their indexes are not read in a
611
+ snapshot — the server does not serve those reads at a cluster time — so a
612
+ full backup reads them **before** it pins the snapshot and **again after**.
613
+ The same both times, they are what the snapshot holds; otherwise it pins
614
+ again, up to five times, then fails:
615
+
616
+ ```text
617
+ MongoBackupError (CHANGING): mongoSource: the collections or their indexes kept
618
+ changing while the snapshot was taken; try again when they settle
619
+ ```
620
+
621
+ Nothing is stored when it does: run the backup again once whatever was
622
+ creating, dropping or indexing collections has finished. Past that point
623
+ the metadata entries come from what was read, not from the database, so:
624
+
625
+ - **an index built while the backup runs** is not in it: it arrives in the
626
+ next incremental, as a `createIndexes` change, and a restore of this
627
+ backup has the collection without it;
628
+ - **a collection dropped or renamed while it runs** is still read, at the
629
+ snapshot, as it was.
630
+
631
+ The next incremental starts **just after** that cluster time, so it replays
632
+ nothing the full backup holds, and misses nothing written since. It follows
633
+ the collections this backup holds — its `metadata/<name>` entries say
634
+ which, and each position records only what changed since, on the
635
+ [format](format.md#the-position-and-the-fingerprints) page.
636
+
637
+ ## A long snapshot
638
+
639
+ The server keeps the history a snapshot reads for
640
+ `minSnapshotHistoryWindowInSeconds` — 300 seconds by default. A full
641
+ backup reads its collections one at a time, and each entry is compressed,
642
+ encrypted and stored in every repository before the next is read, so the
643
+ whole backup — slow repositories included — must fit in that window, or it
644
+ fails:
645
+
646
+ ```text
647
+ MongoBackupError (SNAPSHOT_TOO_OLD): mongoSource: the snapshot outlived the history
648
+ the server keeps; raise minSnapshotHistoryWindowInSeconds, or back up fewer
649
+ collections at a time
650
+ ```
651
+
652
+ Raise the window on every member that may serve the read (on every shard,
653
+ for a sharded cluster), to more than your longest full backup:
654
+
655
+ ```ts
656
+ await client.db('admin').command({ setParameter: 1, minSnapshotHistoryWindowInSeconds: 3600 });
657
+ ```
658
+
659
+ The server keeps more history for it, in its cache and on disk; set it
660
+ back once the backup is done if that matters to you. Or split the database
661
+ into two definitions with two `collections` lists — at the cost of the one
662
+ cluster time, which then holds within each backup, not between them.
663
+
664
+ ## Restoring with `mongoTarget`
665
+
666
+ ```ts
667
+ import { mongoTarget } from '@softistx/mongo-backup';
668
+
669
+ await backups.restore(created.id, mongoTarget({ db: client.db('shop-restored') }), {
670
+ identities: [process.env.BACKUP_IDENTITY as string],
671
+ });
672
+ ```
673
+
674
+ Each collection lands whole or not at all; one already there is refused
675
+ with `EXISTS` unless `replace: true` — [restore](restore.md) has every
676
+ option.
677
+
678
+ ## A nightly job by hand
679
+
680
+ A full backup every night, checked, rotated, run with `bun run` — what
681
+ `run` does, without incrementals, for keys kept apart. Once incrementals
682
+ make sense, [incremental](incremental.md#a-weekly-schedule) has the weekly
683
+ schedule, or [`run`](#run) does it for you.
684
+
685
+ ```ts
686
+ // backup.ts — run with `bun run backup.ts` from cron
687
+ import { bindBackup, defineBackup, localRepository } from '@softistx/backup';
688
+ import { MongoBackupError, mongoSource } from '@softistx/mongo-backup';
689
+ import { MongoClient } from 'mongodb';
690
+
691
+ const client = await MongoClient.connect(process.env.MONGO_URL as string);
692
+ try {
693
+ const backups = bindBackup(defineBackup({ name: 'shop-db' }), {
694
+ repositories: [localRepository({ path: '/mnt/backups' })],
695
+ recipients: [process.env.BACKUP_RECIPIENT as string],
696
+ tmpDir: '/var/tmp',
697
+ });
698
+
699
+ const created = await backups.create(
700
+ mongoSource({ db: client.db('shop'), collections: (name) => name !== 'metrics' }),
701
+ );
702
+ await backups.verify(created.id);
703
+ await backups.prune({ keep: { daily: 14, weekly: 8 } });
704
+ console.log(`backup ${created.id}: ${created.entries} entries, ${created.storedSize} bytes`);
705
+ } catch (error) {
706
+ if (error instanceof MongoBackupError) {
707
+ console.error(`backup failed (${error.code}): ${error.message}`, error.cause);
708
+ }
709
+ throw error;
710
+ } finally {
711
+ await client.close();
712
+ }
713
+ ```
714
+
715
+ Next: [running it in production](operations.md), then
716
+ [incremental](incremental.md) for what an incremental records.