@softistx/mongo-backup 0.0.0-stage → 0.4.2

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,1257 @@
1
+ # Troubleshooting
2
+
3
+ This package throws one error of its own, `MongoBackupError`, told apart by
4
+ its `code`: `SNAPSHOT_TOO_OLD`, `CHANGING`, `HISTORY_LOST`, `UNSUPPORTED`,
5
+ `EXISTS`, `MALFORMED`, `NOT_FOUND` or `KEY_FILE`. A refusal of the way
6
+ `mongoBackups`, `mongoSource`, `mongoTarget` or `restoreCollections` was
7
+ called is a plain `TypeError`. Errors from the driver or the server come back as
8
+ they are; when one is the cause of a `MongoBackupError`, it is its `cause`.
9
+ A key file that is not there is a `KEY_FILE` too, the file system's
10
+ `ENOENT` as its `cause`.
11
+
12
+ **No message of `MongoBackupError` or of those `TypeError`s quotes a value,
13
+ a document or a collection name**: a backup error ends up in logs. A driver
14
+ or server error passes through as it is, and its message may quote both —
15
+ an `E11000` during a restore quotes the duplicate key. To find which collection is concerned, read the
16
+ server's log, or the change stream, around the time of the failure.
17
+
18
+ ```ts
19
+ import { MongoBackupError } from '@softistx/mongo-backup';
20
+
21
+ try {
22
+ await backups.create(mongoSource({ db }), { kind: 'incremental', identities });
23
+ } catch (error) {
24
+ if (error instanceof MongoBackupError) console.error(error.code, error.message);
25
+ throw error;
26
+ }
27
+ ```
28
+
29
+ The errors of `@softistx/backup` itself — keys, repositories, locks, chains —
30
+ are on [its own troubleshooting page](https://github.com/softistx/data/blob/develop/packages/backup/docs/troubleshooting.md);
31
+ the few you meet first with this package are repeated below. Their headings
32
+ use `app` for the definition's name and `local` for the repository's.
33
+
34
+ - **Install and run**
35
+ - [`ReferenceError: Bun is not defined`](#referenceerror-bun-is-not-defined)
36
+ - **Configuration**
37
+ - [`mongoBackups: db must be a MongoDB Db`](#mongobackups-db-must-be-a-mongodb-db)
38
+ - [`mongoBackups: keyFile must be an absolute path`](#mongobackups-keyfile-must-be-an-absolute-path)
39
+ - [`mongoBackups: repository must be an absolute folder, or repositories`](#mongobackups-repository-must-be-an-absolute-folder-or-repositories)
40
+ - [`mongoBackups: keep must be false, or name rules each a whole number, 1 or more`](#mongobackups-keep-must-be-false-or-name-rules-each-a-whole-number-1-or-more)
41
+ - [`mongoBackups: fullEvery must be a whole number of milliseconds, an hour or more`](#mongobackups-fullevery-must-be-a-whole-number-of-milliseconds-an-hour-or-more)
42
+ - [`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-"`](#mongobackups-the-databases-name-cannot-name-a-backup-give-name-1-to-100-characters-lowercase-letters-digits--_-and---starting-with-a-letter-or-a-digit-without-partial-)
43
+ - [`mongoBackups: name must be 1 to 100 characters, lowercase letters, digits, ".", "_" and "-", starting with a letter or a digit, without ".partial-"`](#mongobackups-name-must-be-1-to-100-characters-lowercase-letters-digits--_-and---starting-with-a-letter-or-a-digit-without-partial-)
44
+ - [`mongoBackups: repository must list repositories, each under a name of its own`](#mongobackups-repository-must-list-repositories-each-under-a-name-of-its-own)
45
+ - [`mongoBackups: tmpDir must be an absolute path`](#mongobackups-tmpdir-must-be-an-absolute-path)
46
+ - [`run on "app": now must be a valid Date`](#run-on-app-now-must-be-a-valid-date)
47
+ - [`mongoSource: db must be a MongoDB Db`](#mongosource-db-must-be-a-mongodb-db)
48
+ - [`mongoSource: collections must be a list of names or a function`](#mongosource-collections-must-be-a-list-of-names-or-a-function)
49
+ - [`mongoTarget: db must be a MongoDB Db`](#mongotarget-db-must-be-a-mongodb-db)
50
+ - [`mongoTarget: tmpDir must be an absolute path`](#mongotarget-tmpdir-must-be-an-absolute-path)
51
+ - **The key file**
52
+ - [`usage: nxgt-mongo-backup keygen <path>`](#usage-nxgt-mongo-backup-keygen-path)
53
+ - [`<path> is already there: it is never overwritten`](#path-is-already-there-it-is-never-overwritten)
54
+ - [`keygen failed: <message>`](#keygen-failed-message)
55
+ - [`mongoBackups on "app": there is no key file there; write one with nxgt-mongo-backup keygen`](#mongobackups-on-app-there-is-no-key-file-there-write-one-with-nxgt-mongo-backup-keygen)
56
+ - [`mongoBackups on "app": others than its owner can read or write the key file; chmod 600 it`](#mongobackups-on-app-others-than-its-owner-can-read-or-write-the-key-file-chmod-600-it)
57
+ - [`mongoBackups on "app": the key file is not one keygen wrote`](#mongobackups-on-app-the-key-file-is-not-one-keygen-wrote)
58
+ - **Choosing the backup to restore**
59
+ - [`restore on "app": the repository holds no backup yet`](#restore-on-app-the-repository-holds-no-backup-yet)
60
+ - [`drill on "app": the repository holds no backup yet`](#drill-on-app-the-repository-holds-no-backup-yet)
61
+ - [`restore on "app": no backup was made at or before that time`](#restore-on-app-no-backup-was-made-at-or-before-that-time)
62
+ - [`restore on "app": into must be a MongoDB Db`](#restore-on-app-into-must-be-a-mongodb-db)
63
+ - [`restore on "app": at must be a backup's id or a valid Date`](#restore-on-app-at-must-be-a-backups-id-or-a-valid-date)
64
+ - [`restore on "app": replace is for whole collections; documents says what happens to those there`](#restore-on-app-replace-is-for-whole-collections-documents-says-what-happens-to-those-there)
65
+ - **Full backups**
66
+ - [`mongoSource: the server gave no snapshot time; a backup needs a replica set or a sharded cluster`](#mongosource-the-server-gave-no-snapshot-time-a-backup-needs-a-replica-set-or-a-sharded-cluster)
67
+ - [`mongoSource: a collection named in collections is not in the database`](#mongosource-a-collection-named-in-collections-is-not-in-the-database)
68
+ - [`mongoSource: a collection is of a type this version does not back up (a time-series one); leave it out with collections`](#mongosource-a-collection-is-of-a-type-this-version-does-not-back-up-a-time-series-one-leave-it-out-with-collections)
69
+ - [`mongoSource: the collections or their indexes kept changing while the snapshot was taken; try again when they settle`](#mongosource-the-collections-or-their-indexes-kept-changing-while-the-snapshot-was-taken-try-again-when-they-settle)
70
+ - [`mongoSource: the snapshot outlived the history the server keeps; raise minSnapshotHistoryWindowInSeconds, or back up fewer collections at a time`](#mongosource-the-snapshot-outlived-the-history-the-server-keeps-raise-minsnapshothistorywindowinseconds-or-back-up-fewer-collections-at-a-time)
71
+ - **Incremental and differential backups**
72
+ - [`create on "app": no backup to build on (repository "local")`](#create-on-app-no-backup-to-build-on-repository-local)
73
+ - [`create on "app": the source is not of the kind the backup it builds on was made from`](#create-on-app-the-source-is-not-of-the-kind-the-backup-it-builds-on-was-made-from)
74
+ - [`mongoSource: the server gave no operation time; a backup needs a replica set or a sharded cluster`](#mongosource-the-server-gave-no-operation-time-a-backup-needs-a-replica-set-or-a-sharded-cluster)
75
+ - [`mongoSource: the backup built on recorded no position this version reads; make a full backup`](#mongosource-the-backup-built-on-recorded-no-position-this-version-reads-make-a-full-backup)
76
+ - [`mongoSource: the change stream cannot resume where the last backup stopped: the oplog no longer reaches back there; make a full backup`](#mongosource-the-change-stream-cannot-resume-where-the-last-backup-stopped-the-oplog-no-longer-reaches-back-there-make-a-full-backup)
77
+ - [`mongoSource: 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`](#mongosource-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)
78
+ - [`mongoSource: the collections created, renamed or dropped since the full backup are too many to record; make a full backup`](#mongosource-the-collections-created-renamed-or-dropped-since-the-full-backup-are-too-many-to-record-make-a-full-backup)
79
+ - [`mongoSource: a collection was renamed into those backed up, with documents an incremental backup never read; make a full backup`](#mongosource-a-collection-was-renamed-into-those-backed-up-with-documents-an-incremental-backup-never-read-make-a-full-backup)
80
+ - [`mongoSource: an entry of the backup built on was asked for again; it has no fingerprint, so make a full backup`](#mongosource-an-entry-of-the-backup-built-on-was-asked-for-again-it-has-no-fingerprint-so-make-a-full-backup)
81
+ - **Restoring**
82
+ - [`mongoTarget: a collection or view the backup holds is already in the database; restore into another one, or pass replace: true`](#mongotarget-a-collection-or-view-the-backup-holds-is-already-in-the-database-restore-into-another-one-or-pass-replace-true)
83
+ - [`mongoTarget: an entry name is not one this version writes`](#mongotarget-an-entry-name-is-not-one-this-version-writes)
84
+ - [`mongoTarget: a collection’s documents came before its metadata`](#mongotarget-a-collections-documents-came-before-its-metadata)
85
+ - [`mongoTarget: a metadata entry is not one this version wrote`](#mongotarget-a-metadata-entry-is-not-one-this-version-wrote)
86
+ - [`mongoTarget: a metadata entry is larger than 16 MiB`](#mongotarget-a-metadata-entry-is-larger-than-16-mib)
87
+ - [`mongoTarget: an entry is not a sequence of BSON documents`](#mongotarget-an-entry-is-not-a-sequence-of-bson-documents)
88
+ - [`mongoTarget: a change is not one this version wrote`](#mongotarget-a-change-is-not-one-this-version-wrote)
89
+ - **Restoring some collections**
90
+ - [`restoreCollections: db must be a MongoDB Db`](#restorecollections-db-must-be-a-mongodb-db)
91
+ - [`restoreCollections: scratch must be a MongoDB Db`](#restorecollections-scratch-must-be-a-mongodb-db)
92
+ - [`restoreCollections: scratch must be on db's client`](#restorecollections-scratch-must-be-on-dbs-client)
93
+ - [`restoreCollections: scratch must be another database`](#restorecollections-scratch-must-be-another-database)
94
+ - [`restoreCollections: documents must be { filter, existing: 'replace' | 'keep' }`](#restorecollections-documents-must-be--filter-existing-replace--keep-)
95
+ - [`restoreCollections: replace is for whole collections; documents says what happens to those there`](#restorecollections-replace-is-for-whole-collections-documents-says-what-happens-to-those-there)
96
+ - [`restoreCollections: the scratch database holds collections; give an empty one`](#restorecollections-the-scratch-database-holds-collections-give-an-empty-one)
97
+ - [`restoreCollections: a collection named in collections is not in the backup`](#restorecollections-a-collection-named-in-collections-is-not-in-the-backup)
98
+ - [`restoreCollections: as must give a collection name`](#restorecollections-as-must-give-a-collection-name)
99
+ - [`restoreCollections: as gives two collections one name`](#restorecollections-as-gives-two-collections-one-name)
100
+ - [`restoreCollections: as names a collection not restored`](#restorecollections-as-names-a-collection-not-restored)
101
+ - [`restoreCollections: a collection or view to restore is already in the database; restore it under another name, or pass replace: true`](#restorecollections-a-collection-or-view-to-restore-is-already-in-the-database-restore-it-under-another-name-or-pass-replace-true)
102
+
103
+ **Through `mongoBackups`, the prefix names the call.** Every
104
+ `mongoSource:`, `mongoTarget:` and `restoreCollections:` message below is
105
+ quoted as the function throws it when you call it directly. `run`,
106
+ `restore` and `drill` replace that prefix with `run on "<name>":`,
107
+ `restore on "<name>":` or `drill on "<name>":`, `<name>` being the
108
+ backup's name — `restore on "shop": a collection or view the backup holds
109
+ is already in the database; …` for the `mongoTarget:` one. The class and
110
+ the `code` are the same; a `mongoSource:` or `mongoTarget:` one keeps the
111
+ original as its `cause`; `restoreCollections`'s own refusals are thrown
112
+ under the call's prefix directly and have none. Search for the part after the colon.
113
+ `restoreCollections` called directly does the same for the `mongoTarget:`
114
+ refusals of the restore it runs into its scratch database: they read
115
+ `restoreCollections: …`, the original as `cause`.
116
+
117
+ ## Install and run
118
+
119
+ ### `ReferenceError: Bun is not defined`
120
+
121
+ **When:** the first `create` or `restore`, under Node.
122
+ **Why:** `@softistx/backup` runs on Bun only, and `mongoTarget` stages the
123
+ changes of an incremental backup with `Bun.write` and reads them back with
124
+ `Bun.file`.
125
+ **Fix:** run the job with Bun.
126
+
127
+ ```sh
128
+ bun run backup.ts
129
+ ```
130
+
131
+ ## Configuration
132
+
133
+ These are thrown by `mongoBackups(…)`, `mongoSource(…)` or `mongoTarget(…)`
134
+ themselves, where the backup is wired — or, for `now`, by `run` before it
135
+ starts: nothing was read or written, and `mongoBackups` has not read the
136
+ key file yet.
137
+
138
+ ### `mongoBackups: db must be a MongoDB Db`
139
+
140
+ **Code:** none — a `TypeError`, thrown by `mongoBackups(…)` itself.
141
+ **When:** `mongoBackups({ db, … })` with something that is not a driver
142
+ `Db` — a `MongoClient`, a database name, or a Mongoose connection's `db`
143
+ read before it connected.
144
+ **Why:** the backups are of one database: its name is the backup's name by
145
+ default, and `drill` restores into a database on its client.
146
+ **Fix:** give the database, not the client.
147
+
148
+ ```ts
149
+ import { MongoClient } from 'mongodb';
150
+ import { mongoBackups } from '@softistx/mongo-backup';
151
+
152
+ const client = await MongoClient.connect(process.env.MONGO_URL!);
153
+ const backups = mongoBackups({
154
+ db: client.db('shop'),
155
+ repository: '/var/backups/shop',
156
+ keyFile: '/etc/backup/shop.key',
157
+ });
158
+ ```
159
+
160
+ ### `mongoBackups: keyFile must be an absolute path`
161
+
162
+ **Code:** none — a `TypeError`, thrown by `mongoBackups(…)` itself.
163
+ **When:** `mongoBackups({ keyFile })` with a relative path, or with
164
+ something that is not a string — most often an environment variable that is
165
+ not set, read as `undefined`.
166
+ **Why:** a relative path would depend on the folder the job was started
167
+ from, and a backup job is started from wherever its scheduler likes.
168
+ **Fix:** an absolute path; check the variable before the call.
169
+
170
+ ```ts
171
+ const keyFile = process.env.BACKUP_KEY_FILE;
172
+ if (!keyFile) throw new Error('BACKUP_KEY_FILE is not set');
173
+ const backups = mongoBackups({ db, repository: '/var/backups/shop', keyFile });
174
+ ```
175
+
176
+ ### `mongoBackups: repository must be an absolute folder, or repositories`
177
+
178
+ **Code:** none — a `TypeError`, thrown by `mongoBackups(…)` itself.
179
+ **When:** `mongoBackups({ repository })` with a relative folder, such as
180
+ `'backups'` or `'./backups'`.
181
+ **Why:** a string is a local folder, and as for `keyFile`, a relative one
182
+ would move with the folder the job was started from.
183
+ **Fix:** an absolute folder — or one or more repositories of
184
+ `@softistx/backup`, such as `localRepository` or `s3Repository`.
185
+
186
+ ```ts
187
+ import { join } from 'node:path';
188
+ import { localRepository } from '@softistx/backup';
189
+
190
+ mongoBackups({ db, keyFile, repository: join(import.meta.dir, 'backups') });
191
+ mongoBackups({ db, keyFile, repository: [localRepository({ path: '/var/backups/shop' })] });
192
+ ```
193
+
194
+ ### `mongoBackups: keep must be false, or name rules each a whole number, 1 or more`
195
+
196
+ **Code:** none — a `TypeError`, thrown by `mongoBackups(…)` itself, before
197
+ any backup is stored.
198
+ **When:** `mongoBackups({ keep })` with an empty policy (`{}`), a rule with
199
+ `0`, a fraction or a string, or something that is not a policy at all.
200
+ **Why:** `keep` is what `run` keeps after each backup: `@softistx/backup`'s
201
+ `KeepPolicy` — `last`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`,
202
+ `within`, `maxTotalSize` — each a whole number of 1 or more. A policy that
203
+ names no rule would keep nothing, so it is refused here rather than by
204
+ `prune` after every backup.
205
+ **Fix:** name at least one rule, leave `keep` out for `DEFAULT_KEEP`, or
206
+ pass `false` to keep everything.
207
+
208
+ ```ts
209
+ mongoBackups({ db, repository, keyFile, keep: { daily: 14, weekly: 8 } });
210
+ mongoBackups({ db, repository, keyFile, keep: false });
211
+ ```
212
+
213
+ ### `mongoBackups: fullEvery must be a whole number of milliseconds, an hour or more`
214
+
215
+ **Code:** none — a `TypeError`, thrown by `mongoBackups(…)` itself.
216
+ **When:** `mongoBackups({ fullEvery })` with a number of days or hours
217
+ rather than milliseconds, a fraction, or less than an hour.
218
+ **Why:** `fullEvery` is how old the newest full backup may grow before
219
+ `run` makes another, in milliseconds — a week by default,
220
+ `DEFAULT_FULL_EVERY`. Under an hour, every run would be a full backup.
221
+ **Fix:**
222
+
223
+ ```ts
224
+ const DAY = 24 * 60 * 60 * 1000;
225
+ mongoBackups({ db, repository, keyFile, fullEvery: 3 * DAY });
226
+ ```
227
+
228
+ ### `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-"`
229
+
230
+ **Code:** none — a `TypeError`, thrown by `mongoBackups(…)` itself; its
231
+ `cause` is `@softistx/backup`'s `defineBackup` `TypeError`.
232
+ **When:** `mongoBackups({ db })` without `name`, on a database whose name is
233
+ not a backup name: `client.db('MyShop')`, `client.db('shop_EU')`, a name
234
+ over 100 characters.
235
+ **Why:** the backup is named after the database by default, and a backup
236
+ name becomes a folder and a key prefix in every repository: lowercase
237
+ letters, digits, `.`, `_` and `-` only.
238
+ **Fix:** give the backup a name of its own — and keep it: a new name starts
239
+ a new chain, and the old backups stay under the old one.
240
+
241
+ ```ts
242
+ mongoBackups({ db: client.db('MyShop'), name: 'myshop', repository, keyFile });
243
+ ```
244
+
245
+ ### `mongoBackups: name must be 1 to 100 characters, lowercase letters, digits, ".", "_" and "-", starting with a letter or a digit, without ".partial-"`
246
+
247
+ **Code:** none — a `TypeError`, thrown by `mongoBackups(…)` itself; its
248
+ `cause` is `@softistx/backup`'s `defineBackup` `TypeError`.
249
+ **When:** `mongoBackups({ name })` with capitals, spaces, `/`, an empty
250
+ string, or more than 100 characters.
251
+ **Why:** as for [the database's name](#mongobackups-the-databases-name-cannot-name-a-backup-give-name-1-to-100-characters-lowercase-letters-digits--_-and---starting-with-a-letter-or-a-digit-without-partial-):
252
+ the name becomes a folder and a key prefix.
253
+ **Fix:**
254
+
255
+ ```ts
256
+ mongoBackups({ db, name: 'shop-eu', repository, keyFile });
257
+ ```
258
+
259
+ ### `mongoBackups: repository must list repositories, each under a name of its own`
260
+
261
+ **Code:** none — a `TypeError`, thrown by `mongoBackups(…)` itself.
262
+ **When:** `mongoBackups({ repository: [] })`, or a list holding two
263
+ repositories with the same `name` — two `s3Repository`s left at their
264
+ default name `s3`, say.
265
+ **Why:** every backup is written to each repository, and each one's outcome
266
+ is reported under its name; two under one name could not be told apart.
267
+ **Fix:** name each one.
268
+
269
+ ```ts
270
+ import { s3Repository } from '@softistx/backup';
271
+ import { S3Client } from 'bun';
272
+
273
+ mongoBackups({
274
+ db,
275
+ keyFile,
276
+ repository: [
277
+ s3Repository({ client: new S3Client({ bucket: 'backups-eu' }), name: 's3-eu' }),
278
+ s3Repository({ client: new S3Client({ bucket: 'backups-us' }), name: 's3-us' }),
279
+ ],
280
+ });
281
+ ```
282
+
283
+ ### `mongoBackups: tmpDir must be an absolute path`
284
+
285
+ **Code:** none — a `TypeError`, thrown by `mongoBackups(…)` itself.
286
+ **When:** `mongoBackups({ tmpDir })` with a relative path.
287
+ **Why:** objects and changes are staged there; a relative path would
288
+ depend on the folder the job was started from.
289
+ **Fix:** an absolute path, or leave it out for the system's temporary
290
+ folder.
291
+
292
+ ```ts
293
+ mongoBackups({ db, repository, keyFile, tmpDir: '/var/tmp' });
294
+ ```
295
+
296
+ ### `run on "app": now must be a valid Date`
297
+
298
+ **Code:** none — a `TypeError`; `run` rejects with it before reading
299
+ anything, the key file included. `app` is the backup's name.
300
+ **When:** `run(now)` with something that is not a `Date`, or an invalid
301
+ one — `new Date('tomorrow')`, a date parsed from an empty variable.
302
+ **Why:** `now` decides whether a full or an incremental backup is due;
303
+ with no time, it could decide neither. It decides nothing else: the
304
+ backup and the rotation go by the machine's clock, since a later `now`
305
+ given to the rotation would remove the backup just made.
306
+ **Fix:** leave it out on a schedule; pass a valid `Date` in a spec, or to
307
+ force a full backup.
308
+
309
+ ```ts
310
+ import { DEFAULT_FULL_EVERY } from '@softistx/mongo-backup';
311
+
312
+ await backups.run(); // the machine's time
313
+ await backups.run(new Date(Date.now() + DEFAULT_FULL_EVERY)); // a full backup now
314
+ ```
315
+
316
+ ### `mongoSource: db must be a MongoDB Db`
317
+
318
+ **When:** `mongoSource({ db })` with something that is not a driver `Db` —
319
+ a `MongoClient`, a collection, a connection string, or `undefined`, such as
320
+ a Mongoose connection's `db` read before it connected.
321
+ **Why:** the source reads one database, and needs the `Db` of the official
322
+ `mongodb` driver: it calls `watch`, and reads `databaseName`.
323
+ **Fix:** give the database, not the client.
324
+
325
+ ```ts
326
+ import { MongoClient } from 'mongodb';
327
+ import { mongoSource } from '@softistx/mongo-backup';
328
+
329
+ const client = await MongoClient.connect(process.env.MONGO_URL!);
330
+ const source = mongoSource({ db: client.db('shop') });
331
+ ```
332
+
333
+ With Mongoose, `await mongoose.connect(…)` first, then pass
334
+ `mongoose.connection.db`.
335
+
336
+ ### `mongoSource: collections must be a list of names or a function`
337
+
338
+ **When:** `mongoSource({ db, collections })` with a single string, or a list
339
+ holding something other than strings.
340
+ **Why:** `collections` is either the names to back up, or a test on each
341
+ name; a lone string is refused rather than read letter by letter.
342
+ **Fix:**
343
+
344
+ ```ts
345
+ mongoSource({ db, collections: ['orders'] });
346
+ mongoSource({ db, collections: (name) => !name.startsWith('cache.') });
347
+ ```
348
+
349
+ ### `mongoTarget: db must be a MongoDB Db`
350
+
351
+ **When:** `mongoTarget({ db })` with something that is not a driver `Db`.
352
+ **Why:** as for [the source](#mongosource-db-must-be-a-mongodb-db): the
353
+ target writes into one database.
354
+ **Fix:**
355
+
356
+ ```ts
357
+ import { mongoTarget } from '@softistx/mongo-backup';
358
+
359
+ await backups.restore(id, mongoTarget({ db: client.db('shop-restored') }), { identities });
360
+ ```
361
+
362
+ ### `mongoTarget: tmpDir must be an absolute path`
363
+
364
+ **When:** `mongoTarget({ db, tmpDir })` with a relative path.
365
+ **Why:** each `changes/<n>` entry of an incremental or differential backup
366
+ is staged to a file in `tmpDir` until it has been read and checked to its
367
+ end, then applied; a relative path would depend on the folder the job was
368
+ started from.
369
+ **Fix:** an absolute path on a disk with room for the largest `changes`
370
+ entry — or leave `tmpDir` out for the system's temporary folder.
371
+
372
+ ```ts
373
+ import { join } from 'node:path';
374
+
375
+ mongoTarget({ db, tmpDir: join(import.meta.dir, 'tmp') });
376
+ ```
377
+
378
+ ## The key file
379
+
380
+ `mongoBackups` reads every key it needs from one file, written by
381
+ `nxgt-mongo-backup keygen`. It reads it at the first call that needs it —
382
+ `run`, `restore`, `drill`, `list` or `binding` — and not in
383
+ `mongoBackups(…)` itself. A read that failed is tried again at the next
384
+ call, so a file put right needs no restart.
385
+
386
+ ### `usage: nxgt-mongo-backup keygen <path>`
387
+
388
+ **Exit code:** 2; nothing was written.
389
+ **When:** `nxgt-mongo-backup` run without a command, with a command other
390
+ than `keygen`, or with `keygen` and no path.
391
+ **Why:** the bin has one command, and it takes the path of the file to
392
+ write.
393
+ **Fix:**
394
+
395
+ ```sh
396
+ bunx nxgt-mongo-backup keygen /etc/backup/shop.key
397
+ ```
398
+
399
+ A relative path is taken from the current folder. The command prints the
400
+ path, and the recipient — the public half; never a secret.
401
+
402
+ ### `<path> is already there: it is never overwritten`
403
+
404
+ **Exit code:** 1; the file there is untouched.
405
+ **When:** `nxgt-mongo-backup keygen <path>` on a path that already holds a
406
+ file — a second run of a setup script, say.
407
+ **Why:** every backup is encrypted to the key in that file and signed with
408
+ it; writing a new one over it would make every backup made with it
409
+ unreadable.
410
+ **Fix:** keep the file there — it is the one the job reads — or write the
411
+ new one to another path.
412
+
413
+ ```sh
414
+ bunx nxgt-mongo-backup keygen /etc/backup/shop-2.key
415
+ ```
416
+
417
+ Retire an old key file only once no backup made with it is kept, and keep
418
+ its copy away from the backups until then.
419
+
420
+ ### `keygen failed: <message>`
421
+
422
+ **Exit code:** 1.
423
+ **When:** `nxgt-mongo-backup keygen <path>` could not write the file for
424
+ any reason other than one already there: a folder that does not exist, one
425
+ you cannot write to, a full disk. `<message>` is the system's, such as
426
+ `ENOENT: no such file or directory, open '/etc/backup/shop.key'`.
427
+ **Why:** the file and its folder are written and synced before the command
428
+ says it is done; a write that fails halfway removes the file it created,
429
+ so nothing half-written is left at the path.
430
+ **Fix:** make the folder, or run as a user who can write to it, and run the
431
+ same command again — it is not refused as already there.
432
+
433
+ ```sh
434
+ mkdir -p /etc/backup && bunx nxgt-mongo-backup keygen /etc/backup/shop.key
435
+ ```
436
+
437
+ ### `mongoBackups on "app": there is no key file there; write one with nxgt-mongo-backup keygen`
438
+
439
+ **Code:** `KEY_FILE`; the file system's `ENOENT` is its `cause`, and it
440
+ names the path, never a key. Called directly, `readKeyFile` says
441
+ `readKeyFile: there is no key file there; …`. Any other failure to open
442
+ the file — `EACCES`, `ENOTDIR` — is the system's error, as it is.
443
+ **When:** the first `run`, `restore`, `drill`, `list` or `binding` of a
444
+ `mongoBackups` whose `keyFile` is not there: a typo, a secret not mounted
445
+ yet, a file written on another machine.
446
+ **Why:** `mongoBackups(…)` only checks that the path is absolute; the file
447
+ is read when a key is first needed. The failed read is not kept: the next
448
+ call reads the file again.
449
+ **Fix:** write it there once, or point `keyFile` at the one you have.
450
+
451
+ ```sh
452
+ bunx nxgt-mongo-backup keygen /etc/backup/shop.key
453
+ ```
454
+
455
+ If backups were already made, do not write a new file in place of a lost
456
+ one — it cannot read them. Put back the copy kept away from the backups.
457
+
458
+ ### `mongoBackups on "app": others than its owner can read or write the key file; chmod 600 it`
459
+
460
+ **Code:** `KEY_FILE`. Called directly, `readKeyFile` says
461
+ `readKeyFile: others than its owner can read or write the key file; …`.
462
+ **When:** the first call that reads the key file, when its mode gives
463
+ anything to its group or to others — reading, or writing: a copy made under a loose `umask`, a
464
+ file put there by a deployment tool, a mounted secret with its default
465
+ mode.
466
+ **Why:** the file holds the key that decrypts every backup and the one that
467
+ signs them, so — as `ssh` does with a private key — it is refused rather
468
+ than used while others can read it, or write a key of their own into
469
+ it. `keygen` writes it with mode `600`.
470
+ **Fix:**
471
+
472
+ ```sh
473
+ chmod 600 /etc/backup/shop.key
474
+ ```
475
+
476
+ For a mounted secret, give it mode `0400` or `0600` where it is mounted.
477
+
478
+ ### `mongoBackups on "app": the key file is not one keygen wrote`
479
+
480
+ **Code:** `KEY_FILE`, without a `cause`: the parsers' own errors quote the
481
+ key. Called directly, `readKeyFile` says
482
+ `readKeyFile: the key file is not one keygen wrote`.
483
+ **When:** the first call that reads the key file, when it holds no age
484
+ identity (`AGE-SECRET-KEY-1…`) or no Ed25519 private key in PEM
485
+ (`-----BEGIN PRIVATE KEY-----`), or one that does not parse: the wrong
486
+ file, an `age-keygen` identity alone, a public key, a file cut short, an
487
+ identity with a character changed (its checksum fails), an RSA or other
488
+ private key where the Ed25519 one should be — or one whose line
489
+ endings became `\r\n` on its way through an editor or a secret store.
490
+ **Why:** one file gives both keys: the identity backups are encrypted to and
491
+ read with, and the key their manifests are signed with.
492
+ **Fix:** use the file `keygen` wrote, as it wrote it — or, before any backup
493
+ was made, write a new one.
494
+
495
+ ```sh
496
+ bunx nxgt-mongo-backup keygen /etc/backup/shop.key
497
+ ```
498
+
499
+ ## Choosing the backup to restore
500
+
501
+ `mongoBackups`' `restore` takes the backup `at` names — an id as it is, a
502
+ time as the newest backup made at or before it, nothing as the newest of
503
+ all — and `drill` takes the newest.
504
+
505
+ ### `restore on "app": the repository holds no backup yet`
506
+
507
+ **Code:** `NOT_FOUND`; nothing was read from the repository but its list.
508
+ `app` is the backup's name: `name`, or the database's name by default.
509
+ **When:** `restore` without `at` before the first `run` — or
510
+ on a repository other than the one the job writes to, or under another
511
+ `name`: the backup's name is the database's by default.
512
+ **Why:** with no `at`, the newest backup is restored, and there is none.
513
+ **Fix:** make one first — or check that `repository` and `name` are the
514
+ job's.
515
+
516
+ ```ts
517
+ await backups.run();
518
+ await backups.restore({ into: client.db('shop-restored') });
519
+ ```
520
+
521
+ ### `drill on "app": the repository holds no backup yet`
522
+
523
+ **Code:** `NOT_FOUND`; nothing was restored, and no drill database made.
524
+ **When:** `drill` before the first `run`, or on another repository or
525
+ `name` than the job's.
526
+ **Why:** a drill restores the newest backup, and there is none.
527
+ **Fix:** as for
528
+ [`restore`](#restore-on-app-the-repository-holds-no-backup-yet): run the
529
+ job first, or check `repository` and `name`. A scheduled drill that starts
530
+ before the first backup fails this way once.
531
+
532
+ ```ts
533
+ await backups.run();
534
+ await backups.drill();
535
+ ```
536
+
537
+ ### `restore on "app": no backup was made at or before that time`
538
+
539
+ **Code:** `NOT_FOUND`; nothing was read from the repository but its list.
540
+ **When:** `restore({ into, at })` with a `Date` older than every backup the
541
+ repository still holds: one from before the first backup, one the rotation
542
+ of `keep` has pruned since, or a `Date` parsed from a string in another
543
+ time zone than meant.
544
+ **Why:** a time picks the newest backup made at or before it, and none
545
+ was. A later one is never taken in its place: it would hold changes made
546
+ after the time asked for.
547
+ **Fix:** list what is kept, and restore by id — the oldest, if it will do.
548
+
549
+ ```ts
550
+ const [oldest] = await backups.list(); // oldest first
551
+ if (oldest) await backups.restore({ into: client.db('shop-restored'), at: oldest.id });
552
+ ```
553
+
554
+ ### `restore on "app": into must be a MongoDB Db`
555
+
556
+ **Code:** none — a `TypeError`; `restore` rejects with it before reading
557
+ anything, the key file included.
558
+ **When:** `restore({ into })` with a database name, a `MongoClient`, or
559
+ nothing.
560
+ **Why:** `into` is the database the backup lands in, and must be the
561
+ driver's `Db`.
562
+ **Fix:**
563
+
564
+ ```ts
565
+ await backups.restore({ into: client.db('shop-restored') });
566
+ ```
567
+
568
+ ### `restore on "app": at must be a backup's id or a valid Date`
569
+
570
+ **Code:** none — a `TypeError`; `restore` rejects with it before reading
571
+ anything, the key file included.
572
+ **When:** `restore({ into, at })` with a `Date` that is not a time —
573
+ `new Date('yesterday')`, say — usually parsed from user input or an
574
+ environment variable.
575
+ **Why:** an invalid `Date` is no time at all; taken as one, it would pick
576
+ a backup nobody asked for.
577
+ **Fix:** check the date before the restore, or pass the id `list` gives.
578
+
579
+ ```ts
580
+ const at = new Date(Bun.env['RESTORE_AT'] ?? '');
581
+ if (Number.isNaN(at.getTime())) throw new Error('RESTORE_AT is not a date');
582
+ await backups.restore({ into: client.db('shop-restored'), at });
583
+ ```
584
+
585
+ ### `restore on "app": replace is for whole collections; documents says what happens to those there`
586
+
587
+ **Code:** none — a `TypeError`; `restore` rejects with it before reading
588
+ anything. The types refuse it first: with `documents`, `replace` is
589
+ `never`.
590
+ **When:** `restore({ into, documents, replace })` — both at once.
591
+ **Why:** `replace` swaps whole collections already there; `documents`
592
+ merges some documents into them, and its `existing` already says what
593
+ happens to a document there.
594
+ **Fix:** keep one of the two.
595
+
596
+ ```ts
597
+ await backups.restore({
598
+ into: client.db('shop'),
599
+ collections: ['orders'],
600
+ documents: { filter: { _id: 'o-1001' }, existing: 'replace' }, // the documents, not the collection
601
+ });
602
+ ```
603
+
604
+ ## Full backups
605
+
606
+ A full backup reads every collection in one snapshot session: one cluster
607
+ time for the whole database.
608
+
609
+ ### `mongoSource: the server gave no snapshot time; a backup needs a replica set or a sharded cluster`
610
+
611
+ **Code:** `UNSUPPORTED`.
612
+ **When:** a full `create`, before any entry is read.
613
+ **Why:** the backup reads every collection at one cluster time with a
614
+ snapshot session, and records that time so the next incremental backup can
615
+ start its change stream just after it. A standalone `mongod` has no cluster
616
+ time, no snapshot reads and no change stream. The server may refuse the
617
+ snapshot read itself first, with an error of its own; the cause is the same.
618
+ **Fix:** run MongoDB as a replica set — a single member is enough — and
619
+ connect to it as one.
620
+
621
+ ```sh
622
+ mongod --replSet rs0 --dbpath /data/db
623
+ mongosh --eval 'rs.initiate()'
624
+ ```
625
+
626
+ ```ts
627
+ const client = await MongoClient.connect('mongodb://localhost:27017/?replicaSet=rs0');
628
+ ```
629
+
630
+ ### `mongoSource: a collection named in collections is not in the database`
631
+
632
+ **Code:** none — a `TypeError`, as `create`'s rejection.
633
+ **When:** a full `create` with `collections: [...]` listing a name the
634
+ database does not hold: a typo, a collection not created yet, or the wrong
635
+ database.
636
+ **Why:** a backup of a name that is not there would back up nothing, and
637
+ say nothing. `system.*` collections are never taken, so naming one is
638
+ refused the same way.
639
+ **Fix:** name collections that exist — or pass a function, which takes what
640
+ it matches and refuses nothing.
641
+
642
+ ```ts
643
+ mongoSource({ db, collections: (name) => ['orders', 'customers'].includes(name) });
644
+ ```
645
+
646
+ ### `mongoSource: a collection is of a type this version does not back up (a time-series one); leave it out with collections`
647
+
648
+ **Code:** `UNSUPPORTED`.
649
+ **When:** a full `create` on a database holding a time-series collection
650
+ that `collections` takes — every one, by default. Or an incremental or
651
+ differential `create` whose change stream holds the creation of a
652
+ time-series collection since the backup it builds on.
653
+ **Why:** this version backs up collections and views; it neither reads nor
654
+ restores a time-series collection, and refuses rather than leave it out
655
+ without saying so.
656
+ **Fix:** leave it out, and back it up another way.
657
+
658
+ ```ts
659
+ mongoSource({ db, collections: (name) => name !== 'metrics' });
660
+ ```
661
+
662
+ For an incremental backup too, leaving it out is enough: the change stream
663
+ passes over a collection `collections` leaves out before translating its
664
+ events, so
665
+ the next incremental with the new filter goes past the creation.
666
+
667
+ ### `mongoSource: the collections or their indexes kept changing while the snapshot was taken; try again when they settle`
668
+
669
+ **Code:** `CHANGING`; nothing was stored.
670
+ **When:** a full `create`, while collections the filter takes are created,
671
+ dropped or renamed, or their indexes or options change, without pause — a
672
+ migration, an index build, an application making temporary collections.
673
+ **Why:** the server does not list collections or indexes at a cluster time,
674
+ so a full backup reads them before pinning its snapshot and again after,
675
+ and keeps them only when both agree: then they are the snapshot's. It
676
+ retakes the pin up to five times before giving up, rather than store
677
+ metadata the documents might break — a unique index built in the gap would
678
+ make the backup impossible to restore.
679
+ **Fix:** run the backup once the migration or index build is over, or
680
+ retry after a pause.
681
+
682
+ ```ts
683
+ import { MongoBackupError } from '@softistx/mongo-backup';
684
+
685
+ for (let attempt = 1; ; attempt++) {
686
+ try {
687
+ await backups.create(mongoSource({ db }));
688
+ break;
689
+ } catch (error) {
690
+ if (!(error instanceof MongoBackupError && error.code === 'CHANGING') || attempt === 3) throw error;
691
+ await Bun.sleep(60_000);
692
+ }
693
+ }
694
+ ```
695
+
696
+ ### `mongoSource: the snapshot outlived the history the server keeps; raise minSnapshotHistoryWindowInSeconds, or back up fewer collections at a time`
697
+
698
+ **Code:** `SNAPSHOT_TOO_OLD`; the server's error is its `cause`.
699
+ **When:** a full `create` on a large database, partway through: the read of
700
+ one collection's documents fails some minutes after the backup started.
701
+ **Why:** every collection is read at the cluster time the backup started,
702
+ and the server keeps the history needed to read at that time for
703
+ `minSnapshotHistoryWindowInSeconds` only — 300 seconds by default. A
704
+ backup that takes longer, or a slow repository, outlives it.
705
+ **Fix:** raise the window on every member of the replica set, for as long
706
+ as a full backup takes — it costs cache and disk while a snapshot is open:
707
+
708
+ ```ts
709
+ await client.db('admin').command({ setParameter: 1, minSnapshotHistoryWindowInSeconds: 3600 });
710
+ ```
711
+
712
+ Or split the database into several backups, each with its own
713
+ `collections` — each is consistent in itself, but not with the others.
714
+
715
+ ## Incremental and differential backups
716
+
717
+ An incremental or differential backup reads the change stream from the
718
+ position the backup it builds on recorded, into one `changes/<n>` entry;
719
+ the entries of the backup it builds on are not read again.
720
+
721
+ ### `create on "app": no backup to build on (repository "local")`
722
+
723
+ **Code:** `BackupError` from `@softistx/backup`, `NOT_FOUND`; nothing was read
724
+ from the database. For a differential, the message is
725
+ `create on "app": no full backup to build on (repository "local")`.
726
+ **When:** the first incremental or differential `create` of a definition —
727
+ or after every backup of it was pruned or is unreadable.
728
+ **Why:** an incremental backup stores what changed since another backup,
729
+ and a full one is never made in its place without being asked for.
730
+ **Fix:** make a full backup first, or fall back to one in the job.
731
+
732
+ ```ts
733
+ import { BackupError } from '@softistx/backup';
734
+
735
+ try {
736
+ await backups.create(source, { kind: 'incremental', identities });
737
+ } catch (error) {
738
+ if (!(error instanceof BackupError && error.code === 'NOT_FOUND')) throw error;
739
+ await backups.create(source); // the first one: full
740
+ }
741
+ ```
742
+
743
+ ### `create on "app": the source is not of the kind the backup it builds on was made from`
744
+
745
+ **Code:** a `TypeError` from `@softistx/backup`; nothing was read from the
746
+ database.
747
+ **When:** an incremental or differential `create` with `mongoSource`, on a
748
+ definition whose last backup came from another source — a
749
+ `directorySource` of `mongodump`'s output, say.
750
+ **Why:** a backup from `mongoSource` is of kind `mongo`, and an incremental
751
+ one only builds on a backup of the same kind.
752
+ **Fix:** a definition of its own for the database, starting with a full
753
+ backup.
754
+
755
+ ```ts
756
+ const database = bindBackup(defineBackup({ name: 'shop-db' }), { repositories, recipients });
757
+ await database.create(mongoSource({ db }));
758
+ ```
759
+
760
+ ### `mongoSource: the server gave no operation time; a backup needs a replica set or a sharded cluster`
761
+
762
+ **Code:** `UNSUPPORTED`.
763
+ **When:** an incremental or differential `create`, before the change stream
764
+ is opened.
765
+ **Why:** the backup reads the change stream up to the cluster's operation
766
+ time at its start, and a standalone server gives none — nor a change
767
+ stream.
768
+ **Fix:** as for [a full backup](#mongosource-the-server-gave-no-snapshot-time-a-backup-needs-a-replica-set-or-a-sharded-cluster):
769
+ a replica set, a single member being enough.
770
+
771
+ ```ts
772
+ const client = await MongoClient.connect('mongodb://localhost:27017/?replicaSet=rs0');
773
+ ```
774
+
775
+ ### `mongoSource: the backup built on recorded no position this version reads; make a full backup`
776
+
777
+ **Code:** `MALFORMED`.
778
+ **When:** an incremental or differential `create`, before the change stream
779
+ is opened.
780
+ **Why:** the backup it builds on recorded no position, or one this version
781
+ did not write: it was made by another source declaring the kind `mongo`,
782
+ or by a later version of this package whose position this one does not
783
+ read.
784
+ **Fix:** a full backup, then incrementals from it.
785
+
786
+ ```ts
787
+ await backups.create(mongoSource({ db }));
788
+ ```
789
+
790
+ ### `mongoSource: the change stream cannot resume where the last backup stopped: the oplog no longer reaches back there; make a full backup`
791
+
792
+ **Code:** `HISTORY_LOST`; the server's error is its `cause`.
793
+ **When:** an incremental or differential `create`, as the change stream is
794
+ opened.
795
+ **Why:** a change stream is read from the oplog, which is a capped
796
+ collection: once more was written since the last backup than the oplog
797
+ holds, the position it recorded is gone, and the changes since cannot be
798
+ read. The longer between backups, and the busier the database, the sooner.
799
+ **Fix:** make a full backup — every incremental after it works again — and
800
+ then either back up more often or keep more oplog.
801
+
802
+ ```ts
803
+ import { MongoBackupError } from '@softistx/mongo-backup';
804
+
805
+ try {
806
+ await backups.create(source, { kind: 'incremental', identities });
807
+ } catch (error) {
808
+ if (!(error instanceof MongoBackupError && error.code === 'HISTORY_LOST')) throw error;
809
+ await backups.create(source); // full: the chain starts again here
810
+ }
811
+ ```
812
+
813
+ With `mongoBackups`, `run()` does this by itself: when an incremental was
814
+ due and fails with `HISTORY_LOST`, it makes a full backup instead and
815
+ reports `fellBack: true`. Watch for it — it means the oplog is shorter than
816
+ the time between runs.
817
+
818
+ ```ts
819
+ const report = await backups.run();
820
+ if (report.fellBack) console.warn('backup: the oplog no longer reached the last backup; made a full one');
821
+ ```
822
+
823
+ To keep more oplog, on each member — the size in megabytes, or a minimum
824
+ retention in hours:
825
+
826
+ ```ts
827
+ await client.db('admin').command({ replSetResizeOplog: 1, size: 51200 });
828
+ await client.db('admin').command({ replSetResizeOplog: 1, minRetentionHours: 48 });
829
+ ```
830
+
831
+ ### `mongoSource: 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`
832
+
833
+ **Code:** `UNSUPPORTED`.
834
+ **When:** an incremental or differential `create`, when the change stream
835
+ holds an update to a field whose name holds a `.` or is all digits —
836
+ `'price.eur'`, `'2026'` — in a collection the chain follows: those of its
837
+ full backup, and those created since that `collections` takes. One it does
838
+ not follow is passed over before its events are translated; narrowing
839
+ `collections` mid-chain changes that only from the next full backup.
840
+ **Why:** for such an update the server describes the change with paths it
841
+ cannot tell apart from nested fields or array indexes, so it cannot be
842
+ replayed as written. With the collection's post-images on, the change
843
+ stream gives the whole document after the update, and the backup records
844
+ that instead.
845
+ **Fix:** turn post-images on for that collection, then make a full backup —
846
+ the update already in the change stream has no post-image, so every
847
+ incremental from the old position fails on it.
848
+
849
+ ```ts
850
+ await db.command({ collMod: 'orders', changeStreamPreAndPostImages: { enabled: true } });
851
+ await backups.create(mongoSource({ db }));
852
+ ```
853
+
854
+ Turning them on makes the server keep a copy of each document as it was
855
+ before an update, which costs writes and storage.
856
+
857
+ ### `mongoSource: the collections created, renamed or dropped since the full backup are too many to record; make a full backup`
858
+
859
+ **Code:** `UNSUPPORTED`; the incremental is not stored.
860
+ **When:** an incremental or differential `create`, at the end of its
861
+ changes, once the collections created, renamed or dropped since the chain's
862
+ full backup no longer fit in a position — 64 KiB, `@softistx/backup`'s limit:
863
+ some thousands of names.
864
+ **Why:** the position records how the collections the chain follows differ
865
+ from those of its full backup, and each incremental carries that difference
866
+ on. An application that makes and drops collections all the time — one
867
+ per tenant, per day — makes it grow until the next full backup.
868
+ **Fix:** make a full backup: the difference starts again from nothing.
869
+
870
+ ```ts
871
+ await backups.create(mongoSource({ db }));
872
+ ```
873
+
874
+ ### `mongoSource: a collection was renamed into those backed up, with documents an incremental backup never read; make a full backup`
875
+
876
+ **Code:** `UNSUPPORTED`.
877
+ **When:** an incremental or differential `create`, when a collection the
878
+ chain does not follow was renamed to a name the filter takes — a collection
879
+ left out by `collections`, one a wider filter would take only from the next
880
+ full backup, the `nxgt-restore-<uuid>` collections of a restore into the
881
+ database backed up, or the `tmpXXXXX.renameCollection` collection through
882
+ which the server moves one a whole `restoreCollections` lands there, when
883
+ the chain's filter does not take that name — a list never does.
884
+ **Why:** the documents of a collection not followed were never read, so the
885
+ change stream cannot give them, and a restore could not bring them back. A rename the other way — out of those backed up — is recorded as a
886
+ drop, and a rename between two names taken is replayed.
887
+ **Fix:** make a full backup; the incrementals after it read from there.
888
+
889
+ ```ts
890
+ await backups.create(mongoSource({ db, collections: (name) => name.startsWith('orders') }));
891
+ ```
892
+
893
+ ### `mongoSource: an entry of the backup built on was asked for again; it has no fingerprint, so make a full backup`
894
+
895
+ **Code:** `MALFORMED`.
896
+ **When:** an incremental or differential `create`, as `@softistx/backup` goes
897
+ through the entries of the backup it builds on.
898
+ **Why:** those entries are never read again: `@softistx/backup` keeps each one
899
+ whose fingerprint is the one recorded, and every entry `mongoSource` writes
900
+ has one. An entry recorded without a fingerprint was written by another
901
+ source declaring the kind `mongo`, so this one cannot give it again.
902
+ **Fix:** a full backup with `mongoSource`, then incrementals from it.
903
+
904
+ ```ts
905
+ await backups.create(mongoSource({ db }));
906
+ ```
907
+
908
+ ## Restoring
909
+
910
+ `mongoTarget` takes the entries in the order the backup holds them: each
911
+ collection's `metadata/<name>`, then its `documents/<name>`, then the
912
+ `changes/<n>` of each incremental in the chain. A collection lands whole or
913
+ not at all; the collections before it in the backup stay restored.
914
+
915
+ ### `mongoTarget: a collection or view the backup holds is already in the database; restore into another one, or pass replace: true`
916
+
917
+ **Code:** `EXISTS`.
918
+ **When:** `restore` into a database that already holds a collection or view
919
+ of the same name — the database the backup was made from, or one a first
920
+ restore already filled. Also when the `changes` of an incremental backup
921
+ create a collection that is there, or replay a rename onto a name that is
922
+ taken, where the rename at the source replaced nothing. A rename that did
923
+ replace a collection at the source replaces it here too.
924
+ **Why:** a restore never writes over data without being asked to: the
925
+ collection there is left untouched, and the one from the backup is not
926
+ created.
927
+ **Fix:** restore into an empty database, or replace what is there — each
928
+ collection the backup holds is dropped and created anew, the others are
929
+ left as they are.
930
+
931
+ ```ts
932
+ await backups.restore(id, mongoTarget({ db: client.db('shop-restored') }), { identities });
933
+ await backups.restore(id, mongoTarget({ db, replace: true }), { identities });
934
+ ```
935
+
936
+ After a refusal partway through a restore, drop the database before
937
+ restoring again without `replace`: the collections before the refused one
938
+ were restored.
939
+
940
+ ### `mongoTarget: an entry name is not one this version writes`
941
+
942
+ **Code:** `MALFORMED`.
943
+ **When:** `restore` with `mongoTarget`, at the first entry whose name is
944
+ not `metadata/<collection>`, `documents/<collection>` or `changes/<n>`.
945
+ **Why:** the backup was not made by `mongoSource` — a `directorySource`
946
+ backup restored into a database, say — or by a later version with entries
947
+ this one does not know.
948
+ **Fix:** restore a backup of `mongoSource` into `mongoTarget`, and any other
949
+ into the target of its kind.
950
+
951
+ ```ts
952
+ import { directoryTarget } from '@softistx/backup';
953
+
954
+ await files.restore(id, directoryTarget({ path: '/srv/restore' }), { identities });
955
+ ```
956
+
957
+ ### `mongoTarget: a collection’s documents came before its metadata`
958
+
959
+ **Code:** `MALFORMED`.
960
+ **When:** `restore` with `only`, when it picks `documents/<collection>`
961
+ without `metadata/<collection>`.
962
+ **Why:** a collection is created from its metadata — its options,
963
+ validator, collation and indexes — before its documents land; without it,
964
+ the documents have nowhere to go.
965
+ **Fix:** take both entries of each collection. This is for a full backup:
966
+ the `changes` of an incremental one may touch any collection, so restore it
967
+ whole.
968
+
969
+ ```ts
970
+ const wanted = new Set(['orders', 'customers']);
971
+ await backups.restore(id, mongoTarget({ db }), {
972
+ identities,
973
+ only: (name) => wanted.has(name.slice(name.indexOf('/') + 1)),
974
+ });
975
+ ```
976
+
977
+ ### `mongoTarget: a metadata entry is not one this version wrote`
978
+
979
+ **Code:** `MALFORMED`.
980
+ **When:** `restore`, at a `metadata/<collection>` entry.
981
+ **Why:** its content is not the options and indexes `mongoSource` writes,
982
+ as Extended JSON — the backup came from another source, or from a later
983
+ version of this package.
984
+ **Fix:** restore it with the version that made it, or a later one.
985
+
986
+ ```sh
987
+ bun add @softistx/mongo-backup@latest
988
+ ```
989
+
990
+ ### `mongoTarget: a metadata entry is larger than 16 MiB`
991
+
992
+ **Code:** `MALFORMED`.
993
+ **When:** `restore`, at a `metadata/<collection>` entry.
994
+ **Why:** a metadata entry holds a collection's options and indexes, never
995
+ its documents; none `mongoSource` writes comes near 16 MiB, so one that
996
+ does was not written by it.
997
+ **Fix:** check the backup is one of `mongoSource`, and that it is whole.
998
+
999
+ ```ts
1000
+ await backups.verify(id, { identities });
1001
+ ```
1002
+
1003
+ ### `mongoTarget: an entry is not a sequence of BSON documents`
1004
+
1005
+ **Code:** `MALFORMED`.
1006
+ **When:** `restore`, while a `documents/<collection>` or `changes/<n>` entry
1007
+ is read. For `documents`, the collection being restored is dropped and
1008
+ nothing of it lands; for `changes`, those before the damaged point were
1009
+ applied.
1010
+ **Why:** the bytes are not BSON documents one after the other, as
1011
+ `mongodump` writes them: the entry was not written by `mongoSource`, or it
1012
+ was damaged on the way — in which case `@softistx/backup`'s own integrity check
1013
+ may report it first.
1014
+ **Fix:** verify the backup with its keys: it checks every entry against
1015
+ what the source gave.
1016
+
1017
+ ```ts
1018
+ const verified = await backups.verify(id, { identities });
1019
+ ```
1020
+
1021
+ ### `mongoTarget: a change is not one this version wrote`
1022
+
1023
+ **Code:** `MALFORMED`.
1024
+ **When:** `restore` of an incremental or differential backup, at its
1025
+ `changes/<n>` entry; the changes before that one in the entry were
1026
+ applied.
1027
+ **Why:** the entry holds BSON documents, but not the change records
1028
+ `mongoSource` writes — it came from another source, or from a later
1029
+ version of this package.
1030
+ **Fix:** restore it with the version that made it, or a later one.
1031
+
1032
+ ```sh
1033
+ bun add @softistx/mongo-backup@latest
1034
+ ```
1035
+
1036
+ ## Restoring some collections
1037
+
1038
+ `restoreCollections(backups, id, options)` rebuilds the backup, chain
1039
+ included, in a scratch database, takes from it what `collections` names,
1040
+ moves it into `db` — whole, or only the documents `documents` selects —
1041
+ then drops the scratch database, failed or not — save one you passed that
1042
+ was not empty, which is refused and left as it was. Of the errors below,
1043
+ only the last one may leave something in `db`.
1044
+
1045
+ `mongoBackups`' `restore` goes through it for a partial restore —
1046
+ `collections`, `as` or `documents` — and its messages then name that call
1047
+ and the backup instead: `restore on "app": as names a collection not
1048
+ restored` where the heading says `restoreCollections: as names a
1049
+ collection not restored`. Search for the part after the colon.
1050
+
1051
+ ### `restoreCollections: db must be a MongoDB Db`
1052
+
1053
+ **Code:** none — a `TypeError`; nothing was read.
1054
+ **When:** `restoreCollections` with a `db` that is not a driver `Db` — a
1055
+ `MongoClient`, a database name, or `undefined`.
1056
+ **Why:** the collections are moved into one database, and the scratch one
1057
+ is made on its client.
1058
+ **Fix:** give the database, not the client.
1059
+
1060
+ ```ts
1061
+ import { restoreCollections } from '@softistx/mongo-backup';
1062
+
1063
+ await restoreCollections(backups, id, { identities, db: client.db('shop') });
1064
+ ```
1065
+
1066
+ ### `restoreCollections: scratch must be a MongoDB Db`
1067
+
1068
+ **Code:** none — a `TypeError`; nothing was read.
1069
+ **When:** `restoreCollections` with a `scratch` that is not a driver `Db`,
1070
+ such as a database name.
1071
+ **Why:** `scratch` is where the backup is rebuilt, and it is dropped
1072
+ afterwards; it must be a database on `db`'s client.
1073
+ **Fix:** pass a `Db` — or leave `scratch` out for a fresh
1074
+ `nxgt-restore-<uuid>` on `db`'s client.
1075
+
1076
+ ```ts
1077
+ await restoreCollections(backups, id, { identities, db, scratch: client.db('restore-scratch') });
1078
+ ```
1079
+
1080
+ ### `restoreCollections: scratch must be on db's client`
1081
+
1082
+ **Code:** none — a `TypeError`; nothing was read.
1083
+ **When:** `restoreCollections` with a `scratch` from another `MongoClient`
1084
+ than `db`'s — even one connected to the same deployment.
1085
+ **Why:** collections move out of the scratch database with a rename across
1086
+ databases, and documents with a `$merge`; both run on the scratch's client
1087
+ and name `db` there. From another server, documents would land in a
1088
+ database of that name on the wrong cluster, and the restore would look
1089
+ like it worked.
1090
+ **Fix:** take both from one client — or leave `scratch` out.
1091
+
1092
+ ```ts
1093
+ await restoreCollections(backups, id, { identities, db: client.db('shop'), scratch: client.db('shop-scratch') });
1094
+ ```
1095
+
1096
+ ### `restoreCollections: scratch must be another database`
1097
+
1098
+ **Code:** none — a `TypeError`; nothing was read.
1099
+ **When:** `restoreCollections` with a `scratch` whose name is `db`'s.
1100
+ **Why:** the scratch database is dropped when the restore ends, so it can
1101
+ never be the database restored into.
1102
+ **Fix:** a database of its own, or none.
1103
+
1104
+ ```ts
1105
+ await restoreCollections(backups, id, { identities, db: client.db('shop'), scratch: client.db('shop-scratch') });
1106
+ ```
1107
+
1108
+ ### `restoreCollections: documents must be { filter, existing: 'replace' | 'keep' }`
1109
+
1110
+ **Code:** none — a `TypeError`; nothing was read.
1111
+ **When:** `restoreCollections` with a `documents` whose `filter` is not a
1112
+ query object — an array, a string — or whose `existing` is neither
1113
+ `'replace'` nor `'keep'`, or is left out.
1114
+ **Why:** a document of the backup whose `_id` is already in the collection
1115
+ either replaces it or is dropped, and the restore does not pick for you.
1116
+ **Fix:**
1117
+
1118
+ ```ts
1119
+ await restoreCollections(backups, id, {
1120
+ identities,
1121
+ db,
1122
+ collections: ['orders'],
1123
+ documents: { filter: { customer: customerId }, existing: 'keep' },
1124
+ });
1125
+ ```
1126
+
1127
+ ### `restoreCollections: replace is for whole collections; documents says what happens to those there`
1128
+
1129
+ **Code:** none — a `TypeError`; nothing was read.
1130
+ **When:** `restoreCollections` with both `documents` and `replace`.
1131
+ **Why:** with `documents`, the selected documents are merged into the
1132
+ collection there, and `documents.existing` already says what happens to
1133
+ one with the same `_id`; `replace` drops and moves whole collections.
1134
+ **Fix:** one or the other.
1135
+
1136
+ ```ts
1137
+ await restoreCollections(backups, id, { identities, db, documents: { filter: {}, existing: 'replace' } });
1138
+ await restoreCollections(backups, id, { identities, db, replace: true });
1139
+ ```
1140
+
1141
+ ### `restoreCollections: the scratch database holds collections; give an empty one`
1142
+
1143
+ **Code:** `EXISTS`; nothing was read, and the scratch database was left as
1144
+ it was.
1145
+ **When:** `restoreCollections` with a `scratch` that holds a collection or
1146
+ view — a database in use, or the scratch of an earlier run that was killed
1147
+ before it could drop it.
1148
+ **Why:** the scratch database is dropped when the restore ends; a database
1149
+ holding something might be one that should not be.
1150
+ **Fix:** check what it holds, drop it if it is only a leftover, or give
1151
+ another — or leave `scratch` out.
1152
+
1153
+ ```ts
1154
+ const scratch = client.db('restore-scratch');
1155
+ await scratch.dropDatabase(); // only once you know nothing in it is needed
1156
+ await restoreCollections(backups, id, { identities, db, scratch });
1157
+ ```
1158
+
1159
+ ### `restoreCollections: a collection named in collections is not in the backup`
1160
+
1161
+ **Code:** `NOT_FOUND`; nothing landed in `db`.
1162
+ **When:** `restoreCollections` with `collections: [...]` listing a name the
1163
+ backup does not hold, once the backup has been rebuilt in the scratch
1164
+ database: a typo, a collection created after the backup, or one left out
1165
+ of it by `mongoSource`'s `collections`.
1166
+ **Why:** names are the backup's, as they were at the time of the backup
1167
+ `id` — after every rename the chain's incremental backups recorded. A
1168
+ collection renamed since the full backup is named by its new name; one
1169
+ renamed after the backup `id`, by its old one. Restoring nothing for a
1170
+ name, without saying so, would look like success.
1171
+ **Fix:** name collections as they were at the backup's time — or pass a
1172
+ function, which takes what it matches and refuses nothing.
1173
+
1174
+ ```ts
1175
+ await restoreCollections(backups, id, {
1176
+ identities,
1177
+ db,
1178
+ collections: (name) => ['orders', 'customers'].includes(name),
1179
+ });
1180
+ ```
1181
+
1182
+ ### `restoreCollections: as must give a collection name`
1183
+
1184
+ **Code:** none — a `TypeError`; nothing landed in `db`.
1185
+ **When:** `restoreCollections` with an `as` that gives, for one of the
1186
+ collections restored, something other than a string, an empty string, a
1187
+ name holding `$` or a NUL character, or a name starting with `system.`.
1188
+ An `as` map is checked before the backup is read; a function, once the
1189
+ backup has been rebuilt in the scratch database and the names are known.
1190
+ **Why:** MongoDB refuses those names, or keeps them for itself.
1191
+ **Fix:** a map keyed by names restored — one it does not list keeps its
1192
+ own — or a function that returns a name for every one.
1193
+
1194
+ ```ts
1195
+ await restoreCollections(backups, id, { identities, db, as: { orders: 'orders-restored' } });
1196
+ await restoreCollections(backups, id, { identities, db, as: (name) => `${name}-restored` });
1197
+ ```
1198
+
1199
+ ### `restoreCollections: as gives two collections one name`
1200
+
1201
+ **Code:** none — a `TypeError`; nothing landed in `db`.
1202
+ **When:** `restoreCollections` with an `as` that sends two of the
1203
+ collections or views restored to the same name — a function returning a
1204
+ constant, or a map naming one collection after another that keeps its own.
1205
+ Two keys of an `as` map given one name are refused before the backup is
1206
+ read; a clash with a collection that keeps its own name, and anything a
1207
+ function gives, once the backup has been rebuilt in the scratch database.
1208
+ **Why:** one would land over the other.
1209
+ **Fix:** a name per collection; a suffix or a prefix keeps them apart.
1210
+
1211
+ ```ts
1212
+ await restoreCollections(backups, id, { identities, db, as: (name) => `${name}-restored` });
1213
+ ```
1214
+
1215
+ ### `restoreCollections: as names a collection not restored`
1216
+
1217
+ **Code:** none — a `TypeError`; nothing landed in `db`.
1218
+ **When:** `restoreCollections` with an `as` map whose key names no
1219
+ collection or view restored — a typo, a name `collections` leaves out, a
1220
+ name the backup does not hold at its time, or a view when `documents` is
1221
+ given (views hold no documents, so none is restored). It is checked once
1222
+ the backup has been rebuilt in the scratch database.
1223
+ **Why:** a key that names nothing would leave the collection meant under
1224
+ its own name — so with `documents` and `existing: 'replace'`, or with
1225
+ `replace: true`, over the live one.
1226
+ **Fix:** key the map by the names the backup holds at its time, after
1227
+ any rename its chain recorded.
1228
+
1229
+ ```ts
1230
+ await restoreCollections(backups, id, { identities, db, collections: ['orders'], as: { orders: 'orders-restored' } });
1231
+ ```
1232
+
1233
+ ### `restoreCollections: a collection or view to restore is already in the database; restore it under another name, or pass replace: true`
1234
+
1235
+ **Code:** `EXISTS`.
1236
+ **When:** a whole restore — without `documents` — when a collection or
1237
+ view restored lands on a name `db` already holds: its own name, or the one
1238
+ `as` gives it.
1239
+ **Why:** a restore never writes over data without being asked to. Every
1240
+ name is checked before anything moves, so in the common case nothing
1241
+ landed. A collection created under one of those names between the check
1242
+ and the move is refused as well, and left untouched; the collections moved
1243
+ before it stay restored.
1244
+ **Fix:** restore under another name, replace what is there — each
1245
+ collection or view restored is dropped and moved anew, the others are left
1246
+ as they are — or merge documents into it instead.
1247
+
1248
+ ```ts
1249
+ await restoreCollections(backups, id, { identities, db, collections: ['orders'], as: { orders: 'orders-then' } });
1250
+ await restoreCollections(backups, id, { identities, db, collections: ['orders'], replace: true });
1251
+ await restoreCollections(backups, id, {
1252
+ identities,
1253
+ db,
1254
+ collections: ['orders'],
1255
+ documents: { filter: {}, existing: 'keep' },
1256
+ });
1257
+ ```