@powersync/service-module-mongodb 0.15.1 → 0.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/replication/ChangeStream.d.ts +4 -12
  3. package/dist/replication/ChangeStream.js +378 -443
  4. package/dist/replication/ChangeStream.js.map +1 -1
  5. package/dist/replication/ChangeStreamReplicationJob.d.ts +1 -1
  6. package/dist/replication/ChangeStreamReplicationJob.js +1 -1
  7. package/dist/replication/ChangeStreamReplicationJob.js.map +1 -1
  8. package/dist/replication/ChangeStreamReplicator.d.ts +0 -1
  9. package/dist/replication/ChangeStreamReplicator.js +0 -21
  10. package/dist/replication/ChangeStreamReplicator.js.map +1 -1
  11. package/dist/replication/MongoSnapshotQuery.d.ts +2 -0
  12. package/dist/replication/MongoSnapshotQuery.js +4 -2
  13. package/dist/replication/MongoSnapshotQuery.js.map +1 -1
  14. package/dist/replication/internal-mongodb-utils.d.ts +21 -0
  15. package/dist/replication/internal-mongodb-utils.js +70 -0
  16. package/dist/replication/internal-mongodb-utils.js.map +1 -0
  17. package/dist/replication/replication-index.d.ts +1 -0
  18. package/dist/replication/replication-index.js +1 -0
  19. package/dist/replication/replication-index.js.map +1 -1
  20. package/package.json +8 -8
  21. package/src/replication/ChangeStream.ts +84 -31
  22. package/src/replication/ChangeStreamReplicationJob.ts +1 -1
  23. package/src/replication/ChangeStreamReplicator.ts +0 -21
  24. package/src/replication/MongoSnapshotQuery.ts +7 -3
  25. package/src/replication/internal-mongodb-utils.ts +91 -0
  26. package/src/replication/replication-index.ts +1 -0
  27. package/test/src/change_stream.test.ts +57 -1
  28. package/test/src/internal_mongodb_utils.test.ts +103 -0
  29. package/tsconfig.tsbuildinfo +1 -1
@@ -1,62 +1,11 @@
1
- var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
- if (value !== null && value !== void 0) {
3
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
- var dispose, inner;
5
- if (async) {
6
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
- dispose = value[Symbol.asyncDispose];
8
- }
9
- if (dispose === void 0) {
10
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
- dispose = value[Symbol.dispose];
12
- if (async) inner = dispose;
13
- }
14
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
- if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
- env.stack.push({ value: value, dispose: dispose, async: async });
17
- }
18
- else if (async) {
19
- env.stack.push({ async: true });
20
- }
21
- return value;
22
- };
23
- var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
- return function (env) {
25
- function fail(e) {
26
- env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
- env.hasError = true;
28
- }
29
- var r, s = 0;
30
- function next() {
31
- while (r = env.stack.pop()) {
32
- try {
33
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
- if (r.dispose) {
35
- var result = r.dispose.call(r.value);
36
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
- }
38
- else s |= 1;
39
- }
40
- catch (e) {
41
- fail(e);
42
- }
43
- }
44
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
- if (env.hasError) throw env.error;
46
- }
47
- return next();
48
- };
49
- })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
- var e = new Error(message);
51
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
- });
53
1
  import { isMongoNetworkTimeoutError, isMongoServerError, mongo } from '@powersync/lib-service-mongodb';
54
2
  import { container, DatabaseConnectionError, logger as defaultLogger, ErrorCode, ReplicationAbortedError, ReplicationAssertionError, ServiceError } from '@powersync/lib-services-framework';
55
- import { RelationCache, SaveOperationTag } from '@powersync/service-core';
3
+ import { RelationCache, ReplicationLagTracker, SaveOperationTag } from '@powersync/service-core';
56
4
  import { ReplicationMetric } from '@powersync/service-types';
57
5
  import { MongoLSN } from '../common/MongoLSN.js';
58
6
  import { PostImagesOption } from '../types/types.js';
59
7
  import { escapeRegExp } from '../utils.js';
8
+ import { trackChangeStreamBsonBytes } from './internal-mongodb-utils.js';
60
9
  import { constructAfterRecord, createCheckpoint, getCacheIdentifier, getMongoRelation, STANDALONE_CHECKPOINT_ID } from './MongoRelation.js';
61
10
  import { ChunkedSnapshotQuery } from './MongoSnapshotQuery.js';
62
11
  import { CHECKPOINTS_COLLECTION, timestampToDate } from './replication-utils.js';
@@ -85,16 +34,7 @@ export class ChangeStream {
85
34
  maxAwaitTimeMS;
86
35
  abort_signal;
87
36
  relationCache = new RelationCache(getCacheIdentifier);
88
- /**
89
- * Time of the oldest uncommitted change, according to the source db.
90
- * This is used to determine the replication lag.
91
- */
92
- oldestUncommittedChange = null;
93
- /**
94
- * Keep track of whether we have done a commit or keepalive yet.
95
- * We can only compute replication lag if isStartingReplication == false, or oldestUncommittedChange is present.
96
- */
97
- isStartingReplication = true;
37
+ replicationLag = new ReplicationLagTracker();
98
38
  checkpointStreamId = new mongo.ObjectId();
99
39
  logger;
100
40
  snapshotChunkLength;
@@ -188,101 +128,77 @@ export class ChangeStream {
188
128
  * This LSN can survive initial replication restarts.
189
129
  */
190
130
  async getSnapshotLsn() {
191
- const env_1 = { stack: [], error: void 0, hasError: false };
192
- try {
193
- const hello = await this.defaultDb.command({ hello: 1 });
194
- // Basic sanity check
195
- if (hello.msg == 'isdbgrid') {
196
- throw new ServiceError(ErrorCode.PSYNC_S1341, 'Sharded MongoDB Clusters are not supported yet (including MongoDB Serverless instances).');
131
+ const hello = await this.defaultDb.command({ hello: 1 });
132
+ // Basic sanity check
133
+ if (hello.msg == 'isdbgrid') {
134
+ throw new ServiceError(ErrorCode.PSYNC_S1341, 'Sharded MongoDB Clusters are not supported yet (including MongoDB Serverless instances).');
135
+ }
136
+ else if (hello.setName == null) {
137
+ throw new ServiceError(ErrorCode.PSYNC_S1342, 'Standalone MongoDB instances are not supported - use a replicaset.');
138
+ }
139
+ // Open a change stream just to get a resume token for later use.
140
+ // We could use clusterTime from the hello command, but that won't tell us if the
141
+ // snapshot isn't valid anymore.
142
+ // If we just use the first resumeToken from the stream, we get two potential issues:
143
+ // 1. The resumeToken may just be a wrapped clusterTime, which does not detect changes
144
+ // in source db or other stream issues.
145
+ // 2. The first actual change we get may have the same clusterTime, causing us to incorrect
146
+ // skip that event.
147
+ // Instead, we create a new checkpoint document, and wait until we get that document back in the stream.
148
+ // To avoid potential race conditions with the checkpoint creation, we create a new checkpoint document
149
+ // periodically until the timeout is reached.
150
+ const LSN_TIMEOUT_SECONDS = 60;
151
+ const LSN_CREATE_INTERVAL_SECONDS = 1;
152
+ // Create a checkpoint, and open a change stream using startAtOperationTime with the checkpoint's operationTime.
153
+ const firstCheckpointLsn = await createCheckpoint(this.client, this.defaultDb, this.checkpointStreamId);
154
+ await using streamManager = this.openChangeStream({ lsn: firstCheckpointLsn, maxAwaitTimeMs: 0 });
155
+ const { stream } = streamManager;
156
+ const startTime = performance.now();
157
+ let lastCheckpointCreated = performance.now();
158
+ let eventsSeen = 0;
159
+ while (performance.now() - startTime < LSN_TIMEOUT_SECONDS * 1000) {
160
+ if (performance.now() - lastCheckpointCreated >= LSN_CREATE_INTERVAL_SECONDS * 1000) {
161
+ await createCheckpoint(this.client, this.defaultDb, this.checkpointStreamId);
162
+ lastCheckpointCreated = performance.now();
197
163
  }
198
- else if (hello.setName == null) {
199
- throw new ServiceError(ErrorCode.PSYNC_S1342, 'Standalone MongoDB instances are not supported - use a replicaset.');
164
+ // tryNext() doesn't block, while next() / hasNext() does block until there is data on the stream
165
+ const changeDocument = await stream.tryNext().catch((e) => {
166
+ throw mapChangeStreamError(e);
167
+ });
168
+ if (changeDocument == null) {
169
+ continue;
200
170
  }
201
- // Open a change stream just to get a resume token for later use.
202
- // We could use clusterTime from the hello command, but that won't tell us if the
203
- // snapshot isn't valid anymore.
204
- // If we just use the first resumeToken from the stream, we get two potential issues:
205
- // 1. The resumeToken may just be a wrapped clusterTime, which does not detect changes
206
- // in source db or other stream issues.
207
- // 2. The first actual change we get may have the same clusterTime, causing us to incorrect
208
- // skip that event.
209
- // Instead, we create a new checkpoint document, and wait until we get that document back in the stream.
210
- // To avoid potential race conditions with the checkpoint creation, we create a new checkpoint document
211
- // periodically until the timeout is reached.
212
- const LSN_TIMEOUT_SECONDS = 60;
213
- const LSN_CREATE_INTERVAL_SECONDS = 1;
214
- // Create a checkpoint, and open a change stream using startAtOperationTime with the checkpoint's operationTime.
215
- const firstCheckpointLsn = await createCheckpoint(this.client, this.defaultDb, this.checkpointStreamId);
216
- const streamManager = __addDisposableResource(env_1, this.openChangeStream({ lsn: firstCheckpointLsn, maxAwaitTimeMs: 0 }), true);
217
- const { stream } = streamManager;
218
- const startTime = performance.now();
219
- let lastCheckpointCreated = performance.now();
220
- let eventsSeen = 0;
221
- while (performance.now() - startTime < LSN_TIMEOUT_SECONDS * 1000) {
222
- if (performance.now() - lastCheckpointCreated >= LSN_CREATE_INTERVAL_SECONDS * 1000) {
223
- await createCheckpoint(this.client, this.defaultDb, this.checkpointStreamId);
224
- lastCheckpointCreated = performance.now();
225
- }
226
- // tryNext() doesn't block, while next() / hasNext() does block until there is data on the stream
227
- const changeDocument = await stream.tryNext().catch((e) => {
228
- throw mapChangeStreamError(e);
229
- });
230
- if (changeDocument == null) {
171
+ const ns = 'ns' in changeDocument && 'coll' in changeDocument.ns ? changeDocument.ns : undefined;
172
+ if (ns?.coll == CHECKPOINTS_COLLECTION && 'documentKey' in changeDocument) {
173
+ const checkpointId = changeDocument.documentKey._id;
174
+ if (!this.checkpointStreamId.equals(checkpointId)) {
231
175
  continue;
232
176
  }
233
- const ns = 'ns' in changeDocument && 'coll' in changeDocument.ns ? changeDocument.ns : undefined;
234
- if (ns?.coll == CHECKPOINTS_COLLECTION && 'documentKey' in changeDocument) {
235
- const checkpointId = changeDocument.documentKey._id;
236
- if (!this.checkpointStreamId.equals(checkpointId)) {
237
- continue;
238
- }
239
- const { comparable: lsn } = new MongoLSN({
240
- timestamp: changeDocument.clusterTime,
241
- resume_token: changeDocument._id
242
- });
243
- return lsn;
244
- }
245
- eventsSeen += 1;
177
+ const { comparable: lsn } = new MongoLSN({
178
+ timestamp: changeDocument.clusterTime,
179
+ resume_token: changeDocument._id
180
+ });
181
+ return lsn;
246
182
  }
247
- // Could happen if there is a very large replication lag?
248
- throw new ServiceError(ErrorCode.PSYNC_S1301, `Timeout after while waiting for checkpoint document for ${LSN_TIMEOUT_SECONDS}s. Streamed events = ${eventsSeen}`);
249
- }
250
- catch (e_1) {
251
- env_1.error = e_1;
252
- env_1.hasError = true;
253
- }
254
- finally {
255
- const result_1 = __disposeResources(env_1);
256
- if (result_1)
257
- await result_1;
183
+ eventsSeen += 1;
258
184
  }
185
+ // Could happen if there is a very large replication lag?
186
+ throw new ServiceError(ErrorCode.PSYNC_S1301, `Timeout after while waiting for checkpoint document for ${LSN_TIMEOUT_SECONDS}s. Streamed events = ${eventsSeen}`);
259
187
  }
260
188
  /**
261
189
  * Given a snapshot LSN, validate that we can read from it, by opening a change stream.
262
190
  */
263
191
  async validateSnapshotLsn(lsn) {
264
- const env_2 = { stack: [], error: void 0, hasError: false };
192
+ await using streamManager = this.openChangeStream({ lsn: lsn, maxAwaitTimeMs: 0 });
193
+ const { stream } = streamManager;
265
194
  try {
266
- const streamManager = __addDisposableResource(env_2, this.openChangeStream({ lsn: lsn, maxAwaitTimeMs: 0 }), true);
267
- const { stream } = streamManager;
268
- try {
269
- // tryNext() doesn't block, while next() / hasNext() does block until there is data on the stream
270
- await stream.tryNext();
271
- }
272
- catch (e) {
273
- // Note: A timeout here is not handled as a ChangeStreamInvalidatedError, even though
274
- // we possibly cannot recover from it.
275
- throw mapChangeStreamError(e);
276
- }
195
+ // tryNext() doesn't block, while next() / hasNext() does block until there is data on the stream
196
+ await stream.tryNext();
277
197
  }
278
- catch (e_2) {
279
- env_2.error = e_2;
280
- env_2.hasError = true;
281
- }
282
- finally {
283
- const result_2 = __disposeResources(env_2);
284
- if (result_2)
285
- await result_2;
198
+ catch (e) {
199
+ // Note: A timeout here is not handled as a ChangeStreamInvalidatedError, even though
200
+ // we possibly cannot recover from it.
201
+ throw mapChangeStreamError(e);
286
202
  }
287
203
  }
288
204
  async initialReplication(snapshotLsn) {
@@ -420,75 +336,68 @@ export class ChangeStream {
420
336
  }
421
337
  }
422
338
  async snapshotTable(batch, table) {
423
- const env_3 = { stack: [], error: void 0, hasError: false };
424
- try {
425
- const totalEstimatedCount = await this.estimatedCountNumber(table);
426
- let at = table.snapshotStatus?.replicatedCount ?? 0;
427
- const db = this.client.db(table.schema);
428
- const collection = db.collection(table.name);
429
- const query = __addDisposableResource(env_3, new ChunkedSnapshotQuery({
430
- collection,
431
- key: table.snapshotStatus?.lastKey,
432
- batchSize: this.snapshotChunkLength
433
- }), true);
434
- if (query.lastKey != null) {
435
- this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()} - resuming at _id > ${query.lastKey}`);
339
+ const rowsReplicatedMetric = this.metrics.getCounter(ReplicationMetric.ROWS_REPLICATED);
340
+ const bytesReplicatedMetric = this.metrics.getCounter(ReplicationMetric.DATA_REPLICATED_BYTES);
341
+ const chunksReplicatedMetric = this.metrics.getCounter(ReplicationMetric.CHUNKS_REPLICATED);
342
+ const totalEstimatedCount = await this.estimatedCountNumber(table);
343
+ let at = table.snapshotStatus?.replicatedCount ?? 0;
344
+ const db = this.client.db(table.schema);
345
+ const collection = db.collection(table.name);
346
+ await using query = new ChunkedSnapshotQuery({
347
+ collection,
348
+ key: table.snapshotStatus?.lastKey,
349
+ batchSize: this.snapshotChunkLength
350
+ });
351
+ if (query.lastKey != null) {
352
+ this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()} - resuming at _id > ${query.lastKey}`);
353
+ }
354
+ else {
355
+ this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()}`);
356
+ }
357
+ let lastBatch = performance.now();
358
+ let nextChunkPromise = query.nextChunk();
359
+ while (true) {
360
+ const { docs: docBatch, lastKey, bytes: chunkBytes } = await nextChunkPromise;
361
+ if (docBatch.length == 0) {
362
+ // No more data - stop iterating
363
+ break;
436
364
  }
437
- else {
438
- this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()}`);
365
+ bytesReplicatedMetric.add(chunkBytes);
366
+ chunksReplicatedMetric.add(1);
367
+ if (this.abort_signal.aborted) {
368
+ throw new ReplicationAbortedError(`Aborted initial replication`, this.abort_signal.reason);
439
369
  }
440
- let lastBatch = performance.now();
441
- let nextChunkPromise = query.nextChunk();
442
- while (true) {
443
- const { docs: docBatch, lastKey } = await nextChunkPromise;
444
- if (docBatch.length == 0) {
445
- // No more data - stop iterating
446
- break;
447
- }
448
- if (this.abort_signal.aborted) {
449
- throw new ReplicationAbortedError(`Aborted initial replication`, this.abort_signal.reason);
450
- }
451
- // Pre-fetch next batch, so that we can read and write concurrently
452
- nextChunkPromise = query.nextChunk();
453
- for (let document of docBatch) {
454
- const record = this.constructAfterRecord(document);
455
- // This auto-flushes when the batch reaches its size limit
456
- await batch.save({
457
- tag: SaveOperationTag.INSERT,
458
- sourceTable: table,
459
- before: undefined,
460
- beforeReplicaId: undefined,
461
- after: record,
462
- afterReplicaId: document._id
463
- });
464
- }
465
- // Important: flush before marking progress
466
- await batch.flush();
467
- at += docBatch.length;
468
- this.metrics.getCounter(ReplicationMetric.ROWS_REPLICATED).add(docBatch.length);
469
- table = await batch.updateTableProgress(table, {
470
- lastKey,
471
- replicatedCount: at,
472
- totalEstimatedCount: totalEstimatedCount
370
+ // Pre-fetch next batch, so that we can read and write concurrently
371
+ nextChunkPromise = query.nextChunk();
372
+ for (let document of docBatch) {
373
+ const record = this.constructAfterRecord(document);
374
+ // This auto-flushes when the batch reaches its size limit
375
+ await batch.save({
376
+ tag: SaveOperationTag.INSERT,
377
+ sourceTable: table,
378
+ before: undefined,
379
+ beforeReplicaId: undefined,
380
+ after: record,
381
+ afterReplicaId: document._id
473
382
  });
474
- this.relationCache.update(table);
475
- const duration = performance.now() - lastBatch;
476
- lastBatch = performance.now();
477
- this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()} in ${duration.toFixed(0)}ms`);
478
- this.touch();
479
383
  }
480
- // In case the loop was interrupted, make sure we await the last promise.
481
- await nextChunkPromise;
482
- }
483
- catch (e_3) {
484
- env_3.error = e_3;
485
- env_3.hasError = true;
486
- }
487
- finally {
488
- const result_3 = __disposeResources(env_3);
489
- if (result_3)
490
- await result_3;
384
+ // Important: flush before marking progress
385
+ await batch.flush();
386
+ at += docBatch.length;
387
+ rowsReplicatedMetric.add(docBatch.length);
388
+ table = await batch.updateTableProgress(table, {
389
+ lastKey,
390
+ replicatedCount: at,
391
+ totalEstimatedCount: totalEstimatedCount
392
+ });
393
+ this.relationCache.update(table);
394
+ const duration = performance.now() - lastBatch;
395
+ lastBatch = performance.now();
396
+ this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()} in ${duration.toFixed(0)}ms`);
397
+ this.touch();
491
398
  }
399
+ // In case the loop was interrupted, make sure we await the last promise.
400
+ await nextChunkPromise;
492
401
  }
493
402
  async getRelation(batch, descriptor, options) {
494
403
  const existing = this.relationCache.get(descriptor);
@@ -721,7 +630,22 @@ export class ChangeStream {
721
630
  }
722
631
  };
723
632
  }
633
+ getBufferedChangeCount(stream) {
634
+ // The driver keeps fetched change stream documents on the underlying cursor, but does
635
+ // not expose that through the public ChangeStream API. We use this to detect backlog
636
+ // building up before we have processed the corresponding source changes locally.
637
+ // If the driver API changes, we'll have a hard error here.
638
+ // We specifically want to avoid a silent performance regression if the driver behavior changes.
639
+ const cursor = stream.cursor;
640
+ if (cursor == null || typeof cursor.bufferedCount != 'function') {
641
+ throw new ReplicationAssertionError('MongoDB ChangeStream no longer exposes an internal cursor with bufferedCount');
642
+ }
643
+ return cursor.bufferedCount();
644
+ }
724
645
  async streamChangesInternal() {
646
+ const transactionsReplicatedMetric = this.metrics.getCounter(ReplicationMetric.TRANSACTIONS_REPLICATED);
647
+ const bytesReplicatedMetric = this.metrics.getCounter(ReplicationMetric.DATA_REPLICATED_BYTES);
648
+ const chunksReplicatedMetric = this.metrics.getCounter(ReplicationMetric.CHUNKS_REPLICATED);
725
649
  await this.storage.startBatch({
726
650
  logger: this.logger,
727
651
  zeroLSN: MongoLSN.ZERO.comparable,
@@ -729,265 +653,267 @@ export class ChangeStream {
729
653
  // We get a complete postimage for every change, so we don't need to store the current data.
730
654
  storeCurrentData: false
731
655
  }, async (batch) => {
732
- const env_4 = { stack: [], error: void 0, hasError: false };
733
- try {
734
- const { resumeFromLsn } = batch;
735
- if (resumeFromLsn == null) {
736
- throw new ReplicationAssertionError(`No LSN found to resume from`);
656
+ const { resumeFromLsn } = batch;
657
+ if (resumeFromLsn == null) {
658
+ throw new ReplicationAssertionError(`No LSN found to resume from`);
659
+ }
660
+ const lastLsn = MongoLSN.fromSerialized(resumeFromLsn);
661
+ const startAfter = lastLsn?.timestamp;
662
+ // It is normal for this to be a minute or two old when there is a low volume
663
+ // of ChangeStream events.
664
+ const tokenAgeSeconds = Math.round((Date.now() - timestampToDate(startAfter).getTime()) / 1000);
665
+ this.logger.info(`Resume streaming at ${startAfter?.inspect()} / ${lastLsn} | Token age: ${tokenAgeSeconds}s`);
666
+ await using streamManager = this.openChangeStream({ lsn: resumeFromLsn });
667
+ const { stream, filters } = streamManager;
668
+ if (this.abort_signal.aborted) {
669
+ await stream.close();
670
+ return;
671
+ }
672
+ trackChangeStreamBsonBytes(stream, (bytes) => {
673
+ bytesReplicatedMetric.add(bytes);
674
+ // Each of these represent a single response message from MongoDB.
675
+ chunksReplicatedMetric.add(1);
676
+ });
677
+ // Always start with a checkpoint.
678
+ // This helps us to clear errors when restarting, even if there is
679
+ // no data to replicate.
680
+ let waitForCheckpointLsn = await createCheckpoint(this.client, this.defaultDb, this.checkpointStreamId);
681
+ let splitDocument = null;
682
+ let flexDbNameWorkaroundLogged = false;
683
+ let changesSinceLastCheckpoint = 0;
684
+ let lastEmptyResume = performance.now();
685
+ let lastTxnKey = null;
686
+ while (true) {
687
+ if (this.abort_signal.aborted) {
688
+ break;
689
+ }
690
+ const originalChangeDocument = await stream.tryNext().catch((e) => {
691
+ throw mapChangeStreamError(e);
692
+ });
693
+ // The stream was closed, we will only ever receive `null` from it
694
+ if (!originalChangeDocument && stream.closed) {
695
+ break;
737
696
  }
738
- const lastLsn = MongoLSN.fromSerialized(resumeFromLsn);
739
- const startAfter = lastLsn?.timestamp;
740
- // It is normal for this to be a minute or two old when there is a low volume
741
- // of ChangeStream events.
742
- const tokenAgeSeconds = Math.round((Date.now() - timestampToDate(startAfter).getTime()) / 1000);
743
- this.logger.info(`Resume streaming at ${startAfter?.inspect()} / ${lastLsn} | Token age: ${tokenAgeSeconds}s`);
744
- const streamManager = __addDisposableResource(env_4, this.openChangeStream({ lsn: resumeFromLsn }), true);
745
- const { stream, filters } = streamManager;
746
697
  if (this.abort_signal.aborted) {
747
- await stream.close();
748
- return;
698
+ break;
749
699
  }
750
- // Always start with a checkpoint.
751
- // This helps us to clear errors when restarting, even if there is
752
- // no data to replicate.
753
- let waitForCheckpointLsn = await createCheckpoint(this.client, this.defaultDb, this.checkpointStreamId);
754
- let splitDocument = null;
755
- let flexDbNameWorkaroundLogged = false;
756
- let changesSinceLastCheckpoint = 0;
757
- let lastEmptyResume = performance.now();
758
- while (true) {
759
- if (this.abort_signal.aborted) {
760
- break;
700
+ if (originalChangeDocument == null) {
701
+ // We get a new null document after `maxAwaitTimeMS` if there were no other events.
702
+ // In this case, stream.resumeToken is the resume token associated with the last response.
703
+ // stream.resumeToken is not updated if stream.tryNext() returns data, while stream.next()
704
+ // does update it.
705
+ // From observed behavior, the actual resumeToken changes around once every 10 seconds.
706
+ // If we don't update it on empty events, we do keep consistency, but resuming the stream
707
+ // with old tokens may cause connection timeouts.
708
+ // We throttle this further by only persisting a keepalive once a minute.
709
+ // We add an additional check for waitForCheckpointLsn == null, to make sure we're not
710
+ // doing a keepalive in the middle of a transaction.
711
+ if (waitForCheckpointLsn == null && performance.now() - lastEmptyResume > 60_000) {
712
+ const { comparable: lsn, timestamp } = MongoLSN.fromResumeToken(stream.resumeToken);
713
+ await batch.keepalive(lsn);
714
+ this.touch();
715
+ lastEmptyResume = performance.now();
716
+ // Log the token update. This helps as a general "replication is still active" message in the logs.
717
+ // This token would typically be around 10s behind.
718
+ this.logger.info(`Idle change stream. Persisted resumeToken for ${timestampToDate(timestamp).toISOString()}`);
719
+ this.replicationLag.markStarted();
761
720
  }
762
- const originalChangeDocument = await stream.tryNext().catch((e) => {
763
- throw mapChangeStreamError(e);
764
- });
765
- // The stream was closed, we will only ever receive `null` from it
766
- if (!originalChangeDocument && stream.closed) {
767
- break;
721
+ continue;
722
+ }
723
+ this.touch();
724
+ if (startAfter != null && originalChangeDocument.clusterTime?.lte(startAfter)) {
725
+ continue;
726
+ }
727
+ let changeDocument = originalChangeDocument;
728
+ if (originalChangeDocument?.splitEvent != null) {
729
+ // Handle split events from $changeStreamSplitLargeEvent.
730
+ // This is only relevant for very large update operations.
731
+ const splitEvent = originalChangeDocument?.splitEvent;
732
+ if (splitDocument == null) {
733
+ splitDocument = originalChangeDocument;
768
734
  }
769
- if (this.abort_signal.aborted) {
770
- break;
735
+ else {
736
+ splitDocument = Object.assign(splitDocument, originalChangeDocument);
771
737
  }
772
- if (originalChangeDocument == null) {
773
- // We get a new null document after `maxAwaitTimeMS` if there were no other events.
774
- // In this case, stream.resumeToken is the resume token associated with the last response.
775
- // stream.resumeToken is not updated if stream.tryNext() returns data, while stream.next()
776
- // does update it.
777
- // From observed behavior, the actual resumeToken changes around once every 10 seconds.
778
- // If we don't update it on empty events, we do keep consistency, but resuming the stream
779
- // with old tokens may cause connection timeouts.
780
- // We throttle this further by only persisting a keepalive once a minute.
781
- // We add an additional check for waitForCheckpointLsn == null, to make sure we're not
782
- // doing a keepalive in the middle of a transaction.
783
- if (waitForCheckpointLsn == null && performance.now() - lastEmptyResume > 60_000) {
784
- const { comparable: lsn, timestamp } = MongoLSN.fromResumeToken(stream.resumeToken);
785
- await batch.keepalive(lsn);
786
- this.touch();
787
- lastEmptyResume = performance.now();
788
- // Log the token update. This helps as a general "replication is still active" message in the logs.
789
- // This token would typically be around 10s behind.
790
- this.logger.info(`Idle change stream. Persisted resumeToken for ${timestampToDate(timestamp).toISOString()}`);
791
- this.isStartingReplication = false;
792
- }
738
+ if (splitEvent.fragment == splitEvent.of) {
739
+ // Got all fragments
740
+ changeDocument = splitDocument;
741
+ splitDocument = null;
742
+ }
743
+ else {
744
+ // Wait for more fragments
793
745
  continue;
794
746
  }
795
- this.touch();
796
- if (startAfter != null && originalChangeDocument.clusterTime?.lte(startAfter)) {
747
+ }
748
+ else if (splitDocument != null) {
749
+ // We were waiting for fragments, but got a different event
750
+ throw new ReplicationAssertionError(`Incomplete splitEvent: ${JSON.stringify(splitDocument.splitEvent)}`);
751
+ }
752
+ if (!filters.multipleDatabases &&
753
+ 'ns' in changeDocument &&
754
+ changeDocument.ns.db != this.defaultDb.databaseName &&
755
+ changeDocument.ns.db.endsWith(`_${this.defaultDb.databaseName}`)) {
756
+ // When all of the following conditions are met:
757
+ // 1. We're replicating from an Atlas Flex instance.
758
+ // 2. There were changestream events recorded while the PowerSync service is paused.
759
+ // 3. We're only replicating from a single database.
760
+ // Then we've observed an ns with for example {db: '67b83e86cd20730f1e766dde_ps'},
761
+ // instead of the expected {db: 'ps'}.
762
+ // We correct this.
763
+ changeDocument.ns.db = this.defaultDb.databaseName;
764
+ if (!flexDbNameWorkaroundLogged) {
765
+ flexDbNameWorkaroundLogged = true;
766
+ this.logger.warn(`Incorrect DB name in change stream: ${changeDocument.ns.db}. Changed to ${this.defaultDb.databaseName}.`);
767
+ }
768
+ }
769
+ const ns = 'ns' in changeDocument && 'coll' in changeDocument.ns ? changeDocument.ns : undefined;
770
+ if (ns?.coll == CHECKPOINTS_COLLECTION) {
771
+ /**
772
+ * Dropping the database does not provide an `invalidate` event.
773
+ * We typically would receive `drop` events for the collection which we
774
+ * would process below.
775
+ *
776
+ * However we don't commit the LSN after collections are dropped.
777
+ * The prevents the `startAfter` or `resumeToken` from advancing past the drop events.
778
+ * The stream also closes after the drop events.
779
+ * This causes an infinite loop of processing the collection drop events.
780
+ *
781
+ * This check here invalidates the change stream if our `_checkpoints` collection
782
+ * is dropped. This allows for detecting when the DB is dropped.
783
+ */
784
+ if (changeDocument.operationType == 'drop') {
785
+ throw new ChangeStreamInvalidatedError('Internal collections have been dropped', new Error('_checkpoints collection was dropped'));
786
+ }
787
+ if (!(changeDocument.operationType == 'insert' ||
788
+ changeDocument.operationType == 'update' ||
789
+ changeDocument.operationType == 'replace')) {
797
790
  continue;
798
791
  }
799
- let changeDocument = originalChangeDocument;
800
- if (originalChangeDocument?.splitEvent != null) {
801
- // Handle split events from $changeStreamSplitLargeEvent.
802
- // This is only relevant for very large update operations.
803
- const splitEvent = originalChangeDocument?.splitEvent;
804
- if (splitDocument == null) {
805
- splitDocument = originalChangeDocument;
806
- }
807
- else {
808
- splitDocument = Object.assign(splitDocument, originalChangeDocument);
809
- }
810
- if (splitEvent.fragment == splitEvent.of) {
811
- // Got all fragments
812
- changeDocument = splitDocument;
813
- splitDocument = null;
814
- }
815
- else {
816
- // Wait for more fragments
792
+ // We handle two types of checkpoint events:
793
+ // 1. "Standalone" checkpoints, typically write checkpoints. We want to process these
794
+ // immediately, regardless of where they were created.
795
+ // 2. "Batch" checkpoints for the current stream. This is used as a form of dynamic rate
796
+ // limiting of commits, so we specifically want to exclude checkpoints from other streams.
797
+ //
798
+ // It may be useful to also throttle commits due to standalone checkpoints in the future.
799
+ // However, these typically have a much lower rate than batch checkpoints, so we don't do that for now.
800
+ const checkpointId = changeDocument.documentKey._id;
801
+ if (checkpointId == STANDALONE_CHECKPOINT_ID) {
802
+ // Standalone / write checkpoint received.
803
+ // When we are caught up, commit immediately to keep write checkpoint latency low.
804
+ // Once there is already a batch checkpoint pending, or the driver has buffered more
805
+ // change stream events, collapse standalone checkpoints into the normal batch
806
+ // checkpoint flow to avoid commit churn under sustained load.
807
+ if (waitForCheckpointLsn != null || this.getBufferedChangeCount(stream) > 0) {
808
+ if (waitForCheckpointLsn == null) {
809
+ waitForCheckpointLsn = await createCheckpoint(this.client, this.defaultDb, this.checkpointStreamId);
810
+ }
817
811
  continue;
818
812
  }
819
813
  }
820
- else if (splitDocument != null) {
821
- // We were waiting for fragments, but got a different event
822
- throw new ReplicationAssertionError(`Incomplete splitEvent: ${JSON.stringify(splitDocument.splitEvent)}`);
814
+ else if (!this.checkpointStreamId.equals(checkpointId)) {
815
+ continue;
823
816
  }
824
- if (!filters.multipleDatabases &&
825
- 'ns' in changeDocument &&
826
- changeDocument.ns.db != this.defaultDb.databaseName &&
827
- changeDocument.ns.db.endsWith(`_${this.defaultDb.databaseName}`)) {
828
- // When all of the following conditions are met:
829
- // 1. We're replicating from an Atlas Flex instance.
830
- // 2. There were changestream events recorded while the PowerSync service is paused.
831
- // 3. We're only replicating from a single database.
832
- // Then we've observed an ns with for example {db: '67b83e86cd20730f1e766dde_ps'},
833
- // instead of the expected {db: 'ps'}.
834
- // We correct this.
835
- changeDocument.ns.db = this.defaultDb.databaseName;
836
- if (!flexDbNameWorkaroundLogged) {
837
- flexDbNameWorkaroundLogged = true;
838
- this.logger.warn(`Incorrect DB name in change stream: ${changeDocument.ns.db}. Changed to ${this.defaultDb.databaseName}.`);
839
- }
817
+ const { comparable: lsn } = new MongoLSN({
818
+ timestamp: changeDocument.clusterTime,
819
+ resume_token: changeDocument._id
820
+ });
821
+ if (batch.lastCheckpointLsn != null && lsn < batch.lastCheckpointLsn) {
822
+ // Checkpoint out of order - should never happen with MongoDB.
823
+ // If it does happen, we throw an error to stop the replication - restarting should recover.
824
+ // Since we use batch.lastCheckpointLsn for the next resumeAfter, this should not result in an infinite loop.
825
+ // Originally a workaround for https://jira.mongodb.org/browse/NODE-7042.
826
+ // This has been fixed in the driver in the meantime, but we still keep this as a safety-check.
827
+ throw new ReplicationAssertionError(`Change resumeToken ${changeDocument._id._data} (${timestampToDate(changeDocument.clusterTime).toISOString()}) is less than last checkpoint LSN ${batch.lastCheckpointLsn}. Restarting replication.`);
840
828
  }
841
- const ns = 'ns' in changeDocument && 'coll' in changeDocument.ns ? changeDocument.ns : undefined;
842
- if (ns?.coll == CHECKPOINTS_COLLECTION) {
843
- /**
844
- * Dropping the database does not provide an `invalidate` event.
845
- * We typically would receive `drop` events for the collection which we
846
- * would process below.
847
- *
848
- * However we don't commit the LSN after collections are dropped.
849
- * The prevents the `startAfter` or `resumeToken` from advancing past the drop events.
850
- * The stream also closes after the drop events.
851
- * This causes an infinite loop of processing the collection drop events.
852
- *
853
- * This check here invalidates the change stream if our `_checkpoints` collection
854
- * is dropped. This allows for detecting when the DB is dropped.
855
- */
856
- if (changeDocument.operationType == 'drop') {
857
- throw new ChangeStreamInvalidatedError('Internal collections have been dropped', new Error('_checkpoints collection was dropped'));
858
- }
859
- if (!(changeDocument.operationType == 'insert' ||
860
- changeDocument.operationType == 'update' ||
861
- changeDocument.operationType == 'replace')) {
862
- continue;
863
- }
864
- // We handle two types of checkpoint events:
865
- // 1. "Standalone" checkpoints, typically write checkpoints. We want to process these
866
- // immediately, regardless of where they were created.
867
- // 2. "Batch" checkpoints for the current stream. This is used as a form of dynamic rate
868
- // limiting of commits, so we specifically want to exclude checkpoints from other streams.
869
- //
870
- // It may be useful to also throttle commits due to standalone checkpoints in the future.
871
- // However, these typically have a much lower rate than batch checkpoints, so we don't do that for now.
872
- const checkpointId = changeDocument.documentKey._id;
873
- if (!(checkpointId == STANDALONE_CHECKPOINT_ID || this.checkpointStreamId.equals(checkpointId))) {
874
- continue;
875
- }
876
- const { comparable: lsn } = new MongoLSN({
877
- timestamp: changeDocument.clusterTime,
878
- resume_token: changeDocument._id
879
- });
880
- if (batch.lastCheckpointLsn != null && lsn < batch.lastCheckpointLsn) {
881
- // Checkpoint out of order - should never happen with MongoDB.
882
- // If it does happen, we throw an error to stop the replication - restarting should recover.
883
- // Since we use batch.lastCheckpointLsn for the next resumeAfter, this should not result in an infinite loop.
884
- // Originally a workaround for https://jira.mongodb.org/browse/NODE-7042.
885
- // This has been fixed in the driver in the meantime, but we still keep this as a safety-check.
886
- throw new ReplicationAssertionError(`Change resumeToken ${changeDocument._id._data} (${timestampToDate(changeDocument.clusterTime).toISOString()}) is less than last checkpoint LSN ${batch.lastCheckpointLsn}. Restarting replication.`);
887
- }
888
- if (waitForCheckpointLsn != null && lsn >= waitForCheckpointLsn) {
889
- waitForCheckpointLsn = null;
890
- }
891
- const { checkpointBlocked } = await batch.commit(lsn, {
892
- oldestUncommittedChange: this.oldestUncommittedChange
893
- });
894
- if (!checkpointBlocked) {
895
- this.oldestUncommittedChange = null;
896
- this.isStartingReplication = false;
897
- changesSinceLastCheckpoint = 0;
898
- }
829
+ if (waitForCheckpointLsn != null && lsn >= waitForCheckpointLsn) {
830
+ waitForCheckpointLsn = null;
899
831
  }
900
- else if (changeDocument.operationType == 'insert' ||
901
- changeDocument.operationType == 'update' ||
902
- changeDocument.operationType == 'replace' ||
903
- changeDocument.operationType == 'delete') {
904
- if (waitForCheckpointLsn == null) {
905
- waitForCheckpointLsn = await createCheckpoint(this.client, this.defaultDb, this.checkpointStreamId);
832
+ const { checkpointBlocked } = await batch.commit(lsn, {
833
+ oldestUncommittedChange: this.replicationLag.oldestUncommittedChange
834
+ });
835
+ if (!checkpointBlocked) {
836
+ this.replicationLag.markCommitted();
837
+ changesSinceLastCheckpoint = 0;
838
+ }
839
+ }
840
+ else if (changeDocument.operationType == 'insert' ||
841
+ changeDocument.operationType == 'update' ||
842
+ changeDocument.operationType == 'replace' ||
843
+ changeDocument.operationType == 'delete') {
844
+ if (waitForCheckpointLsn == null) {
845
+ waitForCheckpointLsn = await createCheckpoint(this.client, this.defaultDb, this.checkpointStreamId);
846
+ }
847
+ const rel = getMongoRelation(changeDocument.ns);
848
+ const table = await this.getRelation(batch, rel, {
849
+ // In most cases, we should not need to snapshot this. But if this is the first time we see the collection
850
+ // for whatever reason, then we do need to snapshot it.
851
+ // This may result in some duplicate operations when a collection is created for the first time after
852
+ // sync rules was deployed.
853
+ snapshot: true
854
+ });
855
+ if (table.syncAny) {
856
+ this.replicationLag.trackUncommittedChange(changeDocument.clusterTime == null ? null : timestampToDate(changeDocument.clusterTime));
857
+ const transactionKeyValue = transactionKey(changeDocument);
858
+ if (transactionKeyValue == null || lastTxnKey != transactionKeyValue) {
859
+ // Very crude metric for counting transactions replicated.
860
+ // We ignore operations other than basic CRUD, and ignore changes to _powersync_checkpoints.
861
+ // Individual writes may not have a txnNumber, in which case we count them as separate transactions.
862
+ lastTxnKey = transactionKeyValue;
863
+ transactionsReplicatedMetric.add(1);
906
864
  }
907
- const rel = getMongoRelation(changeDocument.ns);
908
- const table = await this.getRelation(batch, rel, {
909
- // In most cases, we should not need to snapshot this. But if this is the first time we see the collection
910
- // for whatever reason, then we do need to snapshot it.
911
- // This may result in some duplicate operations when a collection is created for the first time after
912
- // sync rules was deployed.
913
- snapshot: true
914
- });
915
- if (table.syncAny) {
916
- if (this.oldestUncommittedChange == null && changeDocument.clusterTime != null) {
917
- this.oldestUncommittedChange = timestampToDate(changeDocument.clusterTime);
918
- }
919
- const flushResult = await this.writeChange(batch, table, changeDocument);
920
- changesSinceLastCheckpoint += 1;
921
- if (flushResult != null && changesSinceLastCheckpoint >= 20_000) {
922
- // When we are catching up replication after an initial snapshot, there may be a very long delay
923
- // before we do a commit(). In that case, we need to periodically persist the resume LSN, so
924
- // we don't restart from scratch if we restart replication.
925
- // The same could apply if we need to catch up on replication after some downtime.
926
- const { comparable: lsn } = new MongoLSN({
927
- timestamp: changeDocument.clusterTime,
928
- resume_token: changeDocument._id
929
- });
930
- this.logger.info(`Updating resume LSN to ${lsn} after ${changesSinceLastCheckpoint} changes`);
931
- await batch.setResumeLsn(lsn);
932
- changesSinceLastCheckpoint = 0;
933
- }
865
+ const flushResult = await this.writeChange(batch, table, changeDocument);
866
+ changesSinceLastCheckpoint += 1;
867
+ if (flushResult != null && changesSinceLastCheckpoint >= 20_000) {
868
+ // When we are catching up replication after an initial snapshot, there may be a very long delay
869
+ // before we do a commit(). In that case, we need to periodically persist the resume LSN, so
870
+ // we don't restart from scratch if we restart replication.
871
+ // The same could apply if we need to catch up on replication after some downtime.
872
+ const { comparable: lsn } = new MongoLSN({
873
+ timestamp: changeDocument.clusterTime,
874
+ resume_token: changeDocument._id
875
+ });
876
+ this.logger.info(`Updating resume LSN to ${lsn} after ${changesSinceLastCheckpoint} changes`);
877
+ await batch.setResumeLsn(lsn);
878
+ changesSinceLastCheckpoint = 0;
934
879
  }
935
880
  }
936
- else if (changeDocument.operationType == 'drop') {
937
- const rel = getMongoRelation(changeDocument.ns);
938
- const table = await this.getRelation(batch, rel, {
939
- // We're "dropping" this collection, so never snapshot it.
940
- snapshot: false
941
- });
942
- if (table.syncAny) {
943
- await batch.drop([table]);
944
- this.relationCache.delete(table);
945
- }
881
+ }
882
+ else if (changeDocument.operationType == 'drop') {
883
+ const rel = getMongoRelation(changeDocument.ns);
884
+ const table = await this.getRelation(batch, rel, {
885
+ // We're "dropping" this collection, so never snapshot it.
886
+ snapshot: false
887
+ });
888
+ if (table.syncAny) {
889
+ await batch.drop([table]);
890
+ this.relationCache.delete(table);
946
891
  }
947
- else if (changeDocument.operationType == 'rename') {
948
- const relFrom = getMongoRelation(changeDocument.ns);
949
- const relTo = getMongoRelation(changeDocument.to);
950
- const tableFrom = await this.getRelation(batch, relFrom, {
951
- // We're "dropping" this collection, so never snapshot it.
952
- snapshot: false
953
- });
954
- if (tableFrom.syncAny) {
955
- await batch.drop([tableFrom]);
956
- this.relationCache.delete(relFrom);
957
- }
958
- // Here we do need to snapshot the new table
959
- const collection = await this.getCollectionInfo(relTo.schema, relTo.name);
960
- await this.handleRelation(batch, relTo, {
961
- // This is a new (renamed) collection, so always snapshot it.
962
- snapshot: true,
963
- collectionInfo: collection
964
- });
892
+ }
893
+ else if (changeDocument.operationType == 'rename') {
894
+ const relFrom = getMongoRelation(changeDocument.ns);
895
+ const relTo = getMongoRelation(changeDocument.to);
896
+ const tableFrom = await this.getRelation(batch, relFrom, {
897
+ // We're "dropping" this collection, so never snapshot it.
898
+ snapshot: false
899
+ });
900
+ if (tableFrom.syncAny) {
901
+ await batch.drop([tableFrom]);
902
+ this.relationCache.delete(relFrom);
965
903
  }
904
+ // Here we do need to snapshot the new table
905
+ const collection = await this.getCollectionInfo(relTo.schema, relTo.name);
906
+ await this.handleRelation(batch, relTo, {
907
+ // This is a new (renamed) collection, so always snapshot it.
908
+ snapshot: true,
909
+ collectionInfo: collection
910
+ });
966
911
  }
967
912
  }
968
- catch (e_4) {
969
- env_4.error = e_4;
970
- env_4.hasError = true;
971
- }
972
- finally {
973
- const result_4 = __disposeResources(env_4);
974
- if (result_4)
975
- await result_4;
976
- }
977
913
  });
978
914
  }
979
- async getReplicationLagMillis() {
980
- if (this.oldestUncommittedChange == null) {
981
- if (this.isStartingReplication) {
982
- // We don't have anything to compute replication lag with yet.
983
- return undefined;
984
- }
985
- else {
986
- // We don't have any uncommitted changes, so replication is up-to-date.
987
- return 0;
988
- }
989
- }
990
- return Date.now() - this.oldestUncommittedChange.getTime();
915
+ getReplicationLagMillis() {
916
+ return this.replicationLag.getLagMillis();
991
917
  }
992
918
  lastTouchedAt = performance.now();
993
919
  touch() {
@@ -1023,4 +949,13 @@ function mapChangeStreamError(e) {
1023
949
  throw new DatabaseConnectionError(ErrorCode.PSYNC_S1346, `Error reading MongoDB ChangeStream`, e);
1024
950
  }
1025
951
  }
952
+ /**
953
+ * Transaction key for a change stream event, used to detect transaction boundaries. Returns null if the event is not part of a transaction.
954
+ */
955
+ function transactionKey(doc) {
956
+ if (doc.txnNumber == null || doc.lsid == null) {
957
+ return null;
958
+ }
959
+ return `${doc.lsid.id.toString('hex')}:${doc.txnNumber}`;
960
+ }
1026
961
  //# sourceMappingURL=ChangeStream.js.map