@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.
- package/LICENSE +21 -0
- package/README.md +484 -2
- package/dist/backups/key-file.d.ts +30 -0
- package/dist/backups/key-file.d.ts.map +1 -0
- package/dist/backups/mongo-backups.d.ts +33 -0
- package/dist/backups/mongo-backups.d.ts.map +1 -0
- package/dist/backups/operations.d.ts +55 -0
- package/dist/backups/operations.d.ts.map +1 -0
- package/dist/backups/options.d.ts +60 -0
- package/dist/backups/options.d.ts.map +1 -0
- package/dist/backups/plan.d.ts +20 -0
- package/dist/backups/plan.d.ts.map +1 -0
- package/dist/chunks/index-j0tptz7w.js +97 -0
- package/dist/chunks/index-j0tptz7w.js.map +11 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +31 -0
- package/dist/cli.js.map +10 -0
- package/dist/errors.d.ts +43 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/format/bson-stream.d.ts +13 -0
- package/dist/format/bson-stream.d.ts.map +1 -0
- package/dist/format/change.d.ts +61 -0
- package/dist/format/change.d.ts.map +1 -0
- package/dist/format/document.d.ts +7 -0
- package/dist/format/document.d.ts.map +1 -0
- package/dist/format/metadata.d.ts +14 -0
- package/dist/format/metadata.d.ts.map +1 -0
- package/dist/format/names.d.ts +22 -0
- package/dist/format/names.d.ts.map +1 -0
- package/dist/format/position.d.ts +29 -0
- package/dist/format/position.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1340 -0
- package/dist/index.js.map +32 -0
- package/dist/restore/landing.d.ts +26 -0
- package/dist/restore/landing.d.ts.map +1 -0
- package/dist/restore/options.d.ts +59 -0
- package/dist/restore/options.d.ts.map +1 -0
- package/dist/restore/restore-collections.d.ts +12 -0
- package/dist/restore/restore-collections.d.ts.map +1 -0
- package/dist/source/catalog.d.ts +28 -0
- package/dist/source/catalog.d.ts.map +1 -0
- package/dist/source/changes.d.ts +12 -0
- package/dist/source/changes.d.ts.map +1 -0
- package/dist/source/collections.d.ts +20 -0
- package/dist/source/collections.d.ts.map +1 -0
- package/dist/source/events.d.ts +46 -0
- package/dist/source/events.d.ts.map +1 -0
- package/dist/source/followed.d.ts +13 -0
- package/dist/source/followed.d.ts.map +1 -0
- package/dist/source/mongo-source.d.ts +24 -0
- package/dist/source/mongo-source.d.ts.map +1 -0
- package/dist/source/snapshot.d.ts +17 -0
- package/dist/source/snapshot.d.ts.map +1 -0
- package/dist/target/changes.d.ts +8 -0
- package/dist/target/changes.d.ts.map +1 -0
- package/dist/target/collection.d.ts +20 -0
- package/dist/target/collection.d.ts.map +1 -0
- package/dist/target/mongo-target.d.ts +22 -0
- package/dist/target/mongo-target.d.ts.map +1 -0
- package/docs/README.md +28 -0
- package/docs/guide/errors.md +411 -0
- package/docs/guide/format.md +179 -0
- package/docs/guide/getting-started.md +716 -0
- package/docs/guide/incremental.md +323 -0
- package/docs/guide/operations.md +237 -0
- package/docs/guide/restore.md +684 -0
- package/docs/roadmap.md +61 -0
- package/docs/troubleshooting.md +1257 -0
- package/package.json +70 -5
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
# Incremental and differential backups
|
|
2
|
+
|
|
3
|
+
This page covers backups that store only what changed since an earlier
|
|
4
|
+
one: what the change stream records, where it starts and stops, what it
|
|
5
|
+
refuses, and how to schedule them.
|
|
6
|
+
|
|
7
|
+
`mongoBackups(…).run()` makes incrementals for you, and a full backup when
|
|
8
|
+
one is due or the oplog has moved on —
|
|
9
|
+
[getting started](getting-started.md#run). This page is what happens inside
|
|
10
|
+
each one, and how to make them by hand.
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { bindBackup, defineBackup, localRepository } from '@softistx/backup';
|
|
14
|
+
import { mongoSource, mongoTarget } from '@softistx/mongo-backup';
|
|
15
|
+
import { MongoClient } from 'mongodb';
|
|
16
|
+
|
|
17
|
+
const client = await MongoClient.connect(process.env.MONGO_URL as string);
|
|
18
|
+
const backups = bindBackup(defineBackup({ name: 'shop-db' }), {
|
|
19
|
+
repositories: [localRepository({ path: '/mnt/backups' })],
|
|
20
|
+
recipients: [process.env.BACKUP_RECIPIENT as string],
|
|
21
|
+
});
|
|
22
|
+
const identities = [process.env.BACKUP_IDENTITY as string];
|
|
23
|
+
const source = mongoSource({ db: client.db('shop') });
|
|
24
|
+
|
|
25
|
+
const full = await backups.create(source); // Sunday
|
|
26
|
+
const monday = await backups.create(source, { kind: 'incremental', identities });
|
|
27
|
+
// { kind: 'incremental', parent: full.id, entries: full.entries + 1, reused: full.entries, … }
|
|
28
|
+
const tuesday = await backups.create(source, { kind: 'incremental', identities });
|
|
29
|
+
// { kind: 'incremental', parent: monday.id, entries: full.entries + 2, … }
|
|
30
|
+
|
|
31
|
+
await backups.restore(tuesday.id, mongoTarget({ db: client.db('shop-restored') }), { identities });
|
|
32
|
+
// the full backup's collections, then Monday's changes, then Tuesday's
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Which backup each kind builds on, the key it needs on the host that makes
|
|
36
|
+
it, and how `prune` keeps a chain are `@softistx/backup`'s rules —
|
|
37
|
+
[chains](https://github.com/softistx/data/blob/develop/packages/backup/docs/guide/chains.md).
|
|
38
|
+
This page is about what `mongoSource` adds to them.
|
|
39
|
+
|
|
40
|
+
## One more entry: `changes/<n>`
|
|
41
|
+
|
|
42
|
+
An incremental or differential holds every entry of the backup it builds
|
|
43
|
+
on — given again by their recorded fingerprints, so none is read or stored
|
|
44
|
+
again — and **one more**: `changes/<n>`, the changes since that backup,
|
|
45
|
+
numbered after the changes entries it already holds.
|
|
46
|
+
|
|
47
|
+
| Backup | Builds on | Its entries |
|
|
48
|
+
| --- | --- | --- |
|
|
49
|
+
| full, Sunday | — | `metadata/*`, `documents/*` |
|
|
50
|
+
| incremental, Monday | Sunday | Sunday's, and `changes/000001`: Sunday to Monday |
|
|
51
|
+
| incremental, Tuesday | Monday | Monday's, and `changes/000002`: Monday to Tuesday |
|
|
52
|
+
| differential, Wednesday | Sunday | Sunday's, and `changes/000001`: Sunday to Wednesday |
|
|
53
|
+
|
|
54
|
+
A restore writes the collections as the full backup read them, then
|
|
55
|
+
applies each `changes/<n>` in order — [restore](restore.md#changes). An
|
|
56
|
+
incremental with nothing changed holds an empty `changes/<n>`, and restores
|
|
57
|
+
what its parent did.
|
|
58
|
+
|
|
59
|
+
## What the change stream records
|
|
60
|
+
|
|
61
|
+
The source watches the whole database, with `showExpandedEvents` so that
|
|
62
|
+
changes to collections and indexes come through, and keeps what a restore
|
|
63
|
+
needs to apply each change again — nothing more:
|
|
64
|
+
|
|
65
|
+
| Event | Kept as | Applied on restore as |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `insert`, `replace` | the document, by its `_id` | a `replaceOne` with `upsert` |
|
|
68
|
+
| `update` | the fields set and unset, and the arrays cut — or the whole document, with [post-images](#post-images-and-dotted-field-names) | the arrays cut, then a `$set` and an `$unset`; or a `replaceOne` with `upsert` |
|
|
69
|
+
| `delete` | the `_id` | a `deleteOne` |
|
|
70
|
+
| `create` | the collection's options | `createCollection` — refused with `EXISTS` when it is there, unless `replace` |
|
|
71
|
+
| `createIndexes`, `dropIndexes` | the indexes, or their names | `createIndexes`; `dropIndex`, an index already gone ignored |
|
|
72
|
+
| `modify` | what `collMod` changed: a validator, an index made hidden, … | `collMod`; a collection gone ignored |
|
|
73
|
+
| `rename` in the database | the new name, and whether it replaced a collection there (`dropTarget`) | `renameCollection`; a collection of that name is replaced if the rename replaced one at the source, refused with `EXISTS` otherwise, unless `replace` — [restore](restore.md#changes) |
|
|
74
|
+
| `rename` to another database, `drop` | a drop | `dropCollection`; a collection gone ignored |
|
|
75
|
+
| `dropDatabase` | a drop of the database | `dropDatabase`, on the database restored into |
|
|
76
|
+
|
|
77
|
+
Other events — sharding changes, say — are not kept. Numbers keep their
|
|
78
|
+
kind: the stream is read without turning BSON numbers into JavaScript ones.
|
|
79
|
+
|
|
80
|
+
## Where it starts and stops
|
|
81
|
+
|
|
82
|
+
- **It starts where the parent stopped**: just after the full backup's
|
|
83
|
+
snapshot time, or where the previous incremental stopped — after the last
|
|
84
|
+
change it read, or at the change stream's own position when it had caught
|
|
85
|
+
up. Nothing is read twice, and nothing in between is missed.
|
|
86
|
+
- **It stops at the time the backup started.** The cluster's operation time
|
|
87
|
+
is read before the first entry; the stream stops at the first change
|
|
88
|
+
after it, at the first read that comes back empty — it has caught up —
|
|
89
|
+
or at an invalidation, which a dropped database brings; the next one
|
|
90
|
+
resumes after it. A write that lands while the backup runs is in the
|
|
91
|
+
next one:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
await orders.insertOne({ _id: 2 });
|
|
95
|
+
const backup = backups.create(source, { kind: 'incremental', identities });
|
|
96
|
+
await orders.insertOne({ _id: 3 }); // while it runs: in the next backup, not this one
|
|
97
|
+
await backup;
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
- **It records where it stopped** — the last change's resume token, or the
|
|
101
|
+
change stream's own when it caught up — in
|
|
102
|
+
the backup's catalog, encrypted, for the next one. Nothing is kept on the
|
|
103
|
+
host: any process with the key makes the next incremental.
|
|
104
|
+
|
|
105
|
+
## Post-images and dotted field names
|
|
106
|
+
|
|
107
|
+
(Only in a collection the chain follows: one it does not follow is
|
|
108
|
+
[passed over](#the-collections-a-chain-follows). Narrowing `collections`
|
|
109
|
+
mid-chain does not stop following one — that waits for the next full
|
|
110
|
+
backup.)
|
|
111
|
+
|
|
112
|
+
Without post-images, an update is kept as the change stream describes it:
|
|
113
|
+
the fields set, the fields removed, the arrays cut. That cannot say an
|
|
114
|
+
update to a field **whose name holds a dot or is a number** — `{ 'x.y': 1 }`,
|
|
115
|
+
`{ '3': 1 }` — which would be applied as a path instead. The server marks
|
|
116
|
+
such an update, and the backup refuses it rather than record it wrong:
|
|
117
|
+
|
|
118
|
+
```text
|
|
119
|
+
MongoBackupError (UNSUPPORTED): mongoSource: an update touched a field whose name
|
|
120
|
+
holds a dot or is a number, which a change cannot say without its post-image;
|
|
121
|
+
turn on changeStreamPreAndPostImages for that collection, or make a full backup
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
A collection that keeps **post-images** has every update recorded as the
|
|
125
|
+
whole document after it — exact whatever the field names, and larger. Turn
|
|
126
|
+
them on for the collections that use such names, then make a full backup:
|
|
127
|
+
the update already in the stream has no post-image, so the incremental
|
|
128
|
+
that met it fails again until a full backup moves past it.
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
await db.command({ collMod: 'settings', changeStreamPreAndPostImages: { enabled: true } });
|
|
132
|
+
// or when creating it:
|
|
133
|
+
await db.createCollection('settings', { changeStreamPreAndPostImages: { enabled: true } });
|
|
134
|
+
|
|
135
|
+
await backups.create(source); // a full backup: the next incremental starts after the update
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
A post-image the server no longer holds — expired, or never written — falls
|
|
139
|
+
back to the update description, as a collection without post-images does.
|
|
140
|
+
|
|
141
|
+
## The collections a chain follows
|
|
142
|
+
|
|
143
|
+
An incremental follows **the collections its full backup held**, plus those
|
|
144
|
+
created since that `collections` takes. The full backup's `metadata/<name>`
|
|
145
|
+
entries give that set; each position records only how it changed since —
|
|
146
|
+
`added` and `removed`, carried on from one incremental to the next — and a
|
|
147
|
+
change to any other collection is not recorded. An event on a collection
|
|
148
|
+
not followed is passed over before it is translated, so an update there
|
|
149
|
+
that a change could not say, or a time-series collection created that the
|
|
150
|
+
filter leaves out, never fails the backup. Leaving a collection out gets
|
|
151
|
+
past `UNSUPPORTED` at once only for a time-series collection not yet
|
|
152
|
+
created; a collection already followed stays followed until the next full
|
|
153
|
+
backup.
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
const source = mongoSource({ db: client.db('shop'), collections: (name) => name !== 'metrics' });
|
|
157
|
+
await backups.create(source); // follows every collection but metrics
|
|
158
|
+
|
|
159
|
+
await client.db('shop').collection('reviews').insertOne({ stars: 5 }); // a new collection
|
|
160
|
+
await backups.create(source, { kind: 'incremental', identities }); // follows reviews from its creation
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
**A change to `collections` takes effect at the next full backup**, never
|
|
164
|
+
halfway through a chain — the chain stays one database at one set of
|
|
165
|
+
collections:
|
|
166
|
+
|
|
167
|
+
- **a wider filter does not take in an existing collection halfway**: its
|
|
168
|
+
documents were never read, so the incremental keeps following what the
|
|
169
|
+
full backup held, and the newly taken collection waits for the next full
|
|
170
|
+
backup;
|
|
171
|
+
- **a narrower filter does not drop one halfway**: the incremental keeps
|
|
172
|
+
recording the changes to every collection the chain follows.
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
await backups.create(mongoSource({ db, collections: ['orders'] }));
|
|
176
|
+
const next = await backups.create(mongoSource({ db, collections: ['orders', 'customers'] }), {
|
|
177
|
+
kind: 'incremental',
|
|
178
|
+
identities,
|
|
179
|
+
});
|
|
180
|
+
// next restores orders, with its changes — not customers
|
|
181
|
+
await backups.create(mongoSource({ db, collections: ['orders', 'customers'] })); // now both
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
### Renames
|
|
185
|
+
|
|
186
|
+
A rename crosses the line between followed and not:
|
|
187
|
+
|
|
188
|
+
| Renamed | Kept as |
|
|
189
|
+
| --- | --- |
|
|
190
|
+
| from a followed collection to a name the filter takes | a `rename`; the new name is followed from then on |
|
|
191
|
+
| from a followed collection to a name the filter leaves out — `orders` to `orders-old`, with `orders-old` left out | a **drop** of `orders` |
|
|
192
|
+
| from a collection not followed to a name the filter takes — `import` to `orders` | refused with `UNSUPPORTED`: the incremental never read the documents it brings |
|
|
193
|
+
| from a collection not followed to a name the filter leaves out | nothing |
|
|
194
|
+
| to another database | a **drop**: it is gone from this one |
|
|
195
|
+
|
|
196
|
+
```text
|
|
197
|
+
MongoBackupError (UNSUPPORTED): mongoSource: a collection was renamed into those
|
|
198
|
+
backed up, with documents an incremental backup never read; make a full backup
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
A restore's own renames count too: a restore lands each collection under
|
|
202
|
+
`nxgt-restore-<uuid>` and renames it into place, so **after restoring into
|
|
203
|
+
the database you back up** — with `replace: true`, say — the next
|
|
204
|
+
incremental sees renames into the followed collections and fails
|
|
205
|
+
`UNSUPPORTED`. Make a full backup right after such a restore:
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
await backups.restore(id, mongoTarget({ db: client.db('shop'), replace: true }), { identities });
|
|
209
|
+
await backups.create(mongoSource({ db: client.db('shop') })); // the chain starts again here
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
A time-series collection created since the parent, among those the filter
|
|
213
|
+
takes, is refused, as a full backup refuses one —
|
|
214
|
+
[choosing collections](getting-started.md#choosing-collections).
|
|
215
|
+
|
|
216
|
+
## A dropped database
|
|
217
|
+
|
|
218
|
+
`dropDatabase` on the database backed up is recorded, and the next backup
|
|
219
|
+
resumes just after it. A restore applies it as **a drop of the database
|
|
220
|
+
restored into** — everything in it, not only what the backup holds — then
|
|
221
|
+
the changes after it. Restore into a database of its own.
|
|
222
|
+
|
|
223
|
+
## The oplog window
|
|
224
|
+
|
|
225
|
+
The change stream reads the **oplog**, which the server keeps for a size or
|
|
226
|
+
a time, not forever. When the position the parent recorded has fallen out
|
|
227
|
+
of it, the incremental fails before it stores anything:
|
|
228
|
+
|
|
229
|
+
```text
|
|
230
|
+
MongoBackupError (HISTORY_LOST): mongoSource: the change stream cannot resume where
|
|
231
|
+
the last backup stopped: the oplog no longer reaches back there; make a full backup
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
So:
|
|
235
|
+
|
|
236
|
+
- **Back up more often than the oplog reaches back**, with a margin for a
|
|
237
|
+
busy day — a burst of writes shortens the window. `rs.printReplicationInfo()`
|
|
238
|
+
in `mongosh` shows it as `log length start to end`.
|
|
239
|
+
- **Keep the oplog for longer than the interval**, by time rather than by
|
|
240
|
+
size, on every member (every shard, for a sharded cluster):
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
await client.db('admin').command({ replSetResizeOplog: 1, minRetentionHours: 48 });
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
- **A differential reads from its full backup**, so the oplog must reach
|
|
247
|
+
back to the full backup, not to the night before. With a weekly full
|
|
248
|
+
backup, that is a week of oplog; incrementals need only a day.
|
|
249
|
+
- **After `HISTORY_LOST`, the next backup must be full**: every incremental
|
|
250
|
+
from the same parent fails the same way.
|
|
251
|
+
|
|
252
|
+
## A weekly schedule
|
|
253
|
+
|
|
254
|
+
A full backup on Sunday, an incremental every other night, and a full one
|
|
255
|
+
whenever an incremental cannot be made:
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
// backup.ts — run nightly with `bun run backup.ts`
|
|
259
|
+
import { BackupError, bindBackup, type CreateOptions, defineBackup, localRepository } from '@softistx/backup';
|
|
260
|
+
import { MongoBackupError, mongoSource } from '@softistx/mongo-backup';
|
|
261
|
+
import { MongoClient } from 'mongodb';
|
|
262
|
+
|
|
263
|
+
const client = await MongoClient.connect(process.env.MONGO_URL as string);
|
|
264
|
+
try {
|
|
265
|
+
const backups = bindBackup(defineBackup({ name: 'shop-db' }), {
|
|
266
|
+
repositories: [localRepository({ path: '/mnt/backups' })],
|
|
267
|
+
recipients: [process.env.BACKUP_RECIPIENT as string],
|
|
268
|
+
tmpDir: '/var/tmp',
|
|
269
|
+
});
|
|
270
|
+
const identities = [(await Bun.file('/etc/backup/identity.txt').text()).trim()]; // chmod 600
|
|
271
|
+
const source = mongoSource({ db: client.db('shop'), collections: (name) => name !== 'metrics' });
|
|
272
|
+
|
|
273
|
+
const options: CreateOptions =
|
|
274
|
+
new Date().getUTCDay() === 0 ? { kind: 'full' } : { kind: 'incremental', identities };
|
|
275
|
+
|
|
276
|
+
let created;
|
|
277
|
+
try {
|
|
278
|
+
created = await backups.create(source, options);
|
|
279
|
+
} catch (error) {
|
|
280
|
+
const startOver =
|
|
281
|
+
// the first night, or the chain pruned away: nothing to build on
|
|
282
|
+
(error instanceof BackupError && error.code === 'NOT_FOUND') ||
|
|
283
|
+
// the oplog moved on, or a change an incremental cannot record
|
|
284
|
+
(error instanceof MongoBackupError &&
|
|
285
|
+
(error.code === 'HISTORY_LOST' || error.code === 'UNSUPPORTED'));
|
|
286
|
+
if (!startOver) throw error;
|
|
287
|
+
console.warn(`incremental refused (${(error as Error).message}); making a full backup`);
|
|
288
|
+
created = await backups.create(source);
|
|
289
|
+
}
|
|
290
|
+
console.log(`${created.kind} ${created.id}: ${created.entries - created.reused} entries stored`);
|
|
291
|
+
|
|
292
|
+
await backups.prune({ keep: { daily: 14, weekly: 8 } }); // keeps every parent a kept backup needs
|
|
293
|
+
} finally {
|
|
294
|
+
await client.close();
|
|
295
|
+
}
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
A full backup made after `UNSUPPORTED` for a time-series collection fails
|
|
299
|
+
too, with the same code: leave the collection out with `collections`.
|
|
300
|
+
|
|
301
|
+
| | `incremental` | `differential` |
|
|
302
|
+
| --- | --- | --- |
|
|
303
|
+
| Its `changes/<n>` holds | the changes since the night before | the changes since the full backup: more each night |
|
|
304
|
+
| The oplog must reach back | to the night before | to the full backup |
|
|
305
|
+
| A restore applies | every `changes/<n>` since the full backup, one per night | one |
|
|
306
|
+
|
|
307
|
+
Either way a restore reads the full backup's collections whole, then
|
|
308
|
+
applies changes; what grows with an incremental chain is the number of
|
|
309
|
+
backups that must be there, intact — `@softistx/backup`'s
|
|
310
|
+
[chains](https://github.com/softistx/data/blob/develop/packages/backup/docs/guide/chains.md#a-typical-schedule).
|
|
311
|
+
|
|
312
|
+
## Errors
|
|
313
|
+
|
|
314
|
+
| Thrown | When |
|
|
315
|
+
| --- | --- |
|
|
316
|
+
| `MongoBackupError` `HISTORY_LOST` | the oplog no longer reaches the parent's position — [above](#the-oplog-window) |
|
|
317
|
+
| `MongoBackupError` `UNSUPPORTED` | an update to a dotted or numeric field name without a post-image; a rename into the collections followed — a restore's own included, [above](#renames); more collections created, renamed or dropped since the full backup than a position records; a time-series collection created |
|
|
318
|
+
| `MongoBackupError` `MALFORMED`: `mongoSource: the backup built on recorded no position this version reads; make a full backup` | the parent holds no position this version wrote |
|
|
319
|
+
| `MongoBackupError` `MALFORMED`: `mongoSource: an entry of the backup built on was asked for again; it has no fingerprint, so make a full backup` | the parent recorded an entry without the fingerprint this source gave it |
|
|
320
|
+
| `BackupError` `NOT_FOUND` | nothing to build on — `@softistx/backup`'s |
|
|
321
|
+
|
|
322
|
+
Every one is in [errors](errors.md), and each message in
|
|
323
|
+
[troubleshooting](../troubleshooting.md).
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# Running it in production
|
|
2
|
+
|
|
3
|
+
This page puts `mongoBackups` on a schedule: the key file and where it
|
|
4
|
+
lives, the job, how you know it works, and the `restore` call to make on
|
|
5
|
+
the day you need a backup back. Each method is documented on
|
|
6
|
+
[getting started](getting-started.md#what-it-returns). The repository's
|
|
7
|
+
[`examples/mongo-backup-job`](https://github.com/softistx/data/tree/develop/examples/mongo-backup-job)
|
|
8
|
+
is this page as code, with a spec that runs the whole cycle against a
|
|
9
|
+
replica set.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
// backup.ts — `bun backup.ts run` hourly, `bun backup.ts drill` daily
|
|
13
|
+
import { mongoBackups } from '@softistx/mongo-backup';
|
|
14
|
+
import { MongoClient } from 'mongodb';
|
|
15
|
+
|
|
16
|
+
const command = Bun.argv[2];
|
|
17
|
+
if (command !== 'run' && command !== 'drill') {
|
|
18
|
+
console.error('usage: bun backup.ts run|drill');
|
|
19
|
+
process.exit(2);
|
|
20
|
+
}
|
|
21
|
+
const client = await MongoClient.connect(process.env.MONGO_URL as string);
|
|
22
|
+
try {
|
|
23
|
+
const backups = mongoBackups({
|
|
24
|
+
db: client.db('shop'),
|
|
25
|
+
repository: '/mnt/backups',
|
|
26
|
+
keyFile: process.env.BACKUP_KEY_FILE as string, // absolute; written by keygen
|
|
27
|
+
});
|
|
28
|
+
const report = command === 'run' ? await backups.run() : await backups.drill();
|
|
29
|
+
console.log(JSON.stringify(report)); // ids, sizes, counts: never a key nor a document
|
|
30
|
+
} finally {
|
|
31
|
+
await client.close();
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
- [The key file](#the-key-file)
|
|
36
|
+
- [The job](#the-job)
|
|
37
|
+
- [The schedule](#the-schedule)
|
|
38
|
+
- [Knowing it works](#knowing-it-works)
|
|
39
|
+
- [Forcing a full backup](#forcing-a-full-backup)
|
|
40
|
+
- [The day you need it](#the-day-you-need-it)
|
|
41
|
+
- [Moving from a job by hand](#moving-from-a-job-by-hand)
|
|
42
|
+
|
|
43
|
+
## The key file
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
bunx nxgt-mongo-backup keygen /etc/backup/shop.key
|
|
47
|
+
# recipient: age1…
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
| It holds | Used for | Needed by |
|
|
51
|
+
| --- | --- | --- |
|
|
52
|
+
| the age identity (`AGE-SECRET-KEY-1…`) | reading backups: an incremental reads the catalog of the one it builds on, `run` reads each new one back, a restore and a drill read the whole chain | `run`, `restore`, `drill` |
|
|
53
|
+
| its recipient (`age1…`) | every backup is encrypted to it — derived from the identity, not stored | `run` |
|
|
54
|
+
| the Ed25519 signing key (PEM) | every manifest is signed with it | `run` |
|
|
55
|
+
| its public key (PEM) | a manifest is read only when signed by it — derived, not stored | every method, `list` included |
|
|
56
|
+
|
|
57
|
+
- **The job host holds the identity**, because `run` makes incrementals
|
|
58
|
+
and reads every backup back. Whoever takes that host can read the
|
|
59
|
+
backups.
|
|
60
|
+
- **A file, not an environment variable**: mode `0600`, named by the
|
|
61
|
+
environment (`BACKUP_KEY_FILE`). A variable ends up in a process listing
|
|
62
|
+
or a crash report more easily than a file does. `readKeyFile` refuses a
|
|
63
|
+
file others than its owner can read or write, with `KEY_FILE`; nothing this package
|
|
64
|
+
throws or reports quotes a key.
|
|
65
|
+
- **Keep a copy away from the backups** — a password manager, a safe. A
|
|
66
|
+
backup whose key file is lost is noise.
|
|
67
|
+
- **The same file for the job, the drill and a restore**. A missing one
|
|
68
|
+
rejects with `KEY_FILE` (`mongoBackups on "shop": there is no key file there;
|
|
69
|
+
write one with nxgt-mongo-backup keygen`), and is looked for again on the next
|
|
70
|
+
call: a key file deployed after the process started is picked up without
|
|
71
|
+
a restart.
|
|
72
|
+
|
|
73
|
+
## The job
|
|
74
|
+
|
|
75
|
+
`run` is the job: a full backup when none is younger than `fullEvery`, an
|
|
76
|
+
incremental otherwise, a full one at once when the oplog no longer reaches
|
|
77
|
+
the last backup, the new backup read back with the identity, then the
|
|
78
|
+
rotation.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const report = await backups.run();
|
|
82
|
+
// { id, kind: 'incremental', fellBack: false, entries: 13, storedSize: 2048, chain: 4, removed: ['…'] }
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- **A full backup a week** (`DEFAULT_FULL_EVERY`), incrementals in between.
|
|
86
|
+
A restore reads the full backup and every incremental after it, so a
|
|
87
|
+
short chain is a fast restore; `chain` in the report says how long it is.
|
|
88
|
+
Lower `fullEvery` for a database that changes a lot.
|
|
89
|
+
- **`HISTORY_LOST` starts a new chain** at once, with `fellBack: true`:
|
|
90
|
+
until a full backup, every incremental would fail alike —
|
|
91
|
+
[the oplog window](incremental.md#the-oplog-window).
|
|
92
|
+
- **Every backup is read back** with the identity — decrypted, every digest
|
|
93
|
+
and the signature checked — before the rotation. A backup never read back
|
|
94
|
+
is not a backup yet.
|
|
95
|
+
- **The rotation runs after the backup**, never before, with `keep`
|
|
96
|
+
(`DEFAULT_KEEP`: a day hourly, two weeks daily, two months weekly, a year
|
|
97
|
+
monthly). A kept incremental keeps the backups it builds on, so a
|
|
98
|
+
rotation never breaks a chain —
|
|
99
|
+
[`@softistx/backup`'s rotation](https://github.com/softistx/data/blob/develop/packages/backup/docs/guide/rotation.md).
|
|
100
|
+
`keep: false` leaves the rotation to you.
|
|
101
|
+
- **One writer at a time**: `create` and `prune` take the repository's
|
|
102
|
+
lock, so a run that overlaps the last one fails rather than interleave.
|
|
103
|
+
The backup rejects with `BackupError` `NOT_STORED` — `PARTIAL` when
|
|
104
|
+
another repository took it — the `LOCKED` in that repository's outcome;
|
|
105
|
+
the rotation rejects with `LOCKED`, after the backup was made and read
|
|
106
|
+
back —
|
|
107
|
+
[as `@softistx/backup`'s locking shows](https://github.com/softistx/data/blob/develop/packages/backup/docs/guide/locking.md).
|
|
108
|
+
Let the scheduler skip such a run, not retry it in a loop.
|
|
109
|
+
- **Anything else is thrown** as it is: `UNSUPPORTED`, `CHANGING`,
|
|
110
|
+
`SNAPSHOT_TOO_OLD`, a driver error. A run that fails while backing up
|
|
111
|
+
pruned nothing — [errors](errors.md).
|
|
112
|
+
|
|
113
|
+
## The schedule
|
|
114
|
+
|
|
115
|
+
| What | How often | Why |
|
|
116
|
+
| --- | --- | --- |
|
|
117
|
+
| `run()` | hourly | an hour is what you can lose |
|
|
118
|
+
| `drill()` | daily or weekly | a backup never restored is a hope |
|
|
119
|
+
| an off-site copy | with every run | a second repository in `repository`, an S3 bucket — every backup is written to each |
|
|
120
|
+
|
|
121
|
+
```text
|
|
122
|
+
0 * * * * cd /srv/backup && bun backup.ts run
|
|
123
|
+
30 4 * * * cd /srv/backup && bun backup.ts drill
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Two server settings bound what the job can do:
|
|
127
|
+
|
|
128
|
+
- **The oplog** must hold more than the time between two runs, with room
|
|
129
|
+
for a burst of writes — or every run falls back to a full backup, and
|
|
130
|
+
`fellBack: true` says so. `rs.printReplicationInfo()` gives its window.
|
|
131
|
+
- **`minSnapshotHistoryWindowInSeconds`** (300 by default) must be longer
|
|
132
|
+
than a full backup takes to read, or it fails with `SNAPSHOT_TOO_OLD` —
|
|
133
|
+
[a long snapshot](getting-started.md#a-long-snapshot).
|
|
134
|
+
|
|
135
|
+
## Knowing it works
|
|
136
|
+
|
|
137
|
+
- **Exit non-zero on failure**, and let the scheduler alert on it. Print
|
|
138
|
+
the report, one line of JSON per run.
|
|
139
|
+
- **Alert on `fellBack: true`** too: the run worked, but stored the whole
|
|
140
|
+
database — the oplog window is shorter than the interval.
|
|
141
|
+
- **Alert on silence**: a job that stopped running fails nothing. The
|
|
142
|
+
newest backup older than two runs is an alert. `list()` decrypts
|
|
143
|
+
nothing, but reads the key file, for the key manifests are signed with:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
const newest = (await backups.list()).at(-1);
|
|
147
|
+
if (!newest || Date.now() - newest.createdAt.getTime() > 2 * 60 * 60 * 1000) {
|
|
148
|
+
console.error('no backup for two hours');
|
|
149
|
+
process.exit(1);
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
- **Drill**: `drill()` restores the newest backup, chain included, into
|
|
154
|
+
`nxgt-drill-<uuid>` on the same client, counts each collection's
|
|
155
|
+
documents, and drops it. Check the counts against what you expect, not
|
|
156
|
+
only that it resolved:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
const { id, collections } = await backups.drill();
|
|
160
|
+
const orders = collections.find((c) => c.name === 'orders')?.documents ?? 0;
|
|
161
|
+
if (orders === 0) throw new Error(`drill of ${id}: no orders`);
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
A drill costs a whole restore on the cluster backed up: schedule it away
|
|
165
|
+
from the busy hours, and give the user the right to create a database. A
|
|
166
|
+
process killed mid-drill leaves `nxgt-drill-<uuid>` behind; drop it by
|
|
167
|
+
hand.
|
|
168
|
+
|
|
169
|
+
## Forcing a full backup
|
|
170
|
+
|
|
171
|
+
An incremental that fails `UNSUPPORTED` — a rename into the backed-up
|
|
172
|
+
collections, a dotted-field update without post-images, a time-series
|
|
173
|
+
collection created — fails again on every `run` until a full backup: the
|
|
174
|
+
change it stopped on is still in the stream. A change to `collections`
|
|
175
|
+
waits for one too. Give `run` a `now` a `fullEvery` ahead: it then finds
|
|
176
|
+
no full backup young enough, and makes one.
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
import { DEFAULT_FULL_EVERY } from '@softistx/mongo-backup';
|
|
180
|
+
|
|
181
|
+
await backups.run(new Date(Date.now() + DEFAULT_FULL_EVERY)); // { kind: 'full', chain: 1, … }
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
`now` decides the kind and nothing else: the backup carries the machine's
|
|
185
|
+
time, and the rotation goes by the machine's clock too — a later `now`
|
|
186
|
+
there would rotate away the backup just made. The full backup is read
|
|
187
|
+
back and rotated like any other, with the same `collections`. Pass your own
|
|
188
|
+
`fullEvery` if it is not the default.
|
|
189
|
+
|
|
190
|
+
Through the binding, the same by hand — give `mongoSource` the same
|
|
191
|
+
`collections` as `mongoBackups`:
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
import { mongoSource } from '@softistx/mongo-backup';
|
|
195
|
+
|
|
196
|
+
const { backups: bound, keys } = await backups.binding();
|
|
197
|
+
const full = await bound.create(mongoSource({ db: client.db('shop') }));
|
|
198
|
+
await bound.verify(full.id, { identities: [keys.identity] });
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
The next `run` builds on it. After a restore into the database you back up,
|
|
202
|
+
do the same: the restore's own renames would otherwise fail the next
|
|
203
|
+
incremental —
|
|
204
|
+
[into the database you back up](restore.md#into-the-database-you-back-up).
|
|
205
|
+
|
|
206
|
+
## The day you need it
|
|
207
|
+
|
|
208
|
+
| You need | Run |
|
|
209
|
+
| --- | --- |
|
|
210
|
+
| the whole database, elsewhere | `backups.restore({ into: client.db('shop-restored') })` |
|
|
211
|
+
| the whole database as it was at a time | `backups.restore({ into: client.db('shop-restored'), at: new Date('2026-10-04T09:00:00Z') })` |
|
|
212
|
+
| the whole database, in place | `backups.restore({ into: client.db('shop'), replace: true })` — once the application is stopped |
|
|
213
|
+
| one collection as it was, beside the live one | `backups.restore({ into: client.db('shop'), collections: ['orders'], as: { orders: 'orders-before' } })` |
|
|
214
|
+
| some documents back | `backups.restore({ into: client.db('shop'), collections: ['orders'], documents: { filter: { _id: 'o-1001' }, existing: 'keep' } })` — [some documents](restore.md#some-documents) |
|
|
215
|
+
|
|
216
|
+
- **Pick the backup by time**: `at: new Date(…)` takes the newest backup
|
|
217
|
+
made at or before it, an incremental included. `list()` gives each one's
|
|
218
|
+
`createdAt` and `id`, and `at` takes an id too.
|
|
219
|
+
- **Restore beside, then swap**: restoring into another database and
|
|
220
|
+
checking it costs a little time and leaves the live data untouched until
|
|
221
|
+
you are sure.
|
|
222
|
+
- **A partial restore rebuilds the whole backup first**, in a scratch
|
|
223
|
+
database on the same client, then moves what was asked for: it costs a
|
|
224
|
+
full restore, whatever it brings back —
|
|
225
|
+
[restoring part of a backup](restore.md#restoring-part-of-a-backup).
|
|
226
|
+
- **After a restore into the database you back up**, make a full backup —
|
|
227
|
+
[forcing a full backup](#forcing-a-full-backup).
|
|
228
|
+
|
|
229
|
+
## Moving from a job by hand
|
|
230
|
+
|
|
231
|
+
`mongoBackups` sees only the backups under its `name` — the database's
|
|
232
|
+
name by default — whose manifest is signed with its key file's signing
|
|
233
|
+
key. A job that called `bindBackup` and `mongoSource` itself, under another
|
|
234
|
+
name or with keys of its own, does not hand its chain over: the first
|
|
235
|
+
`run` is a full backup, and the old backups are left to the old job's
|
|
236
|
+
rotation. Restore those with the lower level and the keys they were made
|
|
237
|
+
with — [restore](restore.md).
|