@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,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/backups/mongo-backups.ts", "../src/backups/operations.ts", "../src/source/catalog.ts", "../src/source/collections.ts", "../src/target/mongo-target.ts", "../src/format/metadata.ts", "../src/format/document.ts", "../src/format/names.ts", "../src/target/changes.ts", "../src/format/bson-stream.ts", "../src/format/change.ts", "../src/target/collection.ts", "../src/restore/landing.ts", "../src/restore/options.ts", "../src/restore/restore-collections.ts", "../src/format/position.ts", "../src/source/events.ts", "../src/source/changes.ts", "../src/source/followed.ts", "../src/source/snapshot.ts", "../src/source/mongo-source.ts", "../src/backups/options.ts", "../src/backups/plan.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import {\n\ttype BackupDefinition,\n\ttype BackupInfo,\n\ttype BoundBackup,\n\tdefineBackup,\n\tlocalRepository,\n\ttype Repository,\n} from '@softistx/backup';\nimport type { BackupKeys } from './key-file';\nimport {\n\tasCalled,\n\tbindingOf,\n\ttype Context,\n\tdrillNewest,\n\tlistOf,\n\ttype RestoreReport,\n\ttype RunReport,\n\trestoreAt,\n\trunOnce,\n} from './operations';\nimport {\n\tcheckOptions,\n\ttype MongoBackupsOptions,\n\ttype RestoreAtOptions,\n} from './options';\nimport type { DrillReport } from './plan';\n\nexport type { RestoreReport, RunReport } from './operations';\n\nexport interface MongoBackups {\n\t/**\n\t * One scheduled run. `now` decides only full or incremental; the backup\n\t * and its rotation go by the machine's clock.\n\t */\n\trun(now?: Date): Promise<RunReport>;\n\t/** A backup, chain included, into `into`: whole, or the part the options name. */\n\trestore(options: RestoreAtOptions): Promise<RestoreReport>;\n\t/** The newest backup restored into a database of its own, counted, then dropped. */\n\tdrill(): Promise<DrillReport>;\n\t/** The backups the repository holds, oldest first. Reads the key file, for the key manifests are signed with. */\n\tlist(): Promise<BackupInfo[]>;\n\t/** The `@softistx/backup` binding underneath, and the keys: for what this does not do. */\n\tbinding(): Promise<{ backups: BoundBackup; keys: BackupKeys }>;\n}\n\nfunction repositoriesOf(\n\trepository: MongoBackupsOptions['repository'],\n): readonly [Repository, ...Repository[]] {\n\tif (typeof repository === 'string')\n\t\treturn [localRepository({ path: repository })];\n\tif (Array.isArray(repository))\n\t\treturn repository as [Repository, ...Repository[]];\n\treturn [repository as Repository];\n}\n\n/** The backup's definition; `defineBackup`'s refusal, told as this call's. */\nfunction definitionOf(options: MongoBackupsOptions): BackupDefinition {\n\ttry {\n\t\treturn defineBackup({ name: options.name ?? options.db.databaseName });\n\t} catch (cause) {\n\t\t// The rule as `defineBackup` states it: that call stays its authority.\n\t\tconst rule = String((cause as Error).message).replace(\n\t\t\t/^defineBackup: the name must be /,\n\t\t\t'',\n\t\t);\n\t\tthrow new TypeError(\n\t\t\toptions.name === undefined\n\t\t\t\t? `mongoBackups: the database's name cannot name a backup; give name: ${rule}`\n\t\t\t\t: `mongoBackups: name must be ${rule}`,\n\t\t\t{ cause },\n\t\t);\n\t}\n}\n\n/**\n * MongoDB backups with the decisions made: one key file, a full backup a\n * week and incrementals in between, every backup read back with the key,\n * a rotation after each run, and one `restore` for a whole database or a\n * part of it. Built on `mongoSource`, `mongoTarget` and\n * `restoreCollections`, which stay there for what this does not do.\n */\nexport function mongoBackups(options: MongoBackupsOptions): MongoBackups {\n\tcheckOptions(options);\n\tconst ctx: Context = {\n\t\toptions,\n\t\tdefinition: definitionOf(options),\n\t\trepositories: repositoriesOf(options.repository),\n\t};\n\treturn {\n\t\tbinding: () => bindingOf(ctx),\n\t\tlist: () => listOf(ctx),\n\t\trun: (now) => asCalled(runOnce(ctx, now), ctx, 'run'),\n\t\trestore: (at) => asCalled(restoreAt(ctx, at), ctx, 'restore'),\n\t\tdrill: () => asCalled(drillNewest(ctx), ctx, 'drill'),\n\t};\n}\n",
|
|
6
|
+
"import {\n\ttype BackupDefinition,\n\ttype BackupInfo,\n\ttype BoundBackup,\n\tbindBackup,\n\ttype Repository,\n\ttype Restored,\n} from '@softistx/backup';\nimport { MongoBackupError, renamed } from '../errors';\nimport type { RestoredCollections } from '../restore/options';\nimport { restoreSome } from '../restore/restore-collections';\nimport { mongoSource } from '../source/mongo-source';\nimport { mongoTarget } from '../target/mongo-target';\nimport { type BackupKeys, readKeyFile } from './key-file';\nimport {\n\tcheckRestore,\n\tDEFAULT_FULL_EVERY,\n\tDEFAULT_KEEP,\n\ttype MongoBackupsOptions,\n\ttype RestoreAtOptions,\n} from './options';\nimport { chosenBackup, countsOf, type DrillReport, kindFor } from './plan';\n\n/** What one `run` did, for the logs: ids and sizes, never a key nor a document. */\nexport interface RunReport {\n\tid: string;\n\tkind: 'full' | 'incremental';\n\t/** `true` when an incremental was due, but the oplog no longer reached the last backup. */\n\tfellBack: boolean;\n\tentries: number;\n\tstoredSize: number;\n\t/** How many backups a restore of this one reads: itself and those it builds on. */\n\tchain: number;\n\t/** The backups the rotation removed. */\n\tremoved: string[];\n}\n\n/** What `restore` wrote: `collections` only when part of a backup was asked for. */\nexport type RestoreReport = Restored & {\n\tcollections?: RestoredCollections['collections'];\n};\n\nexport interface Bound {\n\tbackups: BoundBackup;\n\tkeys: BackupKeys;\n}\n\n/** What each operation reads: data only, the binding once the key file is read. */\nexport interface Context {\n\toptions: MongoBackupsOptions;\n\tdefinition: BackupDefinition;\n\trepositories: readonly [Repository, ...Repository[]];\n\t/** The key file read and the backup bound, once a call needed them. */\n\tready?: Promise<Bound> | undefined;\n}\n\n/** `<call> on \"<backup>\"`: the call a consumer wrote, and the backup it was on. */\nconst named = (ctx: Context, call: string) =>\n\t`${call} on \"${ctx.definition.name}\"`;\n\n/** `p`'s lower-level refusals told as `<call> on \"<backup>\"`. */\nexport function asCalled<T>(\n\tp: Promise<T>,\n\tctx: Context,\n\tcall: string,\n): Promise<T> {\n\treturn renamed(p, named(ctx, call));\n}\n\n/** The binding, the key file read on first use, and again after a failed read. */\nexport function bindingOf(ctx: Context): Promise<Bound> {\n\tif (!ctx.ready) {\n\t\tconst { options } = ctx;\n\t\tconst ready = readKeyFile(options.keyFile, named(ctx, 'mongoBackups')).then(\n\t\t\t(keys) => ({\n\t\t\t\tkeys,\n\t\t\t\tbackups: bindBackup(ctx.definition, {\n\t\t\t\t\trepositories: ctx.repositories,\n\t\t\t\t\trecipients: [keys.recipient],\n\t\t\t\t\tsigning: { key: keys.signingKey },\n\t\t\t\t\ttmpDir: options.tmpDir,\n\t\t\t\t}),\n\t\t\t}),\n\t\t);\n\t\t// A failed read is tried again next call: the file may be fixed by then.\n\t\tready.catch(() => {\n\t\t\tif (ctx.ready === ready) ctx.ready = undefined;\n\t\t});\n\t\tctx.ready = ready;\n\t}\n\treturn ctx.ready;\n}\n\n/** The backups the repository holds that read with the key, oldest first. */\nexport async function listOf(ctx: Context): Promise<BackupInfo[]> {\n\treturn (await (await bindingOf(ctx)).backups.list()).backups;\n}\n\n/**\n * One scheduled run: a full backup when none is younger than `fullEvery`,\n * an incremental otherwise — a full one after all when the oplog no longer\n * reaches the last backup, since every incremental would fail alike until\n * one — read back with the key, then the rotation.\n */\nexport async function runOnce(\n\tctx: Context,\n\tnow = new Date(),\n): Promise<RunReport> {\n\tif (!(now instanceof Date) || Number.isNaN(now.getTime())) {\n\t\tthrow new TypeError(`${named(ctx, 'run')}: now must be a valid Date`);\n\t}\n\tconst { options } = ctx;\n\tconst { backups, keys } = await bindingOf(ctx);\n\tconst identities = [keys.identity];\n\tconst source = () =>\n\t\tmongoSource({ db: options.db, collections: options.collections });\n\tconst due = kindFor(\n\t\tawait listOf(ctx),\n\t\tnow,\n\t\toptions.fullEvery ?? DEFAULT_FULL_EVERY,\n\t);\n\tlet fellBack = false;\n\tconst created =\n\t\tdue === 'full'\n\t\t\t? await backups.create(source())\n\t\t\t: await backups\n\t\t\t\t\t.create(source(), { kind: 'incremental', identities })\n\t\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\t\tif (!(error instanceof MongoBackupError)) throw error;\n\t\t\t\t\t\tif (error.code !== 'HISTORY_LOST') throw error;\n\t\t\t\t\t\tfellBack = true;\n\t\t\t\t\t\treturn backups.create(source());\n\t\t\t\t\t});\n\tconst verified = await backups.verify(created.id, { identities });\n\tconst keep = options.keep ?? DEFAULT_KEEP;\n\t// Not `now`: backups carry the machine's time, so a later `now` would\n\t// rotate away the backup just made.\n\tconst removed = keep === false ? [] : (await backups.prune({ keep })).removed;\n\treturn {\n\t\tid: created.id,\n\t\tkind: created.kind === 'full' ? 'full' : 'incremental',\n\t\tfellBack,\n\t\tentries: created.entries,\n\t\tstoredSize: created.storedSize,\n\t\tchain: verified.chain.length,\n\t\tremoved: removed.map((decision) => decision.id),\n\t};\n}\n\n/**\n * The backup `at.at` names, into `at.into`: whole through `mongoTarget`,\n * or the part the options name through `restoreCollections`.\n */\nexport async function restoreAt(\n\tctx: Context,\n\tat: RestoreAtOptions,\n): Promise<RestoreReport> {\n\tconst where = named(ctx, 'restore');\n\tcheckRestore(at, where);\n\tconst { tmpDir } = ctx.options;\n\tconst { backups, keys } = await bindingOf(ctx);\n\tconst id = chosenBackup(await listOf(ctx), at.at, where);\n\tconst identities = [keys.identity];\n\tconst part =\n\t\tat.collections !== undefined ||\n\t\tat.as !== undefined ||\n\t\tat.documents !== undefined;\n\tif (!part) {\n\t\treturn backups.restore(\n\t\t\tid,\n\t\t\tmongoTarget({ db: at.into, replace: at.replace, tmpDir }),\n\t\t\t{ identities },\n\t\t);\n\t}\n\treturn restoreSome(\n\t\tbackups,\n\t\tid,\n\t\t{\n\t\t\tidentities,\n\t\t\tdb: at.into,\n\t\t\tcollections: at.collections,\n\t\t\tas: at.as,\n\t\t\ttmpDir,\n\t\t\t...(at.documents === undefined\n\t\t\t\t? { replace: at.replace }\n\t\t\t\t: { documents: at.documents }),\n\t\t},\n\t\twhere,\n\t);\n}\n\n/** The newest backup, chain included, into a database of its own, counted, dropped. */\nexport async function drillNewest(ctx: Context): Promise<DrillReport> {\n\tconst { db, tmpDir } = ctx.options;\n\tconst { backups, keys } = await bindingOf(ctx);\n\tconst id = chosenBackup(await listOf(ctx), undefined, named(ctx, 'drill'));\n\tconst drill = db.client.db(`nxgt-drill-${crypto.randomUUID()}`);\n\ttry {\n\t\tawait backups.restore(id, mongoTarget({ db: drill, tmpDir }), {\n\t\t\tidentities: [keys.identity],\n\t\t});\n\t\treturn { id, collections: await countsOf(drill) };\n\t} finally {\n\t\tawait drill.dropDatabase().catch(() => undefined);\n\t}\n}\n",
|
|
7
|
+
"import {\n\tBSON,\n\ttype ClientSession,\n\ttype Db,\n\ttype Document,\n\ttype Timestamp,\n} from 'mongodb';\nimport { MongoBackupError, serverCode } from '../errors';\nimport type { Metadata } from '../format/metadata';\nimport { type CollectionFilter, type Listed, listed } from './collections';\n\n/** The server found no collection by that name. */\nconst NAMESPACE_NOT_FOUND = 26;\n\n/** How many times the pin is taken again while the collections change. */\nconst ATTEMPTS = 5;\n\n/** A collection or a view, with what a backup records of it besides its documents. */\nexport interface Described extends Listed {\n\tmetadata: Metadata;\n}\n\n/** Its indexes, `_id` apart, as `listIndexes` gave them less `v` and `ns`. */\nasync function indexesOf(db: Db, collection: Listed): Promise<Document[]> {\n\tif (collection.type === 'view') return [];\n\tconst indexes = await db.collection(collection.name).listIndexes().toArray();\n\treturn indexes\n\t\t.filter((index) => index['name'] !== '_id_')\n\t\t.map(({ v: _v, ns: _ns, ...index }) => index);\n}\n\n/**\n * The collections and views the filter takes, each with its options and\n * indexes — or nothing when one went while they were being read.\n */\nexport async function describe(\n\tdb: Db,\n\tfilter: CollectionFilter | undefined,\n): Promise<Described[] | undefined> {\n\tconst found: Described[] = [];\n\ttry {\n\t\tfor (const collection of await listed(db, filter)) {\n\t\t\tconst indexes = await indexesOf(db, collection);\n\t\t\tfound.push({\n\t\t\t\t...collection,\n\t\t\t\tmetadata: {\n\t\t\t\t\ttype: collection.type,\n\t\t\t\t\toptions: collection.options,\n\t\t\t\t\tindexes,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tif (serverCode(error) === NAMESPACE_NOT_FOUND) return undefined;\n\t\tthrow error;\n\t}\n\treturn found;\n}\n\n/**\n * A snapshot session with its cluster time fixed: a session takes the time\n * of its first read, so one is made at once — a `distinct` on a\n * collection no one has, which reads nothing and is the read whose reply\n * carries that time — rather than whenever the first entry is opened.\n */\nasync function pin(db: Db): Promise<{ session: ClientSession; at: Timestamp }> {\n\tconst session = db.client.startSession({ snapshot: true });\n\ttry {\n\t\tawait db\n\t\t\t.collection(`nxgt-snapshot-${crypto.randomUUID()}`)\n\t\t\t.distinct('_id', {}, { session });\n\t\tconst at = (session as { snapshotTime?: Timestamp }).snapshotTime;\n\t\tif (!at) {\n\t\t\tthrow new MongoBackupError(\n\t\t\t\t'mongoSource: the server gave no snapshot time; a backup needs a ' +\n\t\t\t\t\t'replica set or a sharded cluster',\n\t\t\t\t'UNSUPPORTED',\n\t\t\t);\n\t\t}\n\t\treturn { session, at };\n\t} catch (error) {\n\t\tawait session.endSession();\n\t\tthrow error;\n\t}\n}\n\nconst same = (a: Described[] | undefined, b: Described[] | undefined) =>\n\ta !== undefined &&\n\tb !== undefined &&\n\tBSON.EJSON.stringify(a, { relaxed: false }) ===\n\t\tBSON.EJSON.stringify(b, { relaxed: false });\n\n/**\n * The snapshot, and what it holds besides documents. The collections, their\n * options and their indexes are not read in a snapshot — the server does\n * not serve those reads at a cluster time — so they are read before the\n * pin and again after it: the same both times, they are what the snapshot\n * holds. Otherwise the pin is taken again, up to five times, then\n * `CHANGING`.\n */\nexport async function pinnedCatalog(\n\tdb: Db,\n\tfilter: CollectionFilter | undefined,\n): Promise<{ session: ClientSession; at: Timestamp; catalog: Described[] }> {\n\tfor (let attempt = 0; attempt < ATTEMPTS; attempt++) {\n\t\tconst before = await describe(db, filter);\n\t\tconst pinned = await pin(db);\n\t\tconst after = await describe(db, filter).catch(async (error: unknown) => {\n\t\t\tawait pinned.session.endSession();\n\t\t\tthrow error;\n\t\t});\n\t\tif (same(before, after)) {\n\t\t\treturn { ...pinned, catalog: after as Described[] };\n\t\t}\n\t\tawait pinned.session.endSession();\n\t}\n\tthrow new MongoBackupError(\n\t\t'mongoSource: the collections or their indexes kept changing while the ' +\n\t\t\t'snapshot was taken; try again when they settle',\n\t\t'CHANGING',\n\t);\n}\n\n/** The first cluster time after `at`: what the snapshot read at `at` does not hold. */\nexport function after(at: Timestamp): Timestamp {\n\treturn at.i === 0xffffffff\n\t\t? new BSON.Timestamp({ t: at.t + 1, i: 0 })\n\t\t: new BSON.Timestamp({ t: at.t, i: at.i + 1 });\n}\n",
|
|
8
|
+
"import { BSON, type Db, type Document } from 'mongodb';\nimport { MongoBackupError } from '../errors';\n\n/** Which collections a backup reads: their names, or a test on each name. */\nexport type CollectionFilter = readonly string[] | ((name: string) => boolean);\n\n/** A collection or a view, as `listCollections` described it. */\nexport interface Listed {\n\tname: string;\n\ttype: 'collection' | 'view';\n\toptions: Document;\n\t/** Its UUID, as Extended JSON: a collection dropped and made again has another. */\n\tuuid: string;\n}\n\n/** Whether `name` is one the filter takes; `system.*` never is. */\nexport function takes(\n\tfilter: CollectionFilter | undefined,\n\tname: string,\n): boolean {\n\tif (name.startsWith('system.')) return false;\n\tif (filter === undefined) return true;\n\treturn typeof filter === 'function' ? filter(name) : filter.includes(name);\n}\n\n/**\n * The collections and views the filter takes, sorted by name. A name the\n * filter lists that the database lacks is a `TypeError`: a typo would\n * otherwise back up nothing, and say nothing.\n */\nexport async function listed(\n\tdb: Db,\n\tfilter: CollectionFilter | undefined,\n): Promise<Listed[]> {\n\tconst all = await db.listCollections({}, { nameOnly: false }).toArray();\n\tconst found: Listed[] = [];\n\tfor (const info of all) {\n\t\tif (!takes(filter, info.name)) continue;\n\t\tif (info.type !== 'collection' && info.type !== 'view') {\n\t\t\tthrow new MongoBackupError(\n\t\t\t\t'mongoSource: a collection is of a type this version does not back up ' +\n\t\t\t\t\t'(a time-series one); leave it out with collections',\n\t\t\t\t'UNSUPPORTED',\n\t\t\t);\n\t\t}\n\t\tfound.push({\n\t\t\tname: info.name,\n\t\t\ttype: info.type,\n\t\t\toptions: (info as { options?: Document }).options ?? {},\n\t\t\tuuid: BSON.EJSON.stringify(\n\t\t\t\t(info as { info?: { uuid?: unknown } }).info?.uuid ?? null,\n\t\t\t),\n\t\t});\n\t}\n\tif (Array.isArray(filter)) {\n\t\tconst names = new Set(found.map((c) => c.name));\n\t\tif (!filter.every((name) => names.has(name))) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'mongoSource: a collection named in collections is not in the database',\n\t\t\t);\n\t\t}\n\t}\n\treturn found.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n",
|
|
9
|
+
"import { tmpdir } from 'node:os';\nimport { isAbsolute } from 'node:path';\nimport type { RestoreTarget } from '@softistx/backup';\nimport type { Db } from 'mongodb';\nimport { MongoBackupError } from '../errors';\nimport { type Metadata, readMetadata } from '../format/metadata';\nimport { parseName } from '../format/names';\nimport { restoreChanges } from './changes';\nimport { restoreCollection, restoreView } from './collection';\n\nexport interface MongoTargetOptions {\n\t/** The database to restore into: the one backed up, or another. */\n\tdb: Db;\n\t/**\n\t * Replace a collection or view already there. `false` by default: one\n\t * there is refused with `EXISTS`, and nothing of it is touched.\n\t */\n\treplace?: boolean | undefined;\n\t/** Where a `changes/<n>` entry is staged before it applies. The system's temporary folder by default. */\n\ttmpDir?: string | undefined;\n}\n\n/** The longest metadata entry read: options and indexes, never documents. */\nconst METADATA_MAX_BYTES = 16 * 1024 * 1024;\n\nconst malformed = (what: string) =>\n\tnew MongoBackupError(`mongoTarget: ${what}`, 'MALFORMED');\n\nasync function metadataFrom(\n\tstream: ReadableStream<Uint8Array>,\n): Promise<Metadata> {\n\tconst chunks: Uint8Array[] = [];\n\tlet size = 0;\n\tfor await (const chunk of stream) {\n\t\tsize += chunk.length;\n\t\tif (size > METADATA_MAX_BYTES) {\n\t\t\tawait stream.cancel().catch(() => undefined);\n\t\t\tthrow malformed('a metadata entry is larger than 16 MiB');\n\t\t}\n\t\tchunks.push(chunk);\n\t}\n\tconst metadata = readMetadata(\n\t\tnew TextDecoder().decode(Buffer.concat(chunks)),\n\t);\n\tif (!metadata)\n\t\tthrow malformed('a metadata entry is not one this version wrote');\n\treturn metadata;\n}\n\nfunction checkOptions(options: MongoTargetOptions): void {\n\tconst db = options?.db as Partial<Db> | undefined;\n\tif (\n\t\ttypeof db?.collection !== 'function' ||\n\t\ttypeof db.databaseName !== 'string'\n\t) {\n\t\tthrow new TypeError('mongoTarget: db must be a MongoDB Db');\n\t}\n\tif (options.tmpDir !== undefined && !isAbsolute(options.tmpDir)) {\n\t\tthrow new TypeError('mongoTarget: tmpDir must be an absolute path');\n\t}\n}\n\n/**\n * A MongoDB database as a restore target. Takes the entries a\n * `mongoSource` backup holds, in their order: each collection's metadata,\n * then its documents — landed whole or not at all — then the changes an\n * incremental backup recorded, applied once each entry was read and\n * checked to its end. A view is created from its metadata.\n */\nexport function mongoTarget(options: MongoTargetOptions): RestoreTarget {\n\tcheckOptions(options);\n\tconst { db } = options;\n\tconst replace = options.replace === true;\n\tconst tmpDir = options.tmpDir ?? tmpdir();\n\tconst metadata = new Map<string, Metadata>();\n\treturn {\n\t\tasync write(name, stream) {\n\t\t\tconst parsed = parseName(name);\n\t\t\tif (!parsed) {\n\t\t\t\tawait stream.cancel();\n\t\t\t\tthrow malformed('an entry name is not one this version writes');\n\t\t\t}\n\t\t\tif (parsed.kind === 'changes') {\n\t\t\t\treturn restoreChanges(db, stream, tmpDir, replace);\n\t\t\t}\n\t\t\tif (parsed.kind === 'metadata') {\n\t\t\t\tconst read = await metadataFrom(stream);\n\t\t\t\tmetadata.set(parsed.collection, read);\n\t\t\t\tif (read.type === 'view') {\n\t\t\t\t\tawait restoreView(db, parsed.collection, read, replace);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst known = metadata.get(parsed.collection);\n\t\t\tif (!known) {\n\t\t\t\tawait stream.cancel();\n\t\t\t\tthrow malformed('a collection’s documents came before its metadata');\n\t\t\t}\n\t\t\tawait restoreCollection(db, parsed.collection, known, stream, replace);\n\t\t},\n\t};\n}\n",
|
|
10
|
+
"import { BSON, type Document } from 'mongodb';\nimport { isDocument } from './document';\n\nconst METADATA_FORMAT = 'nxgt-mongo-backup-metadata/1';\n\n/** What a backup records of a collection or a view, besides its documents. */\nexport interface Metadata {\n\ttype: 'collection' | 'view';\n\t/** What `listCollections` gave as its options: validator, collation, capped… */\n\toptions: Document;\n\t/** Its indexes as `listIndexes` gave them, `_id` apart. */\n\tindexes: Document[];\n}\n\n/** `metadata` as the backup records it: canonical Extended JSON. */\nexport function writeMetadata(metadata: Metadata): string {\n\treturn BSON.EJSON.stringify(\n\t\t{ format: METADATA_FORMAT, ...metadata },\n\t\t{ relaxed: false },\n\t);\n}\n\n/** The metadata an entry holds, or nothing when it is not one this version wrote. */\nexport function readMetadata(text: string): Metadata | undefined {\n\tlet value: unknown;\n\ttry {\n\t\tvalue = BSON.EJSON.parse(text, { relaxed: false });\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!isDocument(value) || value['format'] !== METADATA_FORMAT) {\n\t\treturn undefined;\n\t}\n\tconst { type, options, indexes } = value;\n\tif (\n\t\t(type !== 'collection' && type !== 'view') ||\n\t\t!isDocument(options) ||\n\t\t!Array.isArray(indexes) ||\n\t\t!indexes.every(\n\t\t\t(index) => isDocument(index) && typeof index['name'] === 'string',\n\t\t)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn { type, options, indexes: indexes as Document[] };\n}\n",
|
|
11
|
+
"import type { Document } from 'mongodb';\n\n/**\n * Whether `value` is a document: an object that is neither an array nor a\n * BSON value — read with `promoteValues: false`, an `Int32` is an object too.\n */\nexport function isDocument(value: unknown): value is Document {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t!Array.isArray(value) &&\n\t\t!('_bsontype' in value)\n\t);\n}\n",
|
|
12
|
+
"/**\n * How entries are named: `metadata/<collection>` (its options and indexes,\n * as canonical Extended JSON), `documents/<collection>` (its documents, as\n * concatenated BSON, the format `mongodump` writes), `changes/<n>` (the\n * changes an incremental or differential backup read, as concatenated BSON,\n * numbered in the order they apply).\n */\nexport const METADATA = 'metadata/';\nexport const DOCUMENTS = 'documents/';\nexport const CHANGES = 'changes/';\n\nexport type EntryName =\n\t| { kind: 'metadata' | 'documents'; collection: string }\n\t| { kind: 'changes'; sequence: number };\n\n/** What an entry name says, or nothing when it is not one this version writes. */\nexport function parseName(name: string): EntryName | undefined {\n\tfor (const [prefix, kind] of [\n\t\t[METADATA, 'metadata'],\n\t\t[DOCUMENTS, 'documents'],\n\t] as const) {\n\t\tif (name.startsWith(prefix) && name.length > prefix.length) {\n\t\t\treturn { kind, collection: name.slice(prefix.length) };\n\t\t}\n\t}\n\tif (name.startsWith(CHANGES)) {\n\t\tconst digits = name.slice(CHANGES.length);\n\t\tif (/^\\d{6,9}$/.test(digits)) {\n\t\t\treturn { kind: 'changes', sequence: Number.parseInt(digits, 10) };\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The name of the `sequence`th changes entry. */\nexport function changesName(sequence: number): string {\n\treturn `${CHANGES}${String(sequence).padStart(6, '0')}`;\n}\n",
|
|
13
|
+
"import { mkdtemp, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type {\n\tAnyBulkWriteOperation,\n\tDb,\n\tDocument,\n\tIndexDescription,\n} from 'mongodb';\nimport { MongoBackupError, serverCode } from '../errors';\nimport { bsonDocuments } from '../format/bson-stream';\nimport { type Change, readChange } from '../format/change';\nimport { dropIfThere, exists, taken } from './collection';\n\n/** The server found no collection by that name. */\nconst NAMESPACE_NOT_FOUND = 26;\n\nconst BATCH = 1000;\n\n/** The write one document change makes, as a bulk operation. */\nfunction operationsOf(\n\tchange: Extract<Change, { key: Document }>,\n): AnyBulkWriteOperation[] {\n\tswitch (change.op) {\n\t\tcase 'insert':\n\t\tcase 'replace':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\treplaceOne: {\n\t\t\t\t\t\tfilter: change.key,\n\t\t\t\t\t\treplacement: change.doc,\n\t\t\t\t\t\tupsert: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'delete':\n\t\t\treturn [{ deleteOne: { filter: change.key } }];\n\t\tcase 'update': {\n\t\t\t// Arrays cut first, as the server reports them, then the fields set.\n\t\t\tconst cuts: AnyBulkWriteOperation[] = change.truncated.map((cut) => ({\n\t\t\t\tupdateOne: {\n\t\t\t\t\tfilter: change.key,\n\t\t\t\t\tupdate: {\n\t\t\t\t\t\t$push: { [cut.field]: { $each: [], $slice: cut.newSize } },\n\t\t\t\t\t} as Document,\n\t\t\t\t},\n\t\t\t}));\n\t\t\tconst update: Document = {};\n\t\t\tif (Object.keys(change.set).length > 0) update['$set'] = change.set;\n\t\t\tif (change.unset.length > 0) {\n\t\t\t\tupdate['$unset'] = Object.fromEntries(change.unset.map((f) => [f, '']));\n\t\t\t}\n\t\t\treturn Object.keys(update).length === 0\n\t\t\t\t? cuts\n\t\t\t\t: [...cuts, { updateOne: { filter: change.key, update } }];\n\t\t}\n\t}\n}\n\n/** The server refused a name already taken. */\nconst NAMESPACE_EXISTS = 48;\n\n/** The server found no index by that name. */\nconst INDEX_NOT_FOUND = 27;\n\nconst ignoring =\n\t(...codes: number[]) =>\n\t(error: unknown) => {\n\t\tif (!codes.includes(serverCode(error) ?? 0)) throw error;\n\t};\n\n/**\n * A change to a collection itself, or to the database. A collection the\n * changes create that is already there is refused, as a full restore\n * refuses one — or replaced, with `replace`.\n */\nasync function applyToCollection(\n\tdb: Db,\n\tchange: Exclude<Change, { key: Document }>,\n\treplace: boolean,\n): Promise<void> {\n\tswitch (change.op) {\n\t\tcase 'create':\n\t\t\tif (await exists(db, change.coll)) {\n\t\t\t\tif (!replace) throw taken();\n\t\t\t\tawait dropIfThere(db, change.coll);\n\t\t\t}\n\t\t\tawait db.createCollection(change.coll, change.options);\n\t\t\treturn;\n\t\tcase 'createIndexes':\n\t\t\tawait db\n\t\t\t\t.collection(change.coll)\n\t\t\t\t.createIndexes(change.indexes as IndexDescription[]);\n\t\t\treturn;\n\t\tcase 'dropIndexes':\n\t\t\tfor (const name of change.names) {\n\t\t\t\tawait db\n\t\t\t\t\t.collection(change.coll)\n\t\t\t\t\t.dropIndex(name)\n\t\t\t\t\t.catch(ignoring(INDEX_NOT_FOUND, NAMESPACE_NOT_FOUND));\n\t\t\t}\n\t\t\treturn;\n\t\tcase 'modify':\n\t\t\tawait db\n\t\t\t\t.command({ collMod: change.coll, ...change.changes })\n\t\t\t\t.catch(ignoring(NAMESPACE_NOT_FOUND));\n\t\t\treturn;\n\t\tcase 'drop':\n\t\t\treturn dropIfThere(db, change.coll);\n\t\tcase 'rename':\n\t\t\t// A collection the rename did not replace at the source is not\n\t\t\t// one to replace here, unless `replace` says so: the server refuses\n\t\t\t// a name taken, even one taken a moment ago.\n\t\t\tawait db\n\t\t\t\t.renameCollection(change.coll, change.to, {\n\t\t\t\t\tdropTarget: change.dropTarget || replace,\n\t\t\t\t})\n\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\tif (serverCode(error) === NAMESPACE_EXISTS) throw taken();\n\t\t\t\t\tignoring(NAMESPACE_NOT_FOUND)(error);\n\t\t\t\t});\n\t\t\treturn;\n\t\tcase 'dropDatabase':\n\t\t\tawait db.dropDatabase();\n\t\t\treturn;\n\t}\n}\n\n/**\n * Applies the changes staged in `file`, in order: runs of document changes\n * to one collection go as ordered bulk writes, and a change to a\n * collection itself applies between them.\n */\nasync function applyFile(\n\tdb: Db,\n\tfile: string,\n\treplace: boolean,\n): Promise<void> {\n\tlet coll = '';\n\tlet pending: AnyBulkWriteOperation[] = [];\n\tconst flush = async () => {\n\t\tif (pending.length > 0) {\n\t\t\tawait db\n\t\t\t\t.collection(coll)\n\t\t\t\t.bulkWrite(pending, { ordered: true, bypassDocumentValidation: true });\n\t\t}\n\t\tpending = [];\n\t};\n\tfor await (const bytes of bsonDocuments(\n\t\tBun.file(file).stream(),\n\t\t'mongoTarget',\n\t)) {\n\t\tconst change = readChange(bytes);\n\t\tif (!change) {\n\t\t\tthrow new MongoBackupError(\n\t\t\t\t'mongoTarget: a change is not one this version wrote',\n\t\t\t\t'MALFORMED',\n\t\t\t);\n\t\t}\n\t\tif (!('key' in change)) {\n\t\t\tawait flush();\n\t\t\tawait applyToCollection(db, change, replace);\n\t\t\tcontinue;\n\t\t}\n\t\tif (change.coll !== coll || pending.length >= BATCH) await flush();\n\t\tcoll = change.coll;\n\t\tpending.push(...operationsOf(change));\n\t}\n\tawait flush();\n}\n\n/**\n * Takes a `changes/<n>` entry: staged to a file in `tmpDir` until its\n * stream has ended cleanly — a change applied is not taken back, so none\n * is applied before the backup's checks have passed — then applied.\n */\nexport async function restoreChanges(\n\tdb: Db,\n\tstream: ReadableStream<Uint8Array>,\n\ttmpDir: string,\n\treplace: boolean,\n): Promise<void> {\n\t// A folder of its own, which only this user can read: the changes hold\n\t// whole documents, in the clear.\n\tconst folder = await mkdtemp(join(tmpDir, 'nxgt-mongo-changes-'));\n\ttry {\n\t\tconst file = join(folder, 'changes.bson');\n\t\tawait Bun.write(file, new Response(stream));\n\t\tawait applyFile(db, file, replace);\n\t} finally {\n\t\tawait rm(folder, { recursive: true, force: true });\n\t}\n}\n",
|
|
14
|
+
"import { MongoBackupError } from '../errors';\n\n/**\n * The largest document read back: the server's 16 MiB, and room for the\n * fields a change record adds around one.\n */\nexport const DOCUMENT_MAX_BYTES = 17 * 1024 * 1024;\n\n/**\n * The BSON documents of a stream of concatenated ones — each its own bytes,\n * length first, as `mongodump` writes them. Each is filled in place as the\n * chunks arrive, so a large one is copied once. A length that is not one,\n * or a stream that ends inside a document, is `MALFORMED`.\n */\nexport async function* bsonDocuments(\n\tstream: ReadableStream<Uint8Array>,\n\twhere: string,\n): AsyncGenerator<Uint8Array> {\n\tconst malformed = () =>\n\t\tnew MongoBackupError(\n\t\t\t`${where}: an entry is not a sequence of BSON documents`,\n\t\t\t'MALFORMED',\n\t\t);\n\tlet carry = new Uint8Array(0);\n\tlet document: Uint8Array | undefined;\n\tlet filled = 0;\n\tfor await (const chunk of stream) {\n\t\tconst data = carry.length === 0 ? chunk : concat(carry, chunk);\n\t\tcarry = new Uint8Array(0);\n\t\tlet offset = 0;\n\t\twhile (offset < data.length) {\n\t\t\tif (document) {\n\t\t\t\tconst n = Math.min(document.length - filled, data.length - offset);\n\t\t\t\tdocument.set(data.subarray(offset, offset + n), filled);\n\t\t\t\tfilled += n;\n\t\t\t\toffset += n;\n\t\t\t\tif (filled === document.length) {\n\t\t\t\t\tyield document;\n\t\t\t\t\tdocument = undefined;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (data.length - offset < 4) {\n\t\t\t\tcarry = data.slice(offset);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst length = new DataView(\n\t\t\t\tdata.buffer,\n\t\t\t\tdata.byteOffset + offset,\n\t\t\t\t4,\n\t\t\t).getInt32(0, true);\n\t\t\tif (length < 5 || length > DOCUMENT_MAX_BYTES) throw malformed();\n\t\t\tdocument = new Uint8Array(length);\n\t\t\tfilled = 0;\n\t\t}\n\t}\n\tif (document || carry.length > 0) throw malformed();\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n\tconst joined = new Uint8Array(a.length + b.length);\n\tjoined.set(a);\n\tjoined.set(b, a.length);\n\treturn joined;\n}\n",
|
|
15
|
+
"import { BSON, type Document } from 'mongodb';\nimport { isDocument } from './document';\n\n/**\n * One change as a backup records it: what applying it again needs, and no\n * more — a document written, updated or deleted, or a collection created,\n * indexed, modified, renamed or dropped.\n */\nexport type Change =\n\t| { op: 'insert' | 'replace'; coll: string; key: Document; doc: Document }\n\t| {\n\t\t\top: 'update';\n\t\t\tcoll: string;\n\t\t\tkey: Document;\n\t\t\tset: Document;\n\t\t\tunset: string[];\n\t\t\ttruncated: { field: string; newSize: number }[];\n\t }\n\t| { op: 'delete'; coll: string; key: Document }\n\t| { op: 'create'; coll: string; options: Document }\n\t| { op: 'createIndexes'; coll: string; indexes: Document[] }\n\t| { op: 'dropIndexes'; coll: string; names: string[] }\n\t| { op: 'modify'; coll: string; changes: Document }\n\t| { op: 'drop'; coll: string }\n\t| { op: 'rename'; coll: string; to: string; dropTarget: boolean }\n\t| { op: 'dropDatabase' };\n\n/** What BSON keeps exactly: no number becomes another kind of number. */\nexport const EXACT = { promoteValues: false, bsonRegExp: true } as const;\n\nexport function writeChange(change: Change): Uint8Array {\n\treturn BSON.serialize(change);\n}\n\nconst isStrings = (value: unknown): value is string[] =>\n\tArray.isArray(value) && value.every((item) => typeof item === 'string');\n\n/** The change a record holds, or nothing when it is not one this version wrote. */\nexport function readChange(bytes: Uint8Array): Change | undefined {\n\tconst value = BSON.deserialize(bytes, EXACT);\n\tconst { op, coll } = value;\n\tif (op === 'dropDatabase') return { op };\n\tif (typeof coll !== 'string' || coll.length === 0) return undefined;\n\tswitch (op) {\n\t\tcase 'insert':\n\t\tcase 'replace':\n\t\t\treturn isDocument(value['key']) && isDocument(value['doc'])\n\t\t\t\t? { op, coll, key: value['key'], doc: value['doc'] }\n\t\t\t\t: undefined;\n\t\tcase 'update':\n\t\t\treturn readUpdate(coll, value);\n\t\tcase 'delete':\n\t\t\treturn isDocument(value['key'])\n\t\t\t\t? { op, coll, key: value['key'] }\n\t\t\t\t: undefined;\n\t\tcase 'create':\n\t\t\treturn isDocument(value['options'])\n\t\t\t\t? { op, coll, options: value['options'] }\n\t\t\t\t: undefined;\n\t\tcase 'createIndexes': {\n\t\t\tconst indexes = value['indexes'];\n\t\t\treturn Array.isArray(indexes) && indexes.every(isDocument)\n\t\t\t\t? { op, coll, indexes }\n\t\t\t\t: undefined;\n\t\t}\n\t\tcase 'dropIndexes':\n\t\t\treturn isStrings(value['names'])\n\t\t\t\t? { op, coll, names: value['names'] }\n\t\t\t\t: undefined;\n\t\tcase 'modify':\n\t\t\treturn isDocument(value['changes'])\n\t\t\t\t? { op, coll, changes: value['changes'] }\n\t\t\t\t: undefined;\n\t\tcase 'drop':\n\t\t\treturn { op, coll };\n\t\tcase 'rename':\n\t\t\treturn typeof value['to'] === 'string' &&\n\t\t\t\ttypeof value['dropTarget'] === 'boolean'\n\t\t\t\t? { op, coll, to: value['to'], dropTarget: value['dropTarget'] }\n\t\t\t\t: undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction readUpdate(coll: string, value: Document): Change | undefined {\n\tconst { key, set, unset, truncated } = value;\n\tif (\n\t\t!isDocument(key) ||\n\t\t!isDocument(set) ||\n\t\t!isStrings(unset) ||\n\t\t!Array.isArray(truncated)\n\t) {\n\t\treturn undefined;\n\t}\n\tconst cuts: { field: string; newSize: number }[] = [];\n\tfor (const cut of truncated) {\n\t\tconst size = Number(cut?.newSize);\n\t\tif (typeof cut?.field !== 'string' || !Number.isSafeInteger(size)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tcuts.push({ field: cut.field, newSize: size });\n\t}\n\treturn { op: 'update', coll, key, set, unset, truncated: cuts };\n}\n",
|
|
16
|
+
"import { BSON, type Db, type Document, type IndexDescription } from 'mongodb';\nimport { MongoBackupError, serverCode } from '../errors';\nimport { bsonDocuments } from '../format/bson-stream';\nimport { EXACT } from '../format/change';\nimport type { Metadata } from '../format/metadata';\n\n/** The server refused a name already taken. */\nconst NAMESPACE_EXISTS = 48;\n/** The server found no collection by that name. */\nconst NAMESPACE_NOT_FOUND = 26;\n\nconst BATCH_DOCUMENTS = 1000;\nconst BATCH_BYTES = 8 * 1024 * 1024;\n\nexport function exists(db: Db, name: string): Promise<boolean> {\n\treturn db\n\t\t.listCollections({ name }, { nameOnly: true })\n\t\t.toArray()\n\t\t.then((found) => found.length > 0);\n}\n\n/** Whether `name` is a view in `db`. */\nexport async function isView(db: Db, name: string): Promise<boolean> {\n\tconst [found] = await db\n\t\t.listCollections({ name }, { nameOnly: true })\n\t\t.toArray();\n\treturn found?.type === 'view';\n}\n\nexport function taken(): MongoBackupError {\n\treturn new MongoBackupError(\n\t\t'mongoTarget: a collection or view the backup holds is already in the ' +\n\t\t\t'database; restore into another one, or pass replace: true',\n\t\t'EXISTS',\n\t);\n}\n\nexport async function dropIfThere(db: Db, name: string): Promise<void> {\n\tawait db.dropCollection(name).catch((error: unknown) => {\n\t\tif (serverCode(error) !== NAMESPACE_NOT_FOUND) throw error;\n\t});\n}\n\n/** A view, created from its metadata: in place of one there, with `replace`. */\nexport async function restoreView(\n\tdb: Db,\n\tname: string,\n\tmetadata: Metadata,\n\treplace: boolean,\n): Promise<void> {\n\tif (await exists(db, name)) {\n\t\tif (!replace) throw taken();\n\t\tawait dropIfThere(db, name);\n\t}\n\tawait db.createCollection(name, metadata.options);\n}\n\nasync function insertAll(\n\tdb: Db,\n\tstaging: string,\n\tstream: ReadableStream<Uint8Array>,\n): Promise<void> {\n\tconst collection = db.collection(staging);\n\tlet batch: Document[] = [];\n\tlet bytes = 0;\n\tconst flush = async () => {\n\t\tif (batch.length === 0) return;\n\t\tawait collection.insertMany(batch, {\n\t\t\tbypassDocumentValidation: true,\n\t\t\tordered: true,\n\t\t});\n\t\tbatch = [];\n\t\tbytes = 0;\n\t};\n\tfor await (const raw of bsonDocuments(stream, 'mongoTarget')) {\n\t\tbatch.push(BSON.deserialize(raw, EXACT));\n\t\tbytes += raw.length;\n\t\tif (batch.length >= BATCH_DOCUMENTS || bytes >= BATCH_BYTES) await flush();\n\t}\n\tawait flush();\n}\n\n/**\n * One collection, landed whole or not at all: created apart under a name\n * of its own with the options it had, filled, indexed, and renamed into\n * place only once its stream ended cleanly — the backup's checks run at\n * the end. Anything that fails on the way drops what was made apart.\n * Without `replace`, a collection already there is refused before any\n * document is read, and the rename itself refuses one made meanwhile.\n */\nexport async function restoreCollection(\n\tdb: Db,\n\tname: string,\n\tmetadata: Metadata,\n\tstream: ReadableStream<Uint8Array>,\n\treplace: boolean,\n): Promise<void> {\n\tif (!replace && (await exists(db, name))) {\n\t\tawait stream.cancel();\n\t\tthrow taken();\n\t}\n\tconst staging = `nxgt-restore-${crypto.randomUUID()}`;\n\ttry {\n\t\tawait db.createCollection(staging, metadata.options);\n\t\tawait insertAll(db, staging, stream);\n\t\tif (metadata.indexes.length > 0) {\n\t\t\tawait db\n\t\t\t\t.collection(staging)\n\t\t\t\t.createIndexes(metadata.indexes as IndexDescription[]);\n\t\t}\n\t\t// The server renames over a collection, never over a view: with\n\t\t// `replace`, one there is dropped first — once the documents landed.\n\t\tif (replace && (await isView(db, name))) await dropIfThere(db, name);\n\t\tawait db\n\t\t\t.collection(staging)\n\t\t\t.rename(name, { dropTarget: replace })\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tthrow serverCode(error) === NAMESPACE_EXISTS ? taken() : error;\n\t\t\t});\n\t} catch (error) {\n\t\tawait dropIfThere(db, staging).catch(() => undefined);\n\t\tthrow error;\n\t}\n}\n",
|
|
17
|
+
"import type { Db, IndexDescription } from 'mongodb';\nimport { MongoBackupError, serverCode } from '../errors';\nimport type { Described } from '../source/catalog';\nimport { dropIfThere, exists, isView } from '../target/collection';\nimport type { DocumentSelection } from './options';\n\n/** The server refused a name already taken. */\nconst NAMESPACE_EXISTS = 48;\n\n/** One collection or view of the backup, and the name it lands under. */\nexport interface Chosen {\n\tdescribed: Described;\n\tas: string;\n}\n\nexport function taken(where: string): MongoBackupError {\n\treturn new MongoBackupError(\n\t\t`${where}: a collection or view to restore is already in the ` +\n\t\t\t'database; restore it under another name, or pass replace: true',\n\t\t'EXISTS',\n\t);\n}\n\n/**\n * Each collection moved from `scratch` into `db` whole — a rename across\n * databases, which keeps its options and indexes — then each view made\n * again: on the collection's new name when that collection came too.\n * Without `replace`, a name taken is refused before anything moves, and\n * the rename itself refuses one taken meanwhile.\n */\nexport async function landWhole(\n\tscratch: Db,\n\tdb: Db,\n\tchosen: readonly Chosen[],\n\treplace: boolean,\n\twhere: string,\n): Promise<void> {\n\tif (!replace) {\n\t\tfor (const { as } of chosen) if (await exists(db, as)) throw taken(where);\n\t}\n\tconst renamed = new Map(chosen.map((c) => [c.described.name, c.as]));\n\tconst admin = db.client.db('admin');\n\tfor (const { described, as } of chosen) {\n\t\tif (described.type === 'view') continue;\n\t\t// The server renames over a collection, never over a view.\n\t\tif (replace && (await isView(db, as))) await dropIfThere(db, as);\n\t\tawait admin\n\t\t\t.command({\n\t\t\t\trenameCollection: `${scratch.databaseName}.${described.name}`,\n\t\t\t\tto: `${db.databaseName}.${as}`,\n\t\t\t\tdropTarget: replace,\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tthrow serverCode(error) === NAMESPACE_EXISTS ? taken(where) : error;\n\t\t\t});\n\t}\n\tfor (const { described, as } of chosen) {\n\t\tif (described.type !== 'view') continue;\n\t\tconst { viewOn, ...options } = described.metadata.options;\n\t\tif (replace) await dropIfThere(db, as);\n\t\tawait db\n\t\t\t.createCollection(as, {\n\t\t\t\t...options,\n\t\t\t\tviewOn: renamed.get(viewOn as string) ?? viewOn,\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tthrow serverCode(error) === NAMESPACE_EXISTS ? taken(where) : error;\n\t\t\t});\n\t}\n}\n\n/**\n * The documents `selection` takes from each collection in `scratch`,\n * merged into the one `db` has under its name — made first, with the\n * backup's options and indexes, when there is none. Views hold no\n * documents and are passed over. Says how many each collection gave.\n */\nexport async function landDocuments(\n\tscratch: Db,\n\tdb: Db,\n\tchosen: readonly Chosen[],\n\tselection: DocumentSelection,\n): Promise<Map<string, number>> {\n\tconst counts = new Map<string, number>();\n\tfor (const { described, as } of chosen) {\n\t\tif (described.type === 'view') continue;\n\t\tif (!(await exists(db, as))) await createLike(db, as, described);\n\t\tconst from = scratch.collection(described.name);\n\t\tcounts.set(described.name, await from.countDocuments(selection.filter));\n\t\tawait from\n\t\t\t.aggregate(\n\t\t\t\t[\n\t\t\t\t\t{ $match: selection.filter },\n\t\t\t\t\t{\n\t\t\t\t\t\t$merge: {\n\t\t\t\t\t\t\tinto: { db: db.databaseName, coll: as },\n\t\t\t\t\t\t\ton: '_id',\n\t\t\t\t\t\t\twhenMatched:\n\t\t\t\t\t\t\t\tselection.existing === 'replace' ? 'replace' : 'keepExisting',\n\t\t\t\t\t\t\twhenNotMatched: 'insert',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\t{ bypassDocumentValidation: true },\n\t\t\t)\n\t\t\t.toArray();\n\t}\n\treturn counts;\n}\n\n/** A collection made with `described`'s options and indexes; one made meanwhile is kept. */\nasync function createLike(db: Db, as: string, described: Described) {\n\tawait db\n\t\t.createCollection(as, described.metadata.options)\n\t\t.catch((error: unknown) => {\n\t\t\tif (serverCode(error) !== NAMESPACE_EXISTS) throw error;\n\t\t});\n\tconst { indexes } = described.metadata;\n\tif (indexes.length > 0) {\n\t\tawait db.collection(as).createIndexes(indexes as IndexDescription[]);\n\t}\n}\n",
|
|
18
|
+
"import type { Restored, RestoreOptions, RestoreTarget } from '@softistx/backup';\nimport type { Db, Document } from 'mongodb';\nimport { isDocument } from '../format/document';\nimport type { CollectionFilter } from '../source/collections';\n\n/** What `restoreCollections` needs of a bound backup: its `restore`. */\nexport interface Restorer {\n\trestore(\n\t\tid: string,\n\t\ttarget: RestoreTarget,\n\t\toptions: RestoreOptions,\n\t): Promise<Restored>;\n}\n\n/** Some documents of each collection, merged into what is there. */\nexport interface DocumentSelection {\n\t/** A query, as `find` takes it: `{ _id: id }`, or any other. */\n\tfilter: Document;\n\t/** What a document already there with the same `_id` becomes: the backup's, or kept. */\n\texisting: 'replace' | 'keep';\n}\n\ninterface Common {\n\t/** The age secret keys to open the backup with. */\n\tidentities: readonly string[];\n\t/** The repository to read from, by name. The first one by default. */\n\tfrom?: string | undefined;\n\t/** The database to restore into. */\n\tdb: Db;\n\t/** The collections and views to restore, by their name at the backup's time. All of them by default. */\n\tcollections?: CollectionFilter | undefined;\n\t/** The name each one is restored under. Its own by default. */\n\tas?:\n\t\t| Readonly<Record<string, string>>\n\t\t| ((name: string) => string)\n\t\t| undefined;\n\t/**\n\t * Where the backup is rebuilt first, chain included: an empty database,\n\t * dropped afterwards. A fresh `nxgt-restore-<uuid>` on `db`'s client by\n\t * default.\n\t */\n\tscratch?: Db | undefined;\n\t/** Where a `changes/<n>` entry is staged. The system's temporary folder by default. */\n\ttmpDir?: string | undefined;\n}\n\n/** Whole collections and views, each landed whole or not at all. */\ninterface Whole extends Common {\n\tdocuments?: undefined;\n\t/** Replace a collection or view already there. `false` by default: `EXISTS`. */\n\treplace?: boolean | undefined;\n}\n\n/** Some documents of each collection, merged into the collection there. */\ninterface Part extends Common {\n\tdocuments: DocumentSelection;\n\treplace?: never;\n}\n\nexport type RestoreCollectionsOptions = Whole | Part;\n\n/** What was restored: the backup's entries, and each collection and where it went. */\nexport interface RestoredCollections extends Restored {\n\tcollections: { name: string; as: string; documents?: number }[];\n}\n\nconst NAME = /^[^$\\0]+$/;\n\n/** The name `name` is restored under, checked. */\nexport function destinationOf(\n\tas: RestoreCollectionsOptions['as'],\n\tname: string,\n\twhere = 'restoreCollections',\n): string {\n\tconst to =\n\t\tas === undefined\n\t\t\t? name\n\t\t\t: typeof as === 'function'\n\t\t\t\t? as(name)\n\t\t\t\t: Object.hasOwn(as, name)\n\t\t\t\t\t? as[name]\n\t\t\t\t\t: name;\n\tif (typeof to !== 'string' || !NAME.test(to) || to.startsWith('system.')) {\n\t\tthrow new TypeError(`${where}: as must give a collection name`);\n\t}\n\treturn to;\n}\n\n/** A record `as` is checked at once; a function only once the names are known. */\nfunction checkAs(as: RestoreCollectionsOptions['as'], where: string): void {\n\tif (as === undefined || typeof as === 'function') return;\n\tconst names = Object.keys(as);\n\tconst targets = names.map((name) => destinationOf(as, name, where));\n\tif (new Set(targets).size !== targets.length) {\n\t\tthrow new TypeError(`${where}: as gives two collections one name`);\n\t}\n}\n\nfunction isDb(value: unknown): value is Db {\n\tconst db = value as Partial<Db> | undefined;\n\treturn (\n\t\ttypeof db?.collection === 'function' && typeof db.databaseName === 'string'\n\t);\n}\n\nexport function checkOptions(\n\toptions: RestoreCollectionsOptions,\n\twhere: string,\n): void {\n\tif (!isDb(options?.db)) {\n\t\tthrow new TypeError(`${where}: db must be a MongoDB Db`);\n\t}\n\tif (options.scratch !== undefined && !isDb(options.scratch)) {\n\t\tthrow new TypeError(`${where}: scratch must be a MongoDB Db`);\n\t}\n\tif (\n\t\toptions.scratch !== undefined &&\n\t\toptions.scratch.client !== options.db.client\n\t) {\n\t\tthrow new TypeError(`${where}: scratch must be on db's client`);\n\t}\n\tif (options.scratch?.databaseName === options.db.databaseName) {\n\t\tthrow new TypeError(`${where}: scratch must be another database`);\n\t}\n\tcheckAs(options.as, where);\n\tconst { documents } = options;\n\tif (\n\t\tdocuments !== undefined &&\n\t\t(!isDocument(documents?.filter) ||\n\t\t\t(documents.existing !== 'replace' && documents.existing !== 'keep'))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: documents must be { filter, existing: 'replace' | 'keep' }`,\n\t\t);\n\t}\n\tif (documents !== undefined && options.replace !== undefined) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: replace is for whole collections; documents says what happens to those there`,\n\t\t);\n\t}\n}\n",
|
|
19
|
+
"import type { Db } from 'mongodb';\nimport { MongoBackupError, renamed } from '../errors';\nimport { describe } from '../source/catalog';\nimport { mongoTarget } from '../target/mongo-target';\nimport { type Chosen, landDocuments, landWhole } from './landing';\nimport {\n\tcheckOptions,\n\tdestinationOf,\n\ttype RestoreCollectionsOptions,\n\ttype RestoredCollections,\n\ttype Restorer,\n} from './options';\n\n/** A scratch database given must hold nothing: it is dropped afterwards. */\nasync function checkEmpty(scratch: Db, where: string): Promise<void> {\n\tconst held = await scratch.listCollections({}, { nameOnly: true }).toArray();\n\tif (held.some((info) => !info.name.startsWith('system.'))) {\n\t\tthrow new MongoBackupError(\n\t\t\t`${where}: the scratch database holds collections; give an empty one`,\n\t\t\t'EXISTS',\n\t\t);\n\t}\n}\n\n/**\n * Every key of an `as` record names one restored: a typo would otherwise\n * land that collection under its own name — over the live one.\n */\nfunction checkAsKeys(\n\tas: RestoreCollectionsOptions['as'],\n\tdescribed: readonly { name: string }[],\n\twhere: string,\n): void {\n\tif (as === undefined || typeof as === 'function') return;\n\tconst names = new Set(described.map((d) => d.name));\n\tif (!Object.keys(as).every((key) => names.has(key))) {\n\t\tthrow new TypeError(`${where}: as names a collection not restored`);\n\t}\n}\n\n/** The collections and views to restore, each with the name it lands under. */\nasync function choose(\n\tscratch: Db,\n\toptions: RestoreCollectionsOptions,\n\twhere: string,\n): Promise<Chosen[]> {\n\tconst { collections } = options;\n\tif (Array.isArray(collections)) {\n\t\tconst held = await scratch\n\t\t\t.listCollections({}, { nameOnly: true })\n\t\t\t.toArray();\n\t\tconst names = new Set(\n\t\t\theld.map((info) => info.name).filter((n) => !n.startsWith('system.')),\n\t\t);\n\t\tif (!collections.every((name) => names.has(name))) {\n\t\t\tthrow new MongoBackupError(\n\t\t\t\t`${where}: a collection named in collections is not in the backup`,\n\t\t\t\t'NOT_FOUND',\n\t\t\t);\n\t\t}\n\t}\n\t// Views hold no documents: some documents take none of them.\n\tconst described = ((await describe(scratch, collections)) ?? []).filter(\n\t\t(d) => !options.documents || d.type !== 'view',\n\t);\n\tcheckAsKeys(options.as, described, where);\n\tconst chosen = described.map((d) => ({\n\t\tdescribed: d,\n\t\tas: destinationOf(options.as, d.name, where),\n\t}));\n\tif (new Set(chosen.map((c) => c.as)).size !== chosen.length) {\n\t\tthrow new TypeError(`${where}: as gives two collections one name`);\n\t}\n\treturn chosen;\n}\n\n/**\n * Some of a `mongoSource` backup, chain included, restored into `db`: the\n * collections and views `collections` names, each under the name `as`\n * gives it — whole, or only the documents `documents` selects, merged into\n * what is there. The backup is rebuilt in `scratch` first, then what was\n * asked for is taken from it, and `scratch` is dropped, failed or not.\n */\nexport function restoreCollections(\n\tbackups: Restorer,\n\tid: string,\n\toptions: RestoreCollectionsOptions,\n): Promise<RestoredCollections> {\n\treturn renamed(\n\t\trestoreSome(backups, id, options, 'restoreCollections'),\n\t\t'restoreCollections',\n\t);\n}\n\n/** `restoreCollections`, its messages naming the call `where` says. */\nexport async function restoreSome(\n\tbackups: Restorer,\n\tid: string,\n\toptions: RestoreCollectionsOptions,\n\twhere: string,\n): Promise<RestoredCollections> {\n\tcheckOptions(options, where);\n\tconst { db } = options;\n\tconst scratch =\n\t\toptions.scratch ?? db.client.db(`nxgt-restore-${crypto.randomUUID()}`);\n\tif (options.scratch) await checkEmpty(scratch, where);\n\ttry {\n\t\tconst restored = await backups.restore(\n\t\t\tid,\n\t\t\tmongoTarget({ db: scratch, tmpDir: options.tmpDir }),\n\t\t\t{ identities: options.identities, from: options.from },\n\t\t);\n\t\tconst chosen = await choose(scratch, options, where);\n\t\tlet counts: Map<string, number> | undefined;\n\t\tif (options.documents) {\n\t\t\tcounts = await landDocuments(scratch, db, chosen, options.documents);\n\t\t} else {\n\t\t\tawait landWhole(scratch, db, chosen, options.replace === true, where);\n\t\t}\n\t\treturn {\n\t\t\t...restored,\n\t\t\tcollections: chosen.map(({ described, as }) => {\n\t\t\t\tconst documents = counts?.get(described.name);\n\t\t\t\treturn documents === undefined\n\t\t\t\t\t? { name: described.name, as }\n\t\t\t\t\t: { name: described.name, as, documents };\n\t\t\t}),\n\t\t};\n\t} finally {\n\t\t// What the restore did, or its own failure, is what to report: a\n\t\t// scratch database left behind is the docs' to explain, not an error.\n\t\tawait scratch.dropDatabase().catch(() => undefined);\n\t}\n}\n",
|
|
20
|
+
"import { BSON, type Document, type Timestamp } from 'mongodb';\nimport { isDocument } from './document';\n\nconst POSITION_FORMAT = 'nxgt-mongo-backup-position/1';\n\n/**\n * Where a change stream starts: just after the cluster time a full backup's\n * snapshot read at, or after the last change an incremental one read.\n */\nexport type Resume =\n\t| { startAtOperationTime: Timestamp }\n\t| { startAfter: Document };\n\n/**\n * Where the next incremental backup starts, and how the collections and\n * views it follows differ from those of the chain's full backup — each of\n * which has its `metadata/<name>` entry, so the position stays small\n * however many there are. A change to `collections` takes effect at the\n * next full backup, never halfway through a chain.\n */\nexport interface Position {\n\tresume: Resume;\n\t/** Followed now, with no metadata entry: created since the full backup. */\n\tadded: string[];\n\t/** Not followed any more, though the full backup holds them. */\n\tremoved: string[];\n}\n\n/** `position` as the backup records it: canonical Extended JSON. */\nexport function writePosition(position: Position): string {\n\treturn BSON.EJSON.stringify(\n\t\t{\n\t\t\tformat: POSITION_FORMAT,\n\t\t\t...position.resume,\n\t\t\tadded: [...position.added].sort(),\n\t\t\tremoved: [...position.removed].sort(),\n\t\t},\n\t\t{ relaxed: false },\n\t);\n}\n\nconst isNames = (value: unknown): value is string[] =>\n\tArray.isArray(value) && value.every((name) => typeof name === 'string');\n\nfunction resumeOf(record: Document): Resume | undefined {\n\tconst at = record['startAtOperationTime'];\n\tif (at instanceof BSON.Timestamp) return { startAtOperationTime: at };\n\tconst after = record['startAfter'];\n\tif (isDocument(after)) return { startAfter: after };\n\treturn undefined;\n}\n\n/** The position a backup recorded, or nothing when it is not one this version wrote. */\nexport function readPosition(text: string | undefined): Position | undefined {\n\tif (text === undefined) return undefined;\n\tlet value: unknown;\n\ttry {\n\t\tvalue = BSON.EJSON.parse(text, { relaxed: false });\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!isDocument(value) || value['format'] !== POSITION_FORMAT) {\n\t\treturn undefined;\n\t}\n\tconst resume = resumeOf(value);\n\tconst { added, removed } = value;\n\tif (!resume || !isNames(added) || !isNames(removed)) return undefined;\n\treturn { resume, added, removed };\n}\n",
|
|
21
|
+
"import type { ChangeStreamDocument, Document, Timestamp } from 'mongodb';\nimport { MongoBackupError } from '../errors';\nimport type { Change } from '../format/change';\nimport { type CollectionFilter, takes } from './collections';\n\n/** A change-stream event, with `showExpandedEvents`: the fields read from it. */\nexport type Event = ChangeStreamDocument & {\n\tclusterTime?: Timestamp;\n\tfullDocument?: Document | null;\n\tdocumentKey?: Document;\n\tns?: { db: string; coll?: string };\n\tnsType?: string;\n\tto?: { db: string; coll: string };\n\toperationDescription?: Document;\n\tupdateDescription?: {\n\t\tupdatedFields?: Document;\n\t\tremovedFields?: string[];\n\t\ttruncatedArrays?: { field: string; newSize: number }[];\n\t\tdisambiguatedPaths?: Document;\n\t};\n};\n\nconst unsupported = (what: string) =>\n\tnew MongoBackupError(`mongoSource: ${what}`, 'UNSUPPORTED');\n\n/** The update an event records: its post-image if it has one, its description otherwise. */\nfunction updateOf(event: Event, coll: string, key: Document): Change {\n\tif (event.fullDocument) {\n\t\treturn { op: 'replace', coll, key, doc: event.fullDocument };\n\t}\n\tconst update = event.updateDescription ?? {};\n\tif (Object.keys(update.disambiguatedPaths ?? {}).length > 0) {\n\t\tthrow unsupported(\n\t\t\t'an update touched a field whose name holds a dot or is a number, ' +\n\t\t\t\t'which a change cannot say without its post-image; turn on ' +\n\t\t\t\t'changeStreamPreAndPostImages for that collection, or make a full backup',\n\t\t);\n\t}\n\treturn {\n\t\top: 'update',\n\t\tcoll,\n\t\tkey,\n\t\tset: update.updatedFields ?? {},\n\t\tunset: update.removedFields ?? [],\n\t\ttruncated: (update.truncatedArrays ?? []).map((cut) => ({\n\t\t\tfield: cut.field,\n\t\t\tnewSize: Number(cut.newSize),\n\t\t})),\n\t};\n}\n\n/** A change to a collection itself, from its expanded event. */\nfunction ddlOf(event: Event, coll: string, db: string): Change | undefined {\n\tconst described = event.operationDescription ?? {};\n\tswitch (event.operationType) {\n\t\tcase 'create': {\n\t\t\tif (event.nsType === 'timeseries') {\n\t\t\t\tthrow unsupported(\n\t\t\t\t\t'a collection is of a type this version does not back up ' +\n\t\t\t\t\t\t'(a time-series one); leave it out with collections',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst { idIndex: _idIndex, ...options } = described;\n\t\t\treturn { op: 'create', coll, options };\n\t\t}\n\t\tcase 'createIndexes':\n\t\t\treturn {\n\t\t\t\top: 'createIndexes',\n\t\t\t\tcoll,\n\t\t\t\tindexes: ((described['indexes'] ?? []) as Document[]).map(\n\t\t\t\t\t({ v: _v, ns: _ns, ...index }) => index,\n\t\t\t\t),\n\t\t\t};\n\t\tcase 'dropIndexes':\n\t\t\treturn {\n\t\t\t\top: 'dropIndexes',\n\t\t\t\tcoll,\n\t\t\t\tnames: ((described['indexes'] ?? []) as Document[]).map((index) =>\n\t\t\t\t\tString(index['name']),\n\t\t\t\t),\n\t\t\t};\n\t\tcase 'modify':\n\t\t\treturn { op: 'modify', coll, changes: described };\n\t\tcase 'drop':\n\t\t\treturn { op: 'drop', coll };\n\t\tcase 'rename':\n\t\t\t// Renamed out of the database: gone from it.\n\t\t\t// `dropTarget` there is the UUID of a collection the rename replaced.\n\t\t\treturn event.to?.db === db\n\t\t\t\t? {\n\t\t\t\t\t\top: 'rename',\n\t\t\t\t\t\tcoll,\n\t\t\t\t\t\tto: event.to.coll,\n\t\t\t\t\t\tdropTarget: described['dropTarget'] !== undefined,\n\t\t\t\t\t}\n\t\t\t\t: { op: 'drop', coll };\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/** The change an event records, or nothing when it is not one to keep. */\nexport function changeOf(event: Event, db: string): Change | undefined {\n\tconst coll = event.ns?.coll ?? '';\n\tconst key = event.documentKey ?? {};\n\tswitch (event.operationType) {\n\t\tcase 'insert':\n\t\tcase 'replace':\n\t\t\treturn {\n\t\t\t\top: event.operationType,\n\t\t\t\tcoll,\n\t\t\t\tkey,\n\t\t\t\tdoc: event.fullDocument ?? {},\n\t\t\t};\n\t\tcase 'update':\n\t\t\treturn updateOf(event, coll, key);\n\t\tcase 'delete':\n\t\t\treturn { op: 'delete', coll, key };\n\t\tcase 'dropDatabase':\n\t\t\treturn { op: 'dropDatabase' };\n\t\tdefault:\n\t\t\treturn ddlOf(event, coll, db);\n\t}\n}\n\n/**\n * Whether an event is passed over before it is translated: one on a\n * collection the backup does not follow — or, for a creation, one the\n * filter does not take — so an update or a creation there that a change\n * could not say never fails the backup. A rename is never passed over\n * here: `followed` decides it.\n */\nexport function passedOver(\n\tevent: Event,\n\theld: ReadonlySet<string>,\n\tfilter: CollectionFilter | undefined,\n): boolean {\n\tconst coll = event.ns?.coll;\n\tif (coll === undefined || event.operationType === 'rename') return false;\n\treturn event.operationType === 'create'\n\t\t? !takes(filter, coll)\n\t\t: !held.has(coll);\n}\n\n/**\n * The change as the backup keeps it, and `held` — the collections it\n * follows — brought up to date. A collection created that the filter takes\n * is followed from then on. A rename out of those followed is a drop, and\n * one into them is refused: the documents it brings were never read.\n */\nexport function followed(\n\tchange: Change,\n\theld: Set<string>,\n\tfilter: CollectionFilter | undefined,\n): Change | undefined {\n\tswitch (change.op) {\n\t\tcase 'dropDatabase':\n\t\t\t// Before it, each collection's own drop: but no view has one.\n\t\t\theld.clear();\n\t\t\treturn change;\n\t\tcase 'create':\n\t\t\theld.add(change.coll);\n\t\t\treturn change;\n\t\tcase 'drop':\n\t\t\theld.delete(change.coll);\n\t\t\treturn change;\n\t\tcase 'rename':\n\t\t\treturn renamed(change, held, filter);\n\t\tdefault:\n\t\t\treturn change;\n\t}\n}\n\nfunction renamed(\n\tchange: Extract<Change, { op: 'rename' }>,\n\theld: Set<string>,\n\tfilter: CollectionFilter | undefined,\n): Change | undefined {\n\tconst from = held.has(change.coll);\n\tconst to = takes(filter, change.to);\n\tif (from) held.delete(change.coll);\n\tif (from && to) {\n\t\theld.add(change.to);\n\t\treturn change;\n\t}\n\tif (from) return { op: 'drop', coll: change.coll };\n\tif (to) {\n\t\tthrow unsupported(\n\t\t\t'a collection was renamed into those backed up, with documents an ' +\n\t\t\t\t'incremental backup never read; make a full backup',\n\t\t);\n\t}\n\treturn undefined;\n}\n",
|
|
22
|
+
"import type { ChangeStream, Db, Document, Timestamp } from 'mongodb';\nimport { MongoBackupError, serverCode } from '../errors';\nimport { EXACT, writeChange } from '../format/change';\nimport type { Resume } from '../format/position';\nimport type { CollectionFilter } from './collections';\nimport { changeOf, type Event, followed, passedOver } from './events';\n\n/** The server cannot resume the stream there: its history is gone. */\nconst HISTORY_LOST = new Set([286, 280]);\n\nfunction lost(error: unknown): unknown {\n\treturn HISTORY_LOST.has(serverCode(error) ?? 0)\n\t\t? new MongoBackupError(\n\t\t\t\t'mongoSource: the change stream cannot resume where the last backup ' +\n\t\t\t\t\t'stopped: the oplog no longer reaches back there; make a full backup',\n\t\t\t\t'HISTORY_LOST',\n\t\t\t\t{ cause: error },\n\t\t\t)\n\t\t: error;\n}\n\n/**\n * The changes since `from`, up to the operation time `until`, to the\n * collections `held` names — brought up to date as they come — as\n * concatenated BSON, then `record` with where the next backup resumes.\n * The stream stops at the first event after `until`, at an invalidation,\n * or once a read of the change stream comes back empty — caught up.\n */\nexport function changesOf(\n\tdb: Db,\n\tfrom: Resume,\n\theld: Set<string>,\n\tuntil: Timestamp,\n\tfilter: CollectionFilter | undefined,\n\trecord: (resume: Resume) => void,\n): ReadableStream<Uint8Array> {\n\tlet stream: ChangeStream | undefined;\n\tlet resume = from;\n\tconst finish = async (controller: ReadableStreamDefaultController) => {\n\t\tawait stream?.close();\n\t\trecord(resume);\n\t\tcontroller.close();\n\t};\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tstream ??= db.watch([], {\n\t\t\t\t\t...from,\n\t\t\t\t\tfullDocument: 'whenAvailable',\n\t\t\t\t\tshowExpandedEvents: true,\n\t\t\t\t\t...EXACT,\n\t\t\t\t});\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst event = (await stream.tryNext()) as Event | null;\n\t\t\t\t\t// An empty read: the stream has caught up with now, past `until`.\n\t\t\t\t\tif (event === null) {\n\t\t\t\t\t\tresume = { startAfter: stream.resumeToken as Document };\n\t\t\t\t\t\treturn await finish(controller);\n\t\t\t\t\t}\n\t\t\t\t\tif (event.operationType === 'invalidate') {\n\t\t\t\t\t\tresume = { startAfter: event._id as Document };\n\t\t\t\t\t\treturn await finish(controller);\n\t\t\t\t\t}\n\t\t\t\t\tif (event.clusterTime?.greaterThan(until)) {\n\t\t\t\t\t\treturn await finish(controller);\n\t\t\t\t\t}\n\t\t\t\t\tresume = { startAfter: event._id as Document };\n\t\t\t\t\tif (passedOver(event, held, filter)) continue;\n\t\t\t\t\tconst change = changeOf(event, db.databaseName);\n\t\t\t\t\tconst kept = change && followed(change, held, filter);\n\t\t\t\t\tif (kept) {\n\t\t\t\t\t\tcontroller.enqueue(writeChange(kept));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tawait stream?.close().catch(() => undefined);\n\t\t\t\tcontroller.error(lost(error));\n\t\t\t}\n\t\t},\n\t\tasync cancel() {\n\t\t\tawait stream?.close();\n\t\t},\n\t});\n}\n",
|
|
23
|
+
"import type { Since } from '@softistx/backup';\nimport { MongoBackupError } from '../errors';\nimport { METADATA } from '../format/names';\nimport type { Position } from '../format/position';\n\n/** The collections and views the chain's full backup holds: one metadata entry each. */\nexport function heldByFull(since: Since): Set<string> {\n\tconst names = new Set<string>();\n\tfor (const name of since.entries.keys()) {\n\t\tif (name.startsWith(METADATA)) names.add(name.slice(METADATA.length));\n\t}\n\treturn names;\n}\n\n/** What the chain follows: its full backup's, changed as the position says. */\nexport function followedFrom(\n\tfull: Set<string>,\n\tposition: Position,\n): Set<string> {\n\tconst held = new Set([...full, ...position.added]);\n\tfor (const name of position.removed) held.delete(name);\n\treturn held;\n}\n\n/** How `held` differs from what the full backup holds, as a position records it. */\nexport function differenceOf(\n\tfull: Set<string>,\n\theld: Set<string>,\n): Pick<Position, 'added' | 'removed'> {\n\treturn {\n\t\tadded: [...held].filter((name) => !full.has(name)),\n\t\tremoved: [...full].filter((name) => !held.has(name)),\n\t};\n}\n\n/** The most a position may hold: `@softistx/backup`'s limit. */\nexport const POSITION_MAX_BYTES = 64 * 1024;\n\n/** `text`, unless it is longer than a position may be. */\nexport function fitting(text: string): string {\n\tif (Buffer.byteLength(text) > POSITION_MAX_BYTES) {\n\t\tthrow new MongoBackupError(\n\t\t\t'mongoSource: the collections created, renamed or dropped since the ' +\n\t\t\t\t'full backup are too many to record; make a full backup',\n\t\t\t'UNSUPPORTED',\n\t\t);\n\t}\n\treturn text;\n}\n",
|
|
24
|
+
"import type { SourceEntry } from '@softistx/backup';\nimport type { ClientSession, Db, Timestamp } from 'mongodb';\nimport { MongoBackupError, serverCode } from '../errors';\nimport { writeMetadata } from '../format/metadata';\nimport { DOCUMENTS, METADATA } from '../format/names';\nimport { after, pinnedCatalog } from './catalog';\nimport type { CollectionFilter } from './collections';\n\n/** The server refused a read: its snapshot is older than it keeps. */\nconst SNAPSHOT_TOO_OLD = 239;\n\n/**\n * The cluster's operation time now, read through a session of its own:\n * what a change stream started there misses nothing after.\n */\nexport async function operationTime(db: Db): Promise<Timestamp> {\n\tconst session = db.client.startSession();\n\ttry {\n\t\tawait db.command({ ping: 1 }, { session });\n\t\tconst time = session.operationTime;\n\t\tif (!time) {\n\t\t\tthrow new MongoBackupError(\n\t\t\t\t'mongoSource: the server gave no operation time; a backup needs a ' +\n\t\t\t\t\t'replica set or a sharded cluster',\n\t\t\t\t'UNSUPPORTED',\n\t\t\t);\n\t\t}\n\t\treturn time;\n\t} finally {\n\t\tawait session.endSession();\n\t}\n}\n\n/** A stream of `text`, as an entry gives it. */\nfunction textStream(text: string): ReadableStream<Uint8Array> {\n\treturn new Response(text).body as ReadableStream<Uint8Array>;\n}\n\n/**\n * Every document of one collection, as concatenated BSON — each read raw,\n * so no number changes kind — in the snapshot `session` reads at.\n */\nfunction documentsOf(\n\tdb: Db,\n\tname: string,\n\tsession: ClientSession,\n): ReadableStream<Uint8Array> {\n\tconst cursor = db\n\t\t.collection(name)\n\t\t.find({}, { session, raw: true, batchSize: 1000 });\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst next = (await cursor.next()) as Uint8Array | null;\n\t\t\t\tif (next === null) controller.close();\n\t\t\t\telse controller.enqueue(next);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(\n\t\t\t\t\tserverCode(error) === SNAPSHOT_TOO_OLD\n\t\t\t\t\t\t? new MongoBackupError(\n\t\t\t\t\t\t\t\t'mongoSource: the snapshot outlived the history the server keeps; ' +\n\t\t\t\t\t\t\t\t\t'raise minSnapshotHistoryWindowInSeconds, or back up fewer ' +\n\t\t\t\t\t\t\t\t\t'collections at a time',\n\t\t\t\t\t\t\t\t'SNAPSHOT_TOO_OLD',\n\t\t\t\t\t\t\t\t{ cause: error },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: error,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\tasync cancel() {\n\t\t\tawait cursor.close();\n\t\t},\n\t});\n}\n\n/**\n * A full backup's entries: each collection's metadata, then its documents,\n * every document read in one snapshot session — one cluster time for them\n * all — and the metadata read so that it is that time's too. The next\n * backup's change stream starts just after that time, following the\n * collections this one holds — its metadata entries say which.\n */\nexport async function* snapshotEntries(\n\tdb: Db,\n\tfilter: CollectionFilter | undefined,\n\trecord: (start: Timestamp) => void,\n): AsyncGenerator<SourceEntry> {\n\tconst { session, at, catalog } = await pinnedCatalog(db, filter);\n\tconst fingerprint = `snapshot:${at.toString()}`;\n\ttry {\n\t\tfor (const collection of catalog) {\n\t\t\tconst metadata = writeMetadata(collection.metadata);\n\t\t\tyield {\n\t\t\t\tname: `${METADATA}${collection.name}`,\n\t\t\t\tfingerprint,\n\t\t\t\topen: () => textStream(metadata),\n\t\t\t};\n\t\t\tif (collection.type === 'collection') {\n\t\t\t\tyield {\n\t\t\t\t\tname: `${DOCUMENTS}${collection.name}`,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\topen: () => documentsOf(db, collection.name, session),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\trecord(after(at));\n\t} finally {\n\t\tawait session.endSession();\n\t}\n}\n",
|
|
25
|
+
"import type { BackupSource, Since, SourceEntry } from '@softistx/backup';\nimport type { Db } from 'mongodb';\nimport { MongoBackupError } from '../errors';\nimport { CHANGES, changesName } from '../format/names';\nimport { type Position, readPosition, writePosition } from '../format/position';\nimport { changesOf } from './changes';\nimport type { CollectionFilter } from './collections';\nimport { differenceOf, fitting, followedFrom, heldByFull } from './followed';\nimport { operationTime, snapshotEntries } from './snapshot';\n\nexport interface MongoSourceOptions {\n\t/** The database to back up. Its client must reach a replica set or a sharded cluster. */\n\tdb: Db;\n\t/**\n\t * Which collections and views: their names, or a test on each name.\n\t * Every one but `system.*` by default. A name listed that the database\n\t * lacks is a `TypeError`.\n\t */\n\tcollections?: CollectionFilter | undefined;\n}\n\nfunction checkOptions(options: MongoSourceOptions): void {\n\tconst db = options?.db as Partial<Db> | undefined;\n\tif (typeof db?.watch !== 'function' || typeof db.databaseName !== 'string') {\n\t\tthrow new TypeError('mongoSource: db must be a MongoDB Db');\n\t}\n\tconst filter = options.collections;\n\tif (\n\t\tfilter !== undefined &&\n\t\ttypeof filter !== 'function' &&\n\t\t!(Array.isArray(filter) && filter.every((n) => typeof n === 'string'))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'mongoSource: collections must be a list of names or a function',\n\t\t);\n\t}\n}\n\n/**\n * The entries an incremental or differential backup adds: those of the\n * backup it builds on, untouched — their fingerprints say so, and they are\n * never opened — then one more, the changes since that backup's position.\n */\nasync function* changesEntries(\n\toptions: MongoSourceOptions,\n\tsince: Since,\n\trecord: (position: Position) => void,\n): AsyncGenerator<SourceEntry> {\n\tconst from = readPosition(since.position);\n\tif (!from) {\n\t\tthrow new MongoBackupError(\n\t\t\t'mongoSource: the backup built on recorded no position this version ' +\n\t\t\t\t'reads; make a full backup',\n\t\t\t'MALFORMED',\n\t\t);\n\t}\n\tconst full = heldByFull(since);\n\tconst held = followedFrom(full, from);\n\tconst until = await operationTime(options.db);\n\tlet changes = 0;\n\tfor (const [name, known] of since.entries) {\n\t\tif (name.startsWith(CHANGES)) changes++;\n\t\tyield {\n\t\t\tname,\n\t\t\tfingerprint: known.fingerprint,\n\t\t\topen: () => {\n\t\t\t\tthrow new MongoBackupError(\n\t\t\t\t\t'mongoSource: an entry of the backup built on was asked for again; ' +\n\t\t\t\t\t\t'it has no fingerprint, so make a full backup',\n\t\t\t\t\t'MALFORMED',\n\t\t\t\t);\n\t\t\t},\n\t\t};\n\t}\n\tconst name = changesName(changes + 1);\n\tyield {\n\t\tname,\n\t\tfingerprint: `changes:${since.id}:${name}`,\n\t\topen: () =>\n\t\t\tchangesOf(\n\t\t\t\toptions.db,\n\t\t\t\tfrom.resume,\n\t\t\t\theld,\n\t\t\t\tuntil,\n\t\t\t\toptions.collections,\n\t\t\t\t(resume) => record({ resume, ...differenceOf(full, held) }),\n\t\t\t),\n\t};\n}\n\n/**\n * A MongoDB database as a backup source. A full backup reads every\n * collection in one snapshot — one cluster time for the whole database —\n * as `metadata/<name>` (options and indexes) and `documents/<name>`\n * (concatenated BSON, as `mongodump` writes it); views have metadata only,\n * and GridFS buckets are collections like any other. An incremental or\n * differential backup reads the change stream from where the backup it\n * builds on stopped, into one `changes/<n>` entry.\n */\nexport function mongoSource(options: MongoSourceOptions): BackupSource {\n\tcheckOptions(options);\n\tlet position: string | undefined;\n\tconst record = (at: Position) => {\n\t\tposition = fitting(writePosition(at));\n\t};\n\treturn {\n\t\tkind: 'mongo',\n\t\tentries(since) {\n\t\t\tposition = undefined;\n\t\t\treturn since\n\t\t\t\t? changesEntries(options, since, record)\n\t\t\t\t: snapshotEntries(options.db, options.collections, (start) =>\n\t\t\t\t\t\trecord({\n\t\t\t\t\t\t\tresume: { startAtOperationTime: start },\n\t\t\t\t\t\t\tadded: [],\n\t\t\t\t\t\t\tremoved: [],\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t},\n\t\tposition: () => position,\n\t};\n}\n",
|
|
26
|
+
"import { isAbsolute } from 'node:path';\nimport type { KeepPolicy, Repository } from '@softistx/backup';\nimport type { Db, Document } from 'mongodb';\nimport type { CollectionFilter } from '../source/collections';\n\nconst HOUR = 60 * 60 * 1000;\nconst DAY = 24 * HOUR;\n\n/** A full backup a week, incrementals in between. */\nexport const DEFAULT_FULL_EVERY = 7 * DAY;\n\n/** A day hour by hour, two weeks day by day, two months week by week, a year month by month. */\nexport const DEFAULT_KEEP: KeepPolicy = {\n\tlast: 24,\n\tdaily: 14,\n\tweekly: 8,\n\tmonthly: 12,\n};\n\nexport interface MongoBackupsOptions {\n\t/** The database backed up. */\n\tdb: Db;\n\t/** Where backups go: an absolute folder, or `@softistx/backup` repositories — `s3Repository` among them. */\n\trepository: string | Repository | readonly [Repository, ...Repository[]];\n\t/** The file `nxgt-mongo-backup keygen` wrote: an absolute path. */\n\tkeyFile: string;\n\t/** The backup's name in the repository. The database's name by default. */\n\tname?: string | undefined;\n\t/** The collections backed up. All of them by default. */\n\tcollections?: CollectionFilter | undefined;\n\t/** How old the newest full backup may grow before `run` makes another. A week by default. */\n\tfullEvery?: number | undefined;\n\t/** What `run` keeps after each backup; `false` keeps everything. `DEFAULT_KEEP` by default. */\n\tkeep?: KeepPolicy | false | undefined;\n\t/** Where objects and changes are staged. The system's temporary folder by default. */\n\ttmpDir?: string | undefined;\n}\n\n/** Which backup to restore, where to, and how much of it. */\nexport type RestoreAtOptions = RestoreWhole | RestoreDocuments;\n\ninterface RestoreCommon {\n\t/** The database to restore into: another, or the one backed up. */\n\tinto: Db;\n\t/** A backup's id, or a time: the newest backup made at or before it. The newest by default. */\n\tat?: string | Date | undefined;\n\t/** Some collections and views only, by their name at the backup's time. */\n\tcollections?: CollectionFilter | undefined;\n\t/** Other names to restore them under. */\n\tas?:\n\t\t| Readonly<Record<string, string>>\n\t\t| ((name: string) => string)\n\t\t| undefined;\n}\n\n/** Collections and views whole, each landed whole or not at all. */\ninterface RestoreWhole extends RestoreCommon {\n\tdocuments?: undefined;\n\t/** Replace collections and views already there, rather than refuse them. */\n\treplace?: boolean | undefined;\n}\n\n/** Some documents only, merged into what is there: `existing` says how. */\ninterface RestoreDocuments extends RestoreCommon {\n\tdocuments: { filter: Document; existing: 'replace' | 'keep' };\n\treplace?: never;\n}\n\n// A copy of @softistx/backup's checkPolicy rule list (AGENTS.md, duplication):\n// tied to KeepPolicy so a rule added there fails the typecheck here.\nconst RULES = [\n\t'last',\n\t'hourly',\n\t'daily',\n\t'weekly',\n\t'monthly',\n\t'yearly',\n\t'within',\n\t'maxTotalSize',\n] as const satisfies readonly (keyof KeepPolicy)[];\ntype Missing = Exclude<keyof KeepPolicy, (typeof RULES)[number]>;\n/** Fails to compile when KeepPolicy gains a rule RULES lacks. */\nexport const RULES_COVER_KEEP: [Missing] extends [never] ? true : never = true;\n\n/** `keep` names a rule: checked when it is configured, not after a backup is stored. */\nfunction checkKeep(keep: unknown): void {\n\tif (keep === undefined || keep === false) return;\n\tconst policy = keep as Record<string, unknown> | null;\n\tconst named =\n\t\ttypeof policy === 'object' &&\n\t\tpolicy !== null &&\n\t\tRULES.some((rule) => policy[rule] !== undefined) &&\n\t\tRULES.every((rule) => {\n\t\t\tconst value = policy[rule];\n\t\t\treturn (\n\t\t\t\tvalue === undefined ||\n\t\t\t\t(Number.isSafeInteger(value) && (value as number) >= 1)\n\t\t\t);\n\t\t});\n\tif (!named) {\n\t\tthrow new TypeError(\n\t\t\t'mongoBackups: keep must be false, or name rules each a whole number, 1 or more',\n\t\t);\n\t}\n}\n\n/** What `restore` refuses before it reads a backup; `restoreCollections` checks the rest. */\nexport function checkRestore(at: RestoreAtOptions, where: string): void {\n\tconst into = at?.into as Partial<Db> | undefined;\n\tif (\n\t\ttypeof into?.collection !== 'function' ||\n\t\ttypeof into.databaseName !== 'string'\n\t) {\n\t\tthrow new TypeError(`${where}: into must be a MongoDB Db`);\n\t}\n\tconst when = at?.at;\n\tif (when instanceof Date && Number.isNaN(when.getTime())) {\n\t\tthrow new TypeError(`${where}: at must be a backup's id or a valid Date`);\n\t}\n\t// Also restoreCollections's, but refused here before a backup is read.\n\tif (at?.documents !== undefined && at.replace !== undefined) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: replace is for whole collections; documents says what happens to those there`,\n\t\t);\n\t}\n}\n\nexport function checkOptions(options: MongoBackupsOptions): void {\n\tconst db = options?.db as Partial<Db> | undefined;\n\tif (\n\t\ttypeof db?.collection !== 'function' ||\n\t\ttypeof db.databaseName !== 'string'\n\t) {\n\t\tthrow new TypeError('mongoBackups: db must be a MongoDB Db');\n\t}\n\tif (typeof options.keyFile !== 'string' || !isAbsolute(options.keyFile)) {\n\t\tthrow new TypeError('mongoBackups: keyFile must be an absolute path');\n\t}\n\tconst { repository } = options;\n\tconst isRepository = (r: unknown) =>\n\t\ttypeof (r as Partial<Repository> | null)?.name === 'string';\n\tif (\n\t\ttypeof repository === 'string'\n\t\t\t? !isAbsolute(repository)\n\t\t\t: Array.isArray(repository)\n\t\t\t\t? !repository.every(isRepository)\n\t\t\t\t: !isRepository(repository)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'mongoBackups: repository must be an absolute folder, or repositories',\n\t\t);\n\t}\n\tcheckKeep(options.keep);\n\tif (Array.isArray(repository)) {\n\t\tconst names = new Set(repository.map((r: Repository) => r?.name));\n\t\tif (repository.length === 0 || names.size !== repository.length) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'mongoBackups: repository must list repositories, each under a name of its own',\n\t\t\t);\n\t\t}\n\t}\n\tif (options.tmpDir !== undefined && !isAbsolute(options.tmpDir)) {\n\t\tthrow new TypeError('mongoBackups: tmpDir must be an absolute path');\n\t}\n\tconst every = options.fullEvery;\n\tif (every !== undefined && (!Number.isSafeInteger(every) || every < HOUR)) {\n\t\tthrow new TypeError(\n\t\t\t'mongoBackups: fullEvery must be a whole number of milliseconds, an hour or more',\n\t\t);\n\t}\n}\n",
|
|
27
|
+
"import type { BackupInfo } from '@softistx/backup';\nimport type { Db } from 'mongodb';\nimport { MongoBackupError } from '../errors';\n\n/** What a drill restored: each collection and its documents. */\nexport interface DrillReport {\n\tid: string;\n\tcollections: { name: string; documents: number }[];\n}\n\n/** A full backup when none is younger than `fullEvery`, an incremental otherwise. */\nexport function kindFor(\n\tbackups: readonly BackupInfo[],\n\tnow: Date,\n\tfullEvery: number,\n): 'full' | 'incremental' {\n\tconst recent = backups.some(\n\t\t(backup) =>\n\t\t\tbackup.kind === 'full' &&\n\t\t\tnow.getTime() - backup.createdAt.getTime() < fullEvery,\n\t);\n\treturn recent ? 'incremental' : 'full';\n}\n\n/**\n * The backup `at` names: an id as it is, a time as the newest backup made\n * at or before it, nothing as the newest of all.\n */\nexport function chosenBackup(\n\tbackups: readonly BackupInfo[],\n\tat: string | Date | undefined,\n\twhere: string,\n): string {\n\tif (typeof at === 'string') return at;\n\tconst before = backups\n\t\t.filter((b) => at === undefined || b.createdAt.getTime() <= at.getTime())\n\t\t.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())\n\t\t.at(-1);\n\tif (!before) {\n\t\tthrow new MongoBackupError(\n\t\t\tat === undefined\n\t\t\t\t? `${where}: the repository holds no backup yet`\n\t\t\t\t: `${where}: no backup was made at or before that time`,\n\t\t\t'NOT_FOUND',\n\t\t);\n\t}\n\treturn before.id;\n}\n\n/** Each collection of `db` — views and `system.*` apart — and its documents. */\nexport async function countsOf(db: Db): Promise<DrillReport['collections']> {\n\tconst listed = await db.listCollections({}, { nameOnly: true }).toArray();\n\tconst counts: DrillReport['collections'] = [];\n\tfor (const info of listed.sort((a, b) => (a.name < b.name ? -1 : 1))) {\n\t\tif (info.type !== 'collection' || info.name.startsWith('system.')) continue;\n\t\tcounts.push({\n\t\t\tname: info.name,\n\t\t\tdocuments: await db.collection(info.name).countDocuments(),\n\t\t});\n\t}\n\treturn counts;\n}\n"
|
|
28
|
+
],
|
|
29
|
+
"mappings": ";;;;;;;;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;;;ACAA;AAAA,UACC;AAAA;;;ACDD;AAgBO,SAAS,KAAK,CACpB,QACA,MACU;AAAA,EACV,IAAI,KAAK,WAAW,SAAS;AAAA,IAAG,OAAO;AAAA,EACvC,IAAI,WAAW;AAAA,IAAW,OAAO;AAAA,EACjC,OAAO,OAAO,WAAW,aAAa,OAAO,IAAI,IAAI,OAAO,SAAS,IAAI;AAAA;AAQnE,eAAe,MAAM,CAC3B,IACA,QACoB;AAAA,EACpB,MAAM,MAAM,MAAM,GAAG,gBAAgB,CAAC,GAAG,EAAE,UAAU,MAAM,CAAC,EAAE,QAAQ;AAAA,EACtE,MAAM,QAAkB,CAAC;AAAA,EACzB,WAAW,QAAQ,KAAK;AAAA,IACvB,IAAI,CAAC,MAAM,QAAQ,KAAK,IAAI;AAAA,MAAG;AAAA,IAC/B,IAAI,KAAK,SAAS,gBAAgB,KAAK,SAAS,QAAQ;AAAA,MACvD,MAAM,IAAI,kBACT,0EACC,sDACD,aACD;AAAA,IACD;AAAA,IACA,MAAM,KAAK;AAAA,MACV,MAAM,KAAK;AAAA,MACX,MAAM,KAAK;AAAA,MACX,SAAU,KAAgC,WAAW,CAAC;AAAA,MACtD,MAAM,KAAK,MAAM,U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zC,IAAI,OAAO,eAAe;AAAA,IACzB,OAAO,CAAC,gBAAgB,EAAE,MAAM,WAAW,CAAC,CAAC;AAAA,EAC9C,IAAI,MAAM,QAAQ,UAAU;AAAA,IAC3B,OAAO;AAAA,EACR,OAAO,CAAC,UAAwB;AAAA;AAIjC,SAAS,YAAY,CAAC,SAAgD;AAAA,EACrE,IAAI;AAAA,IACH,OAAO,aAAa,EAAE,MAAM,QAAQ,QAAQ,QAAQ,GAAG,aAAa,CAAC;AAAA,IACpE,OAAO,OAAO;AAAA,IAEf,MAAM,OAAO,OAAQ,MAAgB,OAAO,EAAE,QAC7C,oCACA,EACD;AAAA,IACA,MAAM,IAAI,UACT,QAAQ,SAAS,YACd,sEAAsE,SACtE,8BAA8B,QACjC,EAAE,MAAM,CACT;AAAA;AAAA;AAWK,SAAS,YAAY,CAAC,SAA4C;AAAA,EACxE,cAAa,OAAO;AAAA,EACpB,MAAM,MAAe;AAAA,IACpB;AAAA,IACA,YAAY,aAAa,OAAO;AAAA,IAChC,cAAc,eAAe,QAAQ,UAAU;AAAA,EAChD;AAAA,EACA,OAAO;AAAA,IACN,SAAS,MAAM,UAAU,GAAG;AAAA,IAC5B,MAAM,MAAM,OAAO,GAAG;AAAA,IACtB,KAAK,CAAC,QAAQ,SAAS,QAAQ,KAAK,GAAG,GAAG,KAAK,KAAK;AAAA,IACpD,SAAS,CAAC,OAAO,SAAS,UAAU,KAAK,EAAE,GAAG,KAAK,SAAS;AAAA,IAC5D,OAAO,MAAM,SAAS,YAAY,GAAG,GAAG,KAAK,OAAO;AAAA,EACrD;AAAA;",
|
|
30
|
+
"debugId": "97E3E95757FED5EF64756E2164756E21",
|
|
31
|
+
"names": []
|
|
32
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Db } from 'mongodb';
|
|
2
|
+
import { MongoBackupError } from '../errors.js';
|
|
3
|
+
import type { Described } from '../source/catalog.js';
|
|
4
|
+
import type { DocumentSelection } from './options.js';
|
|
5
|
+
/** One collection or view of the backup, and the name it lands under. */
|
|
6
|
+
export interface Chosen {
|
|
7
|
+
described: Described;
|
|
8
|
+
as: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function taken(where: string): MongoBackupError;
|
|
11
|
+
/**
|
|
12
|
+
* Each collection moved from `scratch` into `db` whole — a rename across
|
|
13
|
+
* databases, which keeps its options and indexes — then each view made
|
|
14
|
+
* again: on the collection's new name when that collection came too.
|
|
15
|
+
* Without `replace`, a name taken is refused before anything moves, and
|
|
16
|
+
* the rename itself refuses one taken meanwhile.
|
|
17
|
+
*/
|
|
18
|
+
export declare function landWhole(scratch: Db, db: Db, chosen: readonly Chosen[], replace: boolean, where: string): Promise<void>;
|
|
19
|
+
/**
|
|
20
|
+
* The documents `selection` takes from each collection in `scratch`,
|
|
21
|
+
* merged into the one `db` has under its name — made first, with the
|
|
22
|
+
* backup's options and indexes, when there is none. Views hold no
|
|
23
|
+
* documents and are passed over. Says how many each collection gave.
|
|
24
|
+
*/
|
|
25
|
+
export declare function landDocuments(scratch: Db, db: Db, chosen: readonly Chosen[], selection: DocumentSelection): Promise<Map<string, number>>;
|
|
26
|
+
//# sourceMappingURL=landing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"landing.d.ts","sourceRoot":"","sources":["../../src/restore/landing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAoB,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAc,MAAM,WAAW,CAAC;AACzD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEnD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAKnD,yEAAyE;AACzE,MAAM,WAAW,MAAM;IACtB,SAAS,EAAE,SAAS,CAAC;IACrB,EAAE,EAAE,MAAM,CAAC;CACX;AAED,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,gBAAgB,CAMrD;AAED;;;;;;GAMG;AACH,wBAAsB,SAAS,CAC9B,OAAO,EAAE,EAAE,EACX,EAAE,EAAE,EAAE,EACN,MAAM,EAAE,SAAS,MAAM,EAAE,EACzB,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,MAAM,GACX,OAAO,CAAC,IAAI,CAAC,CAiCf;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CAClC,OAAO,EAAE,EAAE,EACX,EAAE,EAAE,EAAE,EACN,MAAM,EAAE,SAAS,MAAM,EAAE,EACzB,SAAS,EAAE,iBAAiB,GAC1B,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CA0B9B"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { Restored, RestoreOptions, RestoreTarget } from '@softistx/backup';
|
|
2
|
+
import type { Db, Document } from 'mongodb';
|
|
3
|
+
import type { CollectionFilter } from '../source/collections.js';
|
|
4
|
+
/** What `restoreCollections` needs of a bound backup: its `restore`. */
|
|
5
|
+
export interface Restorer {
|
|
6
|
+
restore(id: string, target: RestoreTarget, options: RestoreOptions): Promise<Restored>;
|
|
7
|
+
}
|
|
8
|
+
/** Some documents of each collection, merged into what is there. */
|
|
9
|
+
export interface DocumentSelection {
|
|
10
|
+
/** A query, as `find` takes it: `{ _id: id }`, or any other. */
|
|
11
|
+
filter: Document;
|
|
12
|
+
/** What a document already there with the same `_id` becomes: the backup's, or kept. */
|
|
13
|
+
existing: 'replace' | 'keep';
|
|
14
|
+
}
|
|
15
|
+
interface Common {
|
|
16
|
+
/** The age secret keys to open the backup with. */
|
|
17
|
+
identities: readonly string[];
|
|
18
|
+
/** The repository to read from, by name. The first one by default. */
|
|
19
|
+
from?: string | undefined;
|
|
20
|
+
/** The database to restore into. */
|
|
21
|
+
db: Db;
|
|
22
|
+
/** The collections and views to restore, by their name at the backup's time. All of them by default. */
|
|
23
|
+
collections?: CollectionFilter | undefined;
|
|
24
|
+
/** The name each one is restored under. Its own by default. */
|
|
25
|
+
as?: Readonly<Record<string, string>> | ((name: string) => string) | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Where the backup is rebuilt first, chain included: an empty database,
|
|
28
|
+
* dropped afterwards. A fresh `nxgt-restore-<uuid>` on `db`'s client by
|
|
29
|
+
* default.
|
|
30
|
+
*/
|
|
31
|
+
scratch?: Db | undefined;
|
|
32
|
+
/** Where a `changes/<n>` entry is staged. The system's temporary folder by default. */
|
|
33
|
+
tmpDir?: string | undefined;
|
|
34
|
+
}
|
|
35
|
+
/** Whole collections and views, each landed whole or not at all. */
|
|
36
|
+
interface Whole extends Common {
|
|
37
|
+
documents?: undefined;
|
|
38
|
+
/** Replace a collection or view already there. `false` by default: `EXISTS`. */
|
|
39
|
+
replace?: boolean | undefined;
|
|
40
|
+
}
|
|
41
|
+
/** Some documents of each collection, merged into the collection there. */
|
|
42
|
+
interface Part extends Common {
|
|
43
|
+
documents: DocumentSelection;
|
|
44
|
+
replace?: never;
|
|
45
|
+
}
|
|
46
|
+
export type RestoreCollectionsOptions = Whole | Part;
|
|
47
|
+
/** What was restored: the backup's entries, and each collection and where it went. */
|
|
48
|
+
export interface RestoredCollections extends Restored {
|
|
49
|
+
collections: {
|
|
50
|
+
name: string;
|
|
51
|
+
as: string;
|
|
52
|
+
documents?: number;
|
|
53
|
+
}[];
|
|
54
|
+
}
|
|
55
|
+
/** The name `name` is restored under, checked. */
|
|
56
|
+
export declare function destinationOf(as: RestoreCollectionsOptions['as'], name: string, where?: string): string;
|
|
57
|
+
export declare function checkOptions(options: RestoreCollectionsOptions, where: string): void;
|
|
58
|
+
export {};
|
|
59
|
+
//# sourceMappingURL=options.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../src/restore/options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,KAAK,EAAE,EAA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ChB;AAED,MAAM,MAAM,yBAAyB,GAAG,KAAK,GAAG,IAAI,CAAC;AAErD,sFAAsF;AACtF,MAAM,WAAW,mBAAoB,SAAQ,QAAQ;IACpD,WAAW,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAChE;AAID,kDAAkD;AAClD,wBAAgB,aAAa,CAC5B,EAAE,EAAE,yBAAyB,CAAC,IAAI,CAAC,EACnC,IAAI,EAAE,MAAM,EACZ,KAAK,SAAuB,GAC1B,MAAM,CAaR;AAmBD,wBAAgB,YAAY,CAC3B,OAAO,EAAE,yBAAyB,EAClC,KAAK,EAAE,MAAM,GACX,IAAI,CAgCN"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type RestoreCollectionsOptions, type RestoredCollections, type Restorer } from './options.js';
|
|
2
|
+
/**
|
|
3
|
+
* Some of a `mongoSource` backup, chain included, restored into `db`: the
|
|
4
|
+
* collections and views `collections` names, each under the name `as`
|
|
5
|
+
* gives it — whole, or only the documents `documents` selects, merged into
|
|
6
|
+
* what is there. The backup is rebuilt in `scratch` first, then what was
|
|
7
|
+
* asked for is taken from it, and `scratch` is dropped, failed or not.
|
|
8
|
+
*/
|
|
9
|
+
export declare function restoreCollections(backups: Restorer, id: string, options: RestoreCollectionsOptions): Promise<RestoredCollections>;
|
|
10
|
+
/** `restoreCollections`, its messages naming the call `where` says. */
|
|
11
|
+
export declare function restoreSome(backups: Restorer, id: string, options: RestoreCollectionsOptions, where: string): Promise<RestoredCollections>;
|
|
12
|
+
//# sourceMappingURL=restore-collections.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"restore-collections.d.ts","sourceRoot":"","sources":["../../src/restore/restore-collections.ts"],"names":[],"mappings":"AAKA,OAAO,EAGN,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EACxB,KAAK,QAAQ,EACb,MAAM,WAAW,CAAC;AAiEnB;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CACjC,OAAO,EAAE,QAAQ,EACjB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,yBAAyB,GAChC,OAAO,CAAC,mBAAmB,CAAC,CAK9B;AAED,uEAAuE;AACvE,wBAAsB,WAAW,CAChC,OAAO,EAAE,QAAQ,EACjB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,yBAAyB,EAClC,KAAK,EAAE,MAAM,GACX,OAAO,CAAC,mBAAmB,CAAC,CAiC9B"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type ClientSession, type Db, type Timestamp } from 'mongodb';
|
|
2
|
+
import type { Metadata } from '../format/metadata.js';
|
|
3
|
+
import { type CollectionFilter, type Listed } from './collections.js';
|
|
4
|
+
/** A collection or a view, with what a backup records of it besides its documents. */
|
|
5
|
+
export interface Described extends Listed {
|
|
6
|
+
metadata: Metadata;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The collections and views the filter takes, each with its options and
|
|
10
|
+
* indexes — or nothing when one went while they were being read.
|
|
11
|
+
*/
|
|
12
|
+
export declare function describe(db: Db, filter: CollectionFilter | undefined): Promise<Described[] | undefined>;
|
|
13
|
+
/**
|
|
14
|
+
* The snapshot, and what it holds besides documents. The collections, their
|
|
15
|
+
* options and their indexes are not read in a snapshot — the server does
|
|
16
|
+
* not serve those reads at a cluster time — so they are read before the
|
|
17
|
+
* pin and again after it: the same both times, they are what the snapshot
|
|
18
|
+
* holds. Otherwise the pin is taken again, up to five times, then
|
|
19
|
+
* `CHANGING`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function pinnedCatalog(db: Db, filter: CollectionFilter | undefined): Promise<{
|
|
22
|
+
session: ClientSession;
|
|
23
|
+
at: Timestamp;
|
|
24
|
+
catalog: Described[];
|
|
25
|
+
}>;
|
|
26
|
+
/** The first cluster time after `at`: what the snapshot read at `at` does not hold. */
|
|
27
|
+
export declare function after(at: Timestamp): Timestamp;
|
|
28
|
+
//# sourceMappingURL=catalog.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../src/source/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,aAAa,EAClB,KAAK,EAAE,EAEP,KAAK,SAAS,EACd,MAAM,SAAS,CAAC;AAEjB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,KAAK,gBAAgB,EAAE,KAAK,MAAM,EAAU,MAAM,eAAe,CAAC;AAQ3E,sFAAsF;AACtF,MAAM,WAAW,SAAU,SAAQ,MAAM;IACxC,QAAQ,EAAE,QAAQ,CAAC;CACnB;AAWD;;;GAGG;AACH,wBAAsB,QAAQ,CAC7B,EAAE,EAAE,EAAE,EACN,MAAM,EAAE,gBAAgB,GAAG,SAAS,GAClC,OAAO,CAAC,SAAS,EAAE,GAAG,SAAS,CAAC,CAmBlC;AAmCD;;;;;;;GAOG;AACH,wBAAsB,aAAa,CAClC,EAAE,EAAE,EAAE,EACN,MAAM,EAAE,gBAAgB,GAAG,SAAS,GAClC,OAAO,CAAC;IAAE,OAAO,EAAE,aAAa,CAAC;IAAC,EAAE,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,SAAS,EAAE,CAAA;CAAE,CAAC,CAkB1E;AAED,uFAAuF;AACvF,wBAAgB,KAAK,CAAC,EAAE,EAAE,SAAS,GAAG,SAAS,CAI9C"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Db, Timestamp } from 'mongodb';
|
|
2
|
+
import type { Resume } from '../format/position.js';
|
|
3
|
+
import type { CollectionFilter } from './collections.js';
|
|
4
|
+
/**
|
|
5
|
+
* The changes since `from`, up to the operation time `until`, to the
|
|
6
|
+
* collections `held` names — brought up to date as they come — as
|
|
7
|
+
* concatenated BSON, then `record` with where the next backup resumes.
|
|
8
|
+
* The stream stops at the first event after `until`, at an invalidation,
|
|
9
|
+
* or once a read of the change stream comes back empty — caught up.
|
|
10
|
+
*/
|
|
11
|
+
export declare function changesOf(db: Db, from: Resume, held: Set<string>, until: Timestamp, filter: CollectionFilter | undefined, record: (resume: Resume) => void): ReadableStream<Uint8Array>;
|
|
12
|
+
//# sourceMappingURL=changes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"changes.d.ts","sourceRoot":"","sources":["../../src/source/changes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,EAAE,EAAY,SAAS,EAAE,MAAM,SAAS,CAAC;AAGrE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAiBtD;;;;;;GAMG;AACH,wBAAgB,SAAS,CACxB,EAAE,EAAE,EAAE,EACN,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,EACjB,KAAK,EAAE,SAAS,EAChB,MAAM,EAAE,gBAAgB,GAAG,SAAS,EACpC,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,GAC9B,cAAc,CAAC,UAAU,CAAC,CAiD5B"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Db, type Document } from 'mongodb';
|
|
2
|
+
/** Which collections a backup reads: their names, or a test on each name. */
|
|
3
|
+
export type CollectionFilter = readonly string[] | ((name: string) => boolean);
|
|
4
|
+
/** A collection or a view, as `listCollections` described it. */
|
|
5
|
+
export interface Listed {
|
|
6
|
+
name: string;
|
|
7
|
+
type: 'collection' | 'view';
|
|
8
|
+
options: Document;
|
|
9
|
+
/** Its UUID, as Extended JSON: a collection dropped and made again has another. */
|
|
10
|
+
uuid: string;
|
|
11
|
+
}
|
|
12
|
+
/** Whether `name` is one the filter takes; `system.*` never is. */
|
|
13
|
+
export declare function takes(filter: CollectionFilter | undefined, name: string): boolean;
|
|
14
|
+
/**
|
|
15
|
+
* The collections and views the filter takes, sorted by name. A name the
|
|
16
|
+
* filter lists that the database lacks is a `TypeError`: a typo would
|
|
17
|
+
* otherwise back up nothing, and say nothing.
|
|
18
|
+
*/
|
|
19
|
+
export declare function listed(db: Db, filter: CollectionFilter | undefined): Promise<Listed[]>;
|
|
20
|
+
//# sourceMappingURL=collections.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"collections.d.ts","sourceRoot":"","sources":["../../src/source/collections.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,EAAE,EAAE,KAAK,QAAQ,EAAE,MAAM,SAAS,CAAC;AAGvD,6EAA6E;AAC7E,MAAM,MAAM,gBAAgB,GAAG,SAAS,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;AAE/E,iEAAiE;AACjE,MAAM,WAAW,MAAM;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,YAAY,GAAG,MAAM,CAAC;IAC5B,OAAO,EAAE,QAAQ,CAAC;IAClB,mFAAmF;IACnF,IAAI,EAAE,MAAM,CAAC;CACb;AAED,mEAAmE;AACnE,wBAAgB,KAAK,CACpB,MAAM,EAAE,gBAAgB,GAAG,SAAS,EACpC,IAAI,EAAE,MAAM,GACV,OAAO,CAIT;AAED;;;;GAIG;AACH,wBAAsB,MAAM,CAC3B,EAAE,EAAE,EAAE,EACN,MAAM,EAAE,gBAAgB,GAAG,SAAS,GAClC,OAAO,CAAC,MAAM,EAAE,CAAC,CA8BnB"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ChangeStreamDocument, Document, Timestamp } from 'mongodb';
|
|
2
|
+
import type { Change } from '../format/change.js';
|
|
3
|
+
import { type CollectionFilter } from './collections.js';
|
|
4
|
+
/** A change-stream event, with `showExpandedEvents`: the fields read from it. */
|
|
5
|
+
export type Event = ChangeStreamDocument & {
|
|
6
|
+
clusterTime?: Timestamp;
|
|
7
|
+
fullDocument?: Document | null;
|
|
8
|
+
documentKey?: Document;
|
|
9
|
+
ns?: {
|
|
10
|
+
db: string;
|
|
11
|
+
coll?: string;
|
|
12
|
+
};
|
|
13
|
+
nsType?: string;
|
|
14
|
+
to?: {
|
|
15
|
+
db: string;
|
|
16
|
+
coll: string;
|
|
17
|
+
};
|
|
18
|
+
operationDescription?: Document;
|
|
19
|
+
updateDescription?: {
|
|
20
|
+
updatedFields?: Document;
|
|
21
|
+
removedFields?: string[];
|
|
22
|
+
truncatedArrays?: {
|
|
23
|
+
field: string;
|
|
24
|
+
newSize: number;
|
|
25
|
+
}[];
|
|
26
|
+
disambiguatedPaths?: Document;
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
/** The change an event records, or nothing when it is not one to keep. */
|
|
30
|
+
export declare function changeOf(event: Event, db: string): Change | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* Whether an event is passed over before it is translated: one on a
|
|
33
|
+
* collection the backup does not follow — or, for a creation, one the
|
|
34
|
+
* filter does not take — so an update or a creation there that a change
|
|
35
|
+
* could not say never fails the backup. A rename is never passed over
|
|
36
|
+
* here: `followed` decides it.
|
|
37
|
+
*/
|
|
38
|
+
export declare function passedOver(event: Event, held: ReadonlySet<string>, filter: CollectionFilter | undefined): boolean;
|
|
39
|
+
/**
|
|
40
|
+
* The change as the backup keeps it, and `held` — the collections it
|
|
41
|
+
* follows — brought up to date. A collection created that the filter takes
|
|
42
|
+
* is followed from then on. A rename out of those followed is a drop, and
|
|
43
|
+
* one into them is refused: the documents it brings were never read.
|
|
44
|
+
*/
|
|
45
|
+
export declare function followed(change: Change, held: Set<string>, filter: CollectionFilter | undefined): Change | undefined;
|
|
46
|
+
//# sourceMappingURL=events.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/source/events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA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,EAAE,MAAM,EACd,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,EACjB,MAAM,EAAE,gBAAgB,GAAG,SAAS,GAClC,MAAM,GAAG,SAAS,CAiBpB"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Since } from '@softistx/backup';
|
|
2
|
+
import type { Position } from '../format/position.js';
|
|
3
|
+
/** The collections and views the chain's full backup holds: one metadata entry each. */
|
|
4
|
+
export declare function heldByFull(since: Since): Set<string>;
|
|
5
|
+
/** What the chain follows: its full backup's, changed as the position says. */
|
|
6
|
+
export declare function followedFrom(full: Set<string>, position: Position): Set<string>;
|
|
7
|
+
/** How `held` differs from what the full backup holds, as a position records it. */
|
|
8
|
+
export declare function differenceOf(full: Set<string>, held: Set<string>): Pick<Position, 'added' | 'removed'>;
|
|
9
|
+
/** The most a position may hold: `@softistx/backup`'s limit. */
|
|
10
|
+
export declare const POSITION_MAX_BYTES: number;
|
|
11
|
+
/** `text`, unless it is longer than a position may be. */
|
|
12
|
+
export declare function fitting(text: string): string;
|
|
13
|
+
//# sourceMappingURL=followed.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"followed.d.ts","sourceRoot":"","sources":["../../src/source/followed.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAG9C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAEnD,wFAAwF;AACxF,wBAAgB,UAAU,CAAC,KAAK,EAAE,KAAK,GAAG,GAAG,CAAC,MAAM,CAAC,CAMpD;AAED,+EAA+E;AAC/E,wBAAgB,YAAY,CAC3B,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,EACjB,QAAQ,EAAE,QAAQ,GAChB,GAAG,CAAC,MAAM,CAAC,CAIb;AAED,oFAAoF;AACpF,wBAAgB,YAAY,CAC3B,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,EACjB,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,GACf,IAAI,CAAC,QAAQ,EAAE,OAAO,GAAG,SAAS,CAAC,CAKrC;AAED,gEAAgE;AAChE,eAAO,MAAM,kBAAkB,QAAY,CAAC;AAE5C,0DAA0D;AAC1D,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAS5C"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { BackupSource } from '@softistx/backup';
|
|
2
|
+
import type { Db } from 'mongodb';
|
|
3
|
+
import type { CollectionFilter } from './collections.js';
|
|
4
|
+
export interface MongoSourceOptions {
|
|
5
|
+
/** The database to back up. Its client must reach a replica set or a sharded cluster. */
|
|
6
|
+
db: Db;
|
|
7
|
+
/**
|
|
8
|
+
* Which collections and views: their names, or a test on each name.
|
|
9
|
+
* Every one but `system.*` by default. A name listed that the database
|
|
10
|
+
* lacks is a `TypeError`.
|
|
11
|
+
*/
|
|
12
|
+
collections?: CollectionFilter | undefined;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A MongoDB database as a backup source. A full backup reads every
|
|
16
|
+
* collection in one snapshot — one cluster time for the whole database —
|
|
17
|
+
* as `metadata/<name>` (options and indexes) and `documents/<name>`
|
|
18
|
+
* (concatenated BSON, as `mongodump` writes it); views have metadata only,
|
|
19
|
+
* and GridFS buckets are collections like any other. An incremental or
|
|
20
|
+
* differential backup reads the change stream from where the backup it
|
|
21
|
+
* builds on stopped, into one `changes/<n>` entry.
|
|
22
|
+
*/
|
|
23
|
+
export declare function mongoSource(options: MongoSourceOptions): BackupSource;
|
|
24
|
+
//# sourceMappingURL=mongo-source.d.ts.map
|