@semics-tech/mongolite 1.2.0 → 1.4.0
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/README.md +91 -20
- package/dist/bin/mongolite-debug.d.ts +6 -1
- package/dist/bin/mongolite-debug.js +6 -113
- package/dist/bin/mongolite-debug.js.map +1 -1
- package/dist/bin/mongolite.d.ts +13 -0
- package/dist/bin/mongolite.js +172 -0
- package/dist/bin/mongolite.js.map +1 -0
- package/dist/cjs/bin/mongolite-debug.js +6 -149
- package/dist/cjs/bin/mongolite.js +207 -0
- package/dist/cjs/cli/discover.js +156 -0
- package/dist/cjs/cli/explorer.js +929 -0
- package/dist/cjs/cli/filter-builder.js +276 -0
- package/dist/cjs/cli/format.js +161 -0
- package/dist/cjs/cli/schema.js +211 -0
- package/dist/cjs/cli/ui.js +431 -0
- package/dist/cjs/collection.js +8 -1
- package/dist/cjs/cursors/findCursor.js +20 -8
- package/dist/cjs/index.js +108 -1
- package/dist/cjs/mongo-client.js +18 -1
- package/dist/cjs/server.js +164 -0
- package/dist/cjs/sync/commands.js +126 -0
- package/dist/cjs/sync/diff.js +174 -0
- package/dist/cjs/sync/httpSink.js +159 -0
- package/dist/cjs/sync/index.js +40 -0
- package/dist/cjs/sync/mongoExecutor.js +306 -0
- package/dist/cjs/sync/mongoSink.js +161 -0
- package/dist/cjs/sync/outbox.js +358 -0
- package/dist/cjs/sync/protocol.js +177 -0
- package/dist/cjs/sync/replicator.js +747 -0
- package/dist/cjs/sync/shadow.js +178 -0
- package/dist/cjs/sync/types.js +2 -0
- package/dist/cli/discover.d.ts +40 -0
- package/dist/cli/discover.js +146 -0
- package/dist/cli/discover.js.map +1 -0
- package/dist/cli/explorer.d.ts +59 -0
- package/dist/cli/explorer.js +923 -0
- package/dist/cli/explorer.js.map +1 -0
- package/dist/cli/filter-builder.d.ts +52 -0
- package/dist/cli/filter-builder.js +268 -0
- package/dist/cli/filter-builder.js.map +1 -0
- package/dist/cli/format.d.ts +29 -0
- package/dist/cli/format.js +153 -0
- package/dist/cli/format.js.map +1 -0
- package/dist/cli/schema.d.ts +58 -0
- package/dist/cli/schema.js +205 -0
- package/dist/cli/schema.js.map +1 -0
- package/dist/cli/ui.d.ts +71 -0
- package/dist/cli/ui.js +379 -0
- package/dist/cli/ui.js.map +1 -0
- package/dist/cloudflare.d.ts +1 -1
- package/dist/cloudflare.js.map +1 -1
- package/dist/collection.js +8 -1
- package/dist/collection.js.map +1 -1
- package/dist/cursors/findCursor.d.ts +12 -0
- package/dist/cursors/findCursor.js +20 -8
- package/dist/cursors/findCursor.js.map +1 -1
- package/dist/index.d.ts +68 -2
- package/dist/index.js +96 -1
- package/dist/index.js.map +1 -1
- package/dist/mongo-client.d.ts +13 -0
- package/dist/mongo-client.js +18 -1
- package/dist/mongo-client.js.map +1 -1
- package/dist/server.d.ts +97 -0
- package/dist/server.js +158 -0
- package/dist/server.js.map +1 -0
- package/dist/sync/commands.d.ts +49 -0
- package/dist/sync/commands.js +118 -0
- package/dist/sync/commands.js.map +1 -0
- package/dist/sync/diff.d.ts +55 -0
- package/dist/sync/diff.js +169 -0
- package/dist/sync/diff.js.map +1 -0
- package/dist/sync/httpSink.d.ts +93 -0
- package/dist/sync/httpSink.js +155 -0
- package/dist/sync/httpSink.js.map +1 -0
- package/dist/sync/index.d.ts +17 -0
- package/dist/sync/index.js +10 -0
- package/dist/sync/index.js.map +1 -0
- package/dist/sync/mongoExecutor.d.ts +37 -0
- package/dist/sync/mongoExecutor.js +302 -0
- package/dist/sync/mongoExecutor.js.map +1 -0
- package/dist/sync/mongoSink.d.ts +109 -0
- package/dist/sync/mongoSink.js +123 -0
- package/dist/sync/mongoSink.js.map +1 -0
- package/dist/sync/outbox.d.ts +120 -0
- package/dist/sync/outbox.js +355 -0
- package/dist/sync/outbox.js.map +1 -0
- package/dist/sync/protocol.d.ts +93 -0
- package/dist/sync/protocol.js +168 -0
- package/dist/sync/protocol.js.map +1 -0
- package/dist/sync/replicator.d.ts +177 -0
- package/dist/sync/replicator.js +744 -0
- package/dist/sync/replicator.js.map +1 -0
- package/dist/sync/shadow.d.ts +54 -0
- package/dist/sync/shadow.js +173 -0
- package/dist/sync/shadow.js.map +1 -0
- package/dist/sync/types.d.ts +388 -0
- package/dist/sync/types.js +2 -0
- package/dist/sync/types.js.map +1 -0
- package/package.json +16 -1
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.executeWrites = executeWrites;
|
|
4
|
+
exports.classifyBulkError = classifyBulkError;
|
|
5
|
+
exports.fetchDocuments = fetchDocuments;
|
|
6
|
+
/**
|
|
7
|
+
* Applies prepared write commands to MongoDB and classifies the outcome.
|
|
8
|
+
*
|
|
9
|
+
* Shared by the direct sink and by the HTTP receiver, so the subtle part has exactly
|
|
10
|
+
* one implementation: **a lost compare-and-swap raises no error.** It is a silent
|
|
11
|
+
* zero-match in an aggregate count, which means detecting it takes deliberate work —
|
|
12
|
+
* comparing what the batch expected to change against what the server says changed, and
|
|
13
|
+
* then re-reading the candidates to find out which document actually lost.
|
|
14
|
+
*/
|
|
15
|
+
const commands_js_1 = require("./commands.js");
|
|
16
|
+
const diff_js_1 = require("./diff.js");
|
|
17
|
+
/**
|
|
18
|
+
* MongoDB server error codes that mean "this write will never succeed" — retrying them
|
|
19
|
+
* would stall the stream behind one bad document forever, so they are dead-lettered.
|
|
20
|
+
*/
|
|
21
|
+
const PERMANENT_ERROR_CODES = new Set([
|
|
22
|
+
2, // BadValue
|
|
23
|
+
9, // FailedToParse
|
|
24
|
+
10334, // BSONObjectTooLarge
|
|
25
|
+
14, // TypeMismatch
|
|
26
|
+
52, // DollarPrefixedFieldName
|
|
27
|
+
56, // EmptyFieldName
|
|
28
|
+
121, // DocumentValidationFailure
|
|
29
|
+
17280, // KeyTooLong
|
|
30
|
+
]);
|
|
31
|
+
/** MongoDB's duplicate-key code. On an insert-if-absent it means we lost a create race. */
|
|
32
|
+
const DUPLICATE_KEY = 11000;
|
|
33
|
+
/**
|
|
34
|
+
* Runs prepared writes against a database, one `bulkWrite` per collection.
|
|
35
|
+
*
|
|
36
|
+
* Throws on transient failure (network, election, timeout) so the caller retries the
|
|
37
|
+
* whole batch without checkpointing. Returns per-operation failures and conflicts for
|
|
38
|
+
* everything it could classify.
|
|
39
|
+
*/
|
|
40
|
+
async function executeWrites(db, writes, options = {}) {
|
|
41
|
+
const { writeConcern = { w: 'majority' }, versioning = true, idMapping, ObjectId } = options;
|
|
42
|
+
const byCollection = new Map();
|
|
43
|
+
for (const write of writes) {
|
|
44
|
+
const bucket = byCollection.get(write.op.collection);
|
|
45
|
+
if (bucket)
|
|
46
|
+
bucket.push(write);
|
|
47
|
+
else
|
|
48
|
+
byCollection.set(write.op.collection, [write]);
|
|
49
|
+
}
|
|
50
|
+
const failures = [];
|
|
51
|
+
const conflicts = [];
|
|
52
|
+
let applied = 0;
|
|
53
|
+
for (const [collectionName, entries] of byCollection) {
|
|
54
|
+
let result = null;
|
|
55
|
+
let rejected = 0;
|
|
56
|
+
try {
|
|
57
|
+
result = await db.collection(collectionName).bulkWrite(entries.map((entry) => entry.command), {
|
|
58
|
+
// Operations within a batch touch distinct documents, so ordering buys
|
|
59
|
+
// nothing and unordered lets the server parallelise.
|
|
60
|
+
ordered: false,
|
|
61
|
+
writeConcern,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
const bulkFailures = classifyBulkError(err, entries.length);
|
|
66
|
+
// A transient failure means the whole batch's fate is unknown — throw so the
|
|
67
|
+
// caller retries it rather than checkpointing work that may not have landed.
|
|
68
|
+
if (bulkFailures === null)
|
|
69
|
+
throw err;
|
|
70
|
+
for (const failure of bulkFailures) {
|
|
71
|
+
const entry = entries[failure.index];
|
|
72
|
+
if (!entry)
|
|
73
|
+
continue;
|
|
74
|
+
// A duplicate `_id` on an insert-if-absent means someone created the document
|
|
75
|
+
// first — a conflict to reconcile, not a poison document. A duplicate on any
|
|
76
|
+
// *other* unique index is a real constraint violation and must be dead-lettered,
|
|
77
|
+
// or it would be retried forever as a phantom conflict.
|
|
78
|
+
if (failure.code === DUPLICATE_KEY && isIdIndexViolation(failure)) {
|
|
79
|
+
conflicts.push({ index: entry.index, reason: 'already-exists' });
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
failures.push({ index: entry.index, message: failure.message, code: failure.code });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
rejected = bulkFailures.length;
|
|
86
|
+
result = err.result ?? null;
|
|
87
|
+
}
|
|
88
|
+
const landed = entries.length - rejected;
|
|
89
|
+
const suspects = findMisses(entries, result, rejected, versioning);
|
|
90
|
+
// `suspects` are candidates to investigate, not confirmed misses: the counts are
|
|
91
|
+
// aggregate, so one short count implicates every conditional write in the batch.
|
|
92
|
+
// Only the re-read says which of them actually lost, and `applied` must be reduced
|
|
93
|
+
// by that number rather than by the number investigated.
|
|
94
|
+
const confirmed = suspects.length
|
|
95
|
+
? await describeConflicts(db, collectionName, suspects, conflicts, idMapping, ObjectId)
|
|
96
|
+
: 0;
|
|
97
|
+
applied += landed - confirmed;
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
applied,
|
|
101
|
+
failures: failures.length > 0 ? failures : undefined,
|
|
102
|
+
conflicts: conflicts.length > 0 ? conflicts : undefined,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Identifies operations whose conditional write may not have matched.
|
|
107
|
+
*
|
|
108
|
+
* `bulkWrite` reports only aggregate counts, so this compares what the batch expected
|
|
109
|
+
* to change against what the server says changed. When the numbers agree, nothing was
|
|
110
|
+
* missed and no per-document work is needed.
|
|
111
|
+
*/
|
|
112
|
+
function findMisses(entries, result, rejected, versioning) {
|
|
113
|
+
if (!versioning || result === null || rejected === entries.length)
|
|
114
|
+
return [];
|
|
115
|
+
const candidates = entries.filter((entry) => (0, commands_js_1.isConditional)(entry.op));
|
|
116
|
+
if (candidates.length === 0)
|
|
117
|
+
return [];
|
|
118
|
+
const writes = candidates.filter((entry) => entry.op.type !== 'delete');
|
|
119
|
+
const deletes = candidates.filter((entry) => entry.op.type === 'delete');
|
|
120
|
+
const acknowledgedWrites = (result.matchedCount ?? 0) + (result.upsertedCount ?? 0);
|
|
121
|
+
const acknowledgedDeletes = result.deletedCount ?? 0;
|
|
122
|
+
const missed = [];
|
|
123
|
+
// The counts are aggregate, so which specific documents missed is unknown; the
|
|
124
|
+
// caller re-reads the candidates and decides per document.
|
|
125
|
+
if (acknowledgedWrites < writes.length)
|
|
126
|
+
missed.push(...writes);
|
|
127
|
+
if (acknowledgedDeletes < deletes.length)
|
|
128
|
+
missed.push(...deletes);
|
|
129
|
+
return missed;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Re-reads the upstream state of operations that may have missed, and records a
|
|
133
|
+
* conflict for each one whose version really has moved on.
|
|
134
|
+
*
|
|
135
|
+
* The re-read turns an aggregate "something didn't match" into a precise, per-document
|
|
136
|
+
* answer, and supplies the current server document the caller needs to reconcile.
|
|
137
|
+
*
|
|
138
|
+
* @returns How many candidates genuinely lost.
|
|
139
|
+
*/
|
|
140
|
+
async function describeConflicts(db, collectionName, candidates, conflicts, idMapping, ObjectId) {
|
|
141
|
+
const ids = candidates.map((entry) => (0, commands_js_1.toUpstreamId)(entry.op.documentId, idMapping, ObjectId));
|
|
142
|
+
const current = await db
|
|
143
|
+
.collection(collectionName)
|
|
144
|
+
.find({ _id: { $in: ids } })
|
|
145
|
+
.toArray();
|
|
146
|
+
const byId = new Map(current.map((doc) => [String(doc._id), doc]));
|
|
147
|
+
let confirmed = 0;
|
|
148
|
+
for (const { index, op } of candidates) {
|
|
149
|
+
const serverDocument = byId.get(op.documentId);
|
|
150
|
+
const serverVersion = (0, commands_js_1.readVersion)(serverDocument);
|
|
151
|
+
if (op.type === 'delete') {
|
|
152
|
+
// Already gone upstream is the outcome we wanted, however it happened.
|
|
153
|
+
if (!serverDocument)
|
|
154
|
+
continue;
|
|
155
|
+
conflicts.push({ index, reason: 'version-mismatch', serverDocument, serverVersion });
|
|
156
|
+
confirmed += 1;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (!serverDocument) {
|
|
160
|
+
conflicts.push({ index, reason: 'missing' });
|
|
161
|
+
confirmed += 1;
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
// The write may have landed after all, with a different operation in the batch
|
|
165
|
+
// being the one that missed.
|
|
166
|
+
//
|
|
167
|
+
// A version one ahead is necessary evidence but nowhere near sufficient: another
|
|
168
|
+
// writer following the same protocol also bumps `_v` by exactly one, so the two
|
|
169
|
+
// cases look identical from the version alone. Confirming that the document
|
|
170
|
+
// actually carries our change is what tells them apart — and getting this wrong
|
|
171
|
+
// silently swallows the very conflicts this machinery exists to catch.
|
|
172
|
+
if ((0, commands_js_1.isConditional)(op) &&
|
|
173
|
+
serverVersion === op.baseVersion + 1 &&
|
|
174
|
+
reflectsWrite(serverDocument, op)) {
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
conflicts.push({ index, reason: 'version-mismatch', serverDocument, serverVersion });
|
|
178
|
+
confirmed += 1;
|
|
179
|
+
}
|
|
180
|
+
return confirmed;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Splits a driver error into per-operation permanent failures.
|
|
184
|
+
*
|
|
185
|
+
* @returns The failures to dead-letter, or `null` when the error is transient and the
|
|
186
|
+
* whole batch should be retried.
|
|
187
|
+
*/
|
|
188
|
+
function classifyBulkError(err, operationCount) {
|
|
189
|
+
const error = err;
|
|
190
|
+
// The driver retried and still could not reach a writable primary.
|
|
191
|
+
if (error.hasErrorLabel?.('RetryableWriteError'))
|
|
192
|
+
return null;
|
|
193
|
+
const writeErrors = error.writeErrors ?? error.result?.writeErrors;
|
|
194
|
+
if (Array.isArray(writeErrors) && writeErrors.length > 0) {
|
|
195
|
+
const failures = [];
|
|
196
|
+
for (const writeError of writeErrors) {
|
|
197
|
+
const code = writeError.code;
|
|
198
|
+
// An unrecognised write error might be transient (a duplicate key during a
|
|
199
|
+
// failover, say), so the batch is worth retrying whole. A duplicate key is
|
|
200
|
+
// handled separately by the caller, as a create race rather than a defect.
|
|
201
|
+
if (code === undefined || (code !== DUPLICATE_KEY && !PERMANENT_ERROR_CODES.has(code))) {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
const index = writeError.index ?? 0;
|
|
205
|
+
if (index >= operationCount)
|
|
206
|
+
return null;
|
|
207
|
+
failures.push({
|
|
208
|
+
index,
|
|
209
|
+
message: writeError.errmsg ?? writeError.message ?? `write error ${code}`,
|
|
210
|
+
code,
|
|
211
|
+
keyPattern: writeError.keyPattern,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return failures;
|
|
215
|
+
}
|
|
216
|
+
// No per-write detail: a connection, timeout or auth error. Retry it.
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* True when the upstream document carries the change this operation was making.
|
|
221
|
+
*
|
|
222
|
+
* Only the paths the operation itself wrote are checked. That is deliberate: those are
|
|
223
|
+
* the values we would have written in local JSON form, so comparing them against the
|
|
224
|
+
* server is meaningful, whereas fields we never touched may hold BSON types the local
|
|
225
|
+
* store cannot represent and would not compare equal.
|
|
226
|
+
*
|
|
227
|
+
* A false positive is possible if another writer happened to set the identical value —
|
|
228
|
+
* and is harmless, since the upstream then holds what we wanted anyway.
|
|
229
|
+
*/
|
|
230
|
+
function reflectsWrite(serverDocument, op) {
|
|
231
|
+
if (op.diff) {
|
|
232
|
+
for (const [path, value] of Object.entries(op.diff.set)) {
|
|
233
|
+
if ((0, commands_js_1.isReservedPath)(path))
|
|
234
|
+
continue;
|
|
235
|
+
if (!valueAtPathEquals(serverDocument, path, value))
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
for (const path of op.diff.unset) {
|
|
239
|
+
if ((0, commands_js_1.isReservedPath)(path))
|
|
240
|
+
continue;
|
|
241
|
+
if (readPath(serverDocument, path) !== undefined)
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
246
|
+
// Whole-document write: every field we sent should be present upstream.
|
|
247
|
+
for (const [key, value] of Object.entries((0, commands_js_1.stripReservedFields)(op.document ?? {}))) {
|
|
248
|
+
if (!valueAtPathEquals(serverDocument, key, value))
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Compares a value at a dotted path against what we wrote.
|
|
255
|
+
*
|
|
256
|
+
* The server side is flattened to local JSON shape first, so a `Date` upstream compares
|
|
257
|
+
* equal to the ISO string a local write would have carried.
|
|
258
|
+
*/
|
|
259
|
+
function valueAtPathEquals(document, path, expected) {
|
|
260
|
+
const actual = readPath(document, path);
|
|
261
|
+
if (actual === undefined)
|
|
262
|
+
return false;
|
|
263
|
+
try {
|
|
264
|
+
return (0, diff_js_1.deepEqual)(JSON.parse(JSON.stringify(actual)), expected);
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/** Reads a dotted path, returning `undefined` if any segment is missing. */
|
|
271
|
+
function readPath(document, path) {
|
|
272
|
+
let current = document;
|
|
273
|
+
for (const segment of path.split('.')) {
|
|
274
|
+
if (typeof current !== 'object' || current === null)
|
|
275
|
+
return undefined;
|
|
276
|
+
current = current[segment];
|
|
277
|
+
if (current === undefined)
|
|
278
|
+
return undefined;
|
|
279
|
+
}
|
|
280
|
+
return current;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* True when a duplicate-key error is about the `_id` index specifically.
|
|
284
|
+
*
|
|
285
|
+
* MongoDB reports the offending index in `keyPattern` (and names it in `errmsg`), which
|
|
286
|
+
* is the only way to tell "someone else created this document" apart from "this document
|
|
287
|
+
* violates a unique constraint on some other field".
|
|
288
|
+
*/
|
|
289
|
+
function isIdIndexViolation(failure) {
|
|
290
|
+
if (failure.keyPattern) {
|
|
291
|
+
const keys = Object.keys(failure.keyPattern);
|
|
292
|
+
return keys.length === 1 && keys[0] === '_id';
|
|
293
|
+
}
|
|
294
|
+
// Older servers and some drivers only give the message; the index name appears in it.
|
|
295
|
+
return /index:\s*_id_/.test(failure.message);
|
|
296
|
+
}
|
|
297
|
+
/** Reads documents back by `_id`, for refreshing a shadow after a conflict. */
|
|
298
|
+
async function fetchDocuments(db, collection, documentIds, idMapping, ObjectId) {
|
|
299
|
+
if (documentIds.length === 0)
|
|
300
|
+
return [];
|
|
301
|
+
const ids = documentIds.map((id) => (0, commands_js_1.toUpstreamId)(id, idMapping, ObjectId));
|
|
302
|
+
return db
|
|
303
|
+
.collection(collection)
|
|
304
|
+
.find({ _id: { $in: ids } })
|
|
305
|
+
.toArray();
|
|
306
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* A {@link SyncSink} that writes to a MongoDB deployment using the official
|
|
4
|
+
* `mongodb` driver.
|
|
5
|
+
*
|
|
6
|
+
* The driver is an **optional peer dependency**, imported dynamically the first
|
|
7
|
+
* time a connection is opened. Projects that never replicate upstream do not
|
|
8
|
+
* need it installed, and bundlers that never reach this module do not pull it in.
|
|
9
|
+
*/
|
|
10
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
11
|
+
if (k2 === undefined) k2 = k;
|
|
12
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
13
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
14
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
15
|
+
}
|
|
16
|
+
Object.defineProperty(o, k2, desc);
|
|
17
|
+
}) : (function(o, m, k, k2) {
|
|
18
|
+
if (k2 === undefined) k2 = k;
|
|
19
|
+
o[k2] = m[k];
|
|
20
|
+
}));
|
|
21
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
22
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
23
|
+
}) : function(o, v) {
|
|
24
|
+
o["default"] = v;
|
|
25
|
+
});
|
|
26
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
27
|
+
var ownKeys = function(o) {
|
|
28
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
29
|
+
var ar = [];
|
|
30
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
31
|
+
return ar;
|
|
32
|
+
};
|
|
33
|
+
return ownKeys(o);
|
|
34
|
+
};
|
|
35
|
+
return function (mod) {
|
|
36
|
+
if (mod && mod.__esModule) return mod;
|
|
37
|
+
var result = {};
|
|
38
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
39
|
+
__setModuleDefault(result, mod);
|
|
40
|
+
return result;
|
|
41
|
+
};
|
|
42
|
+
})();
|
|
43
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
44
|
+
exports.MongoUpstreamSink = exports.UPDATED_AT_FIELD = exports.VERSION_FIELD = void 0;
|
|
45
|
+
const commands_js_1 = require("./commands.js");
|
|
46
|
+
const mongoExecutor_js_1 = require("./mongoExecutor.js");
|
|
47
|
+
var commands_js_2 = require("./commands.js");
|
|
48
|
+
Object.defineProperty(exports, "VERSION_FIELD", { enumerable: true, get: function () { return commands_js_2.VERSION_FIELD; } });
|
|
49
|
+
Object.defineProperty(exports, "UPDATED_AT_FIELD", { enumerable: true, get: function () { return commands_js_2.UPDATED_AT_FIELD; } });
|
|
50
|
+
class MongoUpstreamSink {
|
|
51
|
+
constructor(options) {
|
|
52
|
+
this.options = options;
|
|
53
|
+
this.name = 'mongodb';
|
|
54
|
+
this.client = null;
|
|
55
|
+
this.db = null;
|
|
56
|
+
this.driver = null;
|
|
57
|
+
if (!options.connectionString) {
|
|
58
|
+
throw new Error('MongoUpstreamSink requires a `connectionString`.');
|
|
59
|
+
}
|
|
60
|
+
this.idMapping = options.idMapping ?? 'auto';
|
|
61
|
+
this.versioning = options.versioning ?? true;
|
|
62
|
+
this.driver = options.driver ?? null;
|
|
63
|
+
}
|
|
64
|
+
async connect() {
|
|
65
|
+
if (this.client && this.db)
|
|
66
|
+
return;
|
|
67
|
+
const driver = await this.loadDriver();
|
|
68
|
+
const client = new driver.MongoClient(this.options.connectionString, this.clientOptions());
|
|
69
|
+
await client.connect();
|
|
70
|
+
this.client = client;
|
|
71
|
+
this.db = client.db(this.options.database);
|
|
72
|
+
}
|
|
73
|
+
async apply(operations) {
|
|
74
|
+
if (!this.db)
|
|
75
|
+
await this.connect();
|
|
76
|
+
const db = this.db;
|
|
77
|
+
if (!db)
|
|
78
|
+
throw new Error('MongoUpstreamSink is not connected.');
|
|
79
|
+
const writes = operations.map((op, index) => ({
|
|
80
|
+
index,
|
|
81
|
+
op,
|
|
82
|
+
command: (0, commands_js_1.buildWriteCommand)(op, this.commandOptions()),
|
|
83
|
+
}));
|
|
84
|
+
return (0, mongoExecutor_js_1.executeWrites)(db, writes, {
|
|
85
|
+
writeConcern: this.options.writeConcern ?? { w: 'majority' },
|
|
86
|
+
versioning: this.versioning,
|
|
87
|
+
idMapping: this.idMapping,
|
|
88
|
+
ObjectId: this.driver?.ObjectId,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Command-building settings. The driver's own `ObjectId` is used when available so
|
|
93
|
+
* BSON instances match the connection that will serialise them.
|
|
94
|
+
*/
|
|
95
|
+
commandOptions() {
|
|
96
|
+
return {
|
|
97
|
+
idMapping: this.idMapping,
|
|
98
|
+
versioning: this.versioning,
|
|
99
|
+
ObjectId: this.driver?.ObjectId,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
async fetch(collection, documentIds) {
|
|
103
|
+
if (documentIds.length === 0)
|
|
104
|
+
return [];
|
|
105
|
+
if (!this.db)
|
|
106
|
+
await this.connect();
|
|
107
|
+
const db = this.db;
|
|
108
|
+
if (!db)
|
|
109
|
+
throw new Error('MongoUpstreamSink is not connected.');
|
|
110
|
+
return (0, mongoExecutor_js_1.fetchDocuments)(db, collection, documentIds, this.idMapping, this.driver?.ObjectId);
|
|
111
|
+
}
|
|
112
|
+
async close() {
|
|
113
|
+
const client = this.client;
|
|
114
|
+
this.client = null;
|
|
115
|
+
this.db = null;
|
|
116
|
+
if (client)
|
|
117
|
+
await client.close();
|
|
118
|
+
}
|
|
119
|
+
// ---------------------------------------------------------------- internals
|
|
120
|
+
async loadDriver() {
|
|
121
|
+
if (this.driver)
|
|
122
|
+
return this.driver;
|
|
123
|
+
try {
|
|
124
|
+
// Indirect specifier: `mongodb` is optional, and a literal import would
|
|
125
|
+
// make it a hard build-time dependency for everyone compiling this package.
|
|
126
|
+
const specifier = 'mongodb';
|
|
127
|
+
const mod = (await Promise.resolve(`${specifier}`).then(s => __importStar(require(s))));
|
|
128
|
+
this.driver = mod;
|
|
129
|
+
return mod;
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
throw new Error('MongoDB sync requires the `mongodb` driver. Install it with `npm install mongodb`, ' +
|
|
133
|
+
`or pass a \`driver\` explicitly. Original error: ${err instanceof Error ? err.message : String(err)}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
clientOptions() {
|
|
137
|
+
const { authSource, authMechanism, authMechanismProperties, username, password, tls, tlsCAFile, tlsCertificateKeyFile, tlsCertificateKeyFilePassword, tlsCRLFile, tlsAllowInvalidHostnames, tlsAllowInvalidCertificates, driverOptions, } = this.options;
|
|
138
|
+
const auth = username !== undefined || password !== undefined ? { username, password } : undefined;
|
|
139
|
+
// Undefined keys are stripped so they never override a setting that the
|
|
140
|
+
// connection string already specified.
|
|
141
|
+
return stripUndefined({
|
|
142
|
+
authSource,
|
|
143
|
+
authMechanism,
|
|
144
|
+
authMechanismProperties,
|
|
145
|
+
auth,
|
|
146
|
+
tls,
|
|
147
|
+
tlsCAFile,
|
|
148
|
+
tlsCertificateKeyFile,
|
|
149
|
+
tlsCertificateKeyFilePassword,
|
|
150
|
+
tlsCRLFile,
|
|
151
|
+
tlsAllowInvalidHostnames,
|
|
152
|
+
tlsAllowInvalidCertificates,
|
|
153
|
+
...driverOptions,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
exports.MongoUpstreamSink = MongoUpstreamSink;
|
|
158
|
+
/** Drops unset keys so they never override what the connection string specified. */
|
|
159
|
+
function stripUndefined(value) {
|
|
160
|
+
return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined));
|
|
161
|
+
}
|