@powersync/service-module-mongodb 0.22.5 → 0.22.7
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/CHANGELOG.md +21 -0
- package/dist/replication/ChangeStream.d.ts +14 -0
- package/dist/replication/ChangeStream.js +241 -195
- package/dist/replication/ChangeStream.js.map +1 -1
- package/dist/replication/MongoSnapshotter.d.ts +7 -0
- package/dist/replication/MongoSnapshotter.js +65 -37
- package/dist/replication/MongoSnapshotter.js.map +1 -1
- package/package.json +9 -9
- package/src/replication/ChangeStream.ts +278 -211
- package/src/replication/MongoSnapshotter.ts +73 -42
- package/test/src/change_stream_abort.test.ts +5 -1
- package/test/src/offloaded_replication.test.ts +558 -0
- package/test/src/snapshot_progress_interval.test.ts +147 -0
- package/test/src/stream_progress.test.ts +24 -8
- package/test/src/stream_progress_interval.test.ts +311 -0
- package/tsconfig.tsbuildinfo +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# @powersync/service-module-mongodb
|
|
2
2
|
|
|
3
|
+
## 0.22.7
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [9b0fce0]
|
|
8
|
+
- @powersync/service-core@1.29.1
|
|
9
|
+
|
|
10
|
+
## 0.22.6
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- baea889: [MongoDB Storage] Increase replication performance by pipelining replication work.
|
|
15
|
+
- Updated dependencies [de9deec]
|
|
16
|
+
- Updated dependencies [baea889]
|
|
17
|
+
- Updated dependencies [9bebc41]
|
|
18
|
+
- @powersync/service-core@1.29.0
|
|
19
|
+
- @powersync/service-jsonbig@0.18.0
|
|
20
|
+
- @powersync/service-sync-rules@0.45.1
|
|
21
|
+
- @powersync/lib-services-framework@0.10.6
|
|
22
|
+
- @powersync/lib-service-mongodb@0.6.37
|
|
23
|
+
|
|
3
24
|
## 0.22.5
|
|
4
25
|
|
|
5
26
|
### Patch Changes
|
|
@@ -22,6 +22,19 @@ export interface ChangeStreamOptions {
|
|
|
22
22
|
* Override snapshotChunkLength for testing.
|
|
23
23
|
*/
|
|
24
24
|
snapshotChunkLength?: number;
|
|
25
|
+
/**
|
|
26
|
+
* Minimum time between durable snapshot progress updates, checked between pages.
|
|
27
|
+
* Defaults to 10_000ms; 0 persists every page. Final progress is always persisted.
|
|
28
|
+
* Automatic size-based storage flushes are independent of this interval.
|
|
29
|
+
*/
|
|
30
|
+
snapshotProgressIntervalMs?: number;
|
|
31
|
+
/**
|
|
32
|
+
* Minimum time between restart-only resume updates, checked at safe source page boundaries.
|
|
33
|
+
* Defaults to 10_000ms; 0 persists every eligible page. Checkpoint commits remain immediate;
|
|
34
|
+
* published checkpoints count toward this interval. Shutdown persists the last fully consumed safe page.
|
|
35
|
+
* Automatic size-based storage flushes are independent of this interval.
|
|
36
|
+
*/
|
|
37
|
+
streamingProgressIntervalMs?: number;
|
|
25
38
|
/**
|
|
26
39
|
* Override keepalive interval for testing (defaults to 60_000ms).
|
|
27
40
|
*/
|
|
@@ -74,6 +87,7 @@ export declare class ChangeStream {
|
|
|
74
87
|
private readonly queryProvider;
|
|
75
88
|
private readonly hasQueryProviderFactory;
|
|
76
89
|
private keepaliveIntervalMs;
|
|
90
|
+
private readonly streamingProgressIntervalMs;
|
|
77
91
|
private isDocumentDb;
|
|
78
92
|
private _checkpointImplementation;
|
|
79
93
|
/**
|
|
@@ -55,6 +55,7 @@ export class ChangeStream {
|
|
|
55
55
|
queryProvider;
|
|
56
56
|
hasQueryProviderFactory;
|
|
57
57
|
keepaliveIntervalMs;
|
|
58
|
+
streamingProgressIntervalMs;
|
|
58
59
|
isDocumentDb = false;
|
|
59
60
|
_checkpointImplementation = null;
|
|
60
61
|
/**
|
|
@@ -71,6 +72,7 @@ export class ChangeStream {
|
|
|
71
72
|
this.connections = options.connections;
|
|
72
73
|
this.snapshotChunkLength = options.snapshotChunkLength ?? 6_000;
|
|
73
74
|
this.keepaliveIntervalMs = options.keepaliveIntervalMs ?? 60_000;
|
|
75
|
+
this.streamingProgressIntervalMs = options.streamingProgressIntervalMs ?? 10_000;
|
|
74
76
|
if (options.maxAwaitTimeMS) {
|
|
75
77
|
this.maxAwaitTimeMS = options.maxAwaitTimeMS;
|
|
76
78
|
}
|
|
@@ -466,7 +468,8 @@ export class ChangeStream {
|
|
|
466
468
|
// We get a complete postimage for every change, so we don't need to store the current data.
|
|
467
469
|
storeCurrentData: false,
|
|
468
470
|
hooks: this.storageHooks,
|
|
469
|
-
|
|
471
|
+
// Let the source loop stop on cancellation, then drain its last safe progress below.
|
|
472
|
+
// Storage still uses the replication lease signal to cancel work if ownership is lost.
|
|
470
473
|
tracer
|
|
471
474
|
}, async (batch) => {
|
|
472
475
|
const { resumeFromLsn } = batch;
|
|
@@ -483,6 +486,28 @@ export class ChangeStream {
|
|
|
483
486
|
let receivedBytes = 0;
|
|
484
487
|
let changesSinceProgress = 0;
|
|
485
488
|
let filteredSinceProgress = null;
|
|
489
|
+
let lastProgressAt = performance.now();
|
|
490
|
+
let durableResumeLsn = resumeFromLsn;
|
|
491
|
+
let pendingProgress = null;
|
|
492
|
+
const markProgressPersisted = (lsn, timestamp) => {
|
|
493
|
+
durableResumeLsn = lsn;
|
|
494
|
+
lastProgressAt = performance.now();
|
|
495
|
+
// MongoDB's token timestamp may lag by about 10 seconds. DocumentDB tokens have no timestamp.
|
|
496
|
+
this.lastPersistedResumeTimestamp = timestamp?.getTime() ?? Date.now();
|
|
497
|
+
// A persisted position covers every earlier page in source order.
|
|
498
|
+
pendingProgress = null;
|
|
499
|
+
};
|
|
500
|
+
const persistProgress = async () => {
|
|
501
|
+
if (pendingProgress == null) {
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const { lsn, timestamp } = pendingProgress;
|
|
505
|
+
// Row writes must be durable before their source token. This advances recovery without
|
|
506
|
+
// publishing a checkpoint ahead of an outstanding barrier, transaction or snapshot.
|
|
507
|
+
await batch.flush({ oldestUncommittedChange: this.replicationLag.oldestUncommittedChange });
|
|
508
|
+
await batch.setResumeLsn(lsn);
|
|
509
|
+
markProgressPersisted(lsn, timestamp);
|
|
510
|
+
};
|
|
486
511
|
const stream = this.openChangeStream({
|
|
487
512
|
lsn: resumeFromLsn,
|
|
488
513
|
filters,
|
|
@@ -503,221 +528,242 @@ export class ChangeStream {
|
|
|
503
528
|
let waitForCheckpointLsn = await this.createBatchCheckpoint();
|
|
504
529
|
let lastKeepalive = performance.now();
|
|
505
530
|
let lastTxnKey = null;
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
const ns = 'ns' in changeDocument && 'coll' in changeDocument.ns ? changeDocument.ns : undefined;
|
|
515
|
-
if (ns?.coll == CHECKPOINTS_COLLECTION) {
|
|
516
|
-
/**
|
|
517
|
-
* Dropping the database does not provide an `invalidate` event.
|
|
518
|
-
* We typically would receive `drop` events for the collection which we
|
|
519
|
-
* would process below.
|
|
520
|
-
*
|
|
521
|
-
* However we don't commit the LSN after collections are dropped.
|
|
522
|
-
* This prevents the `startAfter` or `resumeToken` from advancing past the drop events.
|
|
523
|
-
* The stream also closes after the drop events.
|
|
524
|
-
* This causes an infinite loop of processing the collection drop events.
|
|
525
|
-
*
|
|
526
|
-
* This check here invalidates the change stream if our `_powersync_checkpoints` collection
|
|
527
|
-
* is dropped. This allows for detecting when the DB is dropped.
|
|
528
|
-
*/
|
|
529
|
-
if (changeDocument.operationType == 'drop') {
|
|
530
|
-
throw new ChangeStreamInvalidatedError('Internal collections have been dropped', new Error('_powersync_checkpoints collection was dropped'));
|
|
531
|
-
}
|
|
532
|
-
if (!(changeDocument.operationType == 'insert' ||
|
|
533
|
-
changeDocument.operationType == 'update' ||
|
|
534
|
-
changeDocument.operationType == 'replace')) {
|
|
535
|
-
continue;
|
|
536
|
-
}
|
|
537
|
-
// We handle two types of checkpoint events:
|
|
538
|
-
// 1. "Standalone" checkpoints, typically write checkpoints. We want to process these
|
|
539
|
-
// immediately, regardless of where they were created.
|
|
540
|
-
// 2. "Batch" checkpoints for the current stream. This is used as a form of dynamic rate
|
|
541
|
-
// limiting of commits, so we specifically want to exclude checkpoints from other streams.
|
|
542
|
-
//
|
|
543
|
-
// It may be useful to also throttle commits due to standalone checkpoints in the future.
|
|
544
|
-
// However, these typically have a much lower rate than batch checkpoints, so we don't do that for now.
|
|
545
|
-
const kind = this.checkpointImplementation.event.observe(changeDocument);
|
|
546
|
-
if (kind == 'foreign') {
|
|
547
|
-
// Another stream's barrier - ignore.
|
|
548
|
-
continue;
|
|
531
|
+
try {
|
|
532
|
+
streamLoop: for await (const sourceBatch of stream) {
|
|
533
|
+
if (this.abortSignal.aborted) {
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
for (const { event: changeDocument, hasBufferedChanges } of sourceBatch.events) {
|
|
537
|
+
if (this.abortSignal.aborted) {
|
|
538
|
+
break streamLoop;
|
|
549
539
|
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
540
|
+
this.touch();
|
|
541
|
+
changesSinceProgress++;
|
|
542
|
+
const ns = 'ns' in changeDocument && 'coll' in changeDocument.ns ? changeDocument.ns : undefined;
|
|
543
|
+
if (ns?.coll == CHECKPOINTS_COLLECTION) {
|
|
544
|
+
/**
|
|
545
|
+
* Dropping the database does not provide an `invalidate` event.
|
|
546
|
+
* We typically would receive `drop` events for the collection which we
|
|
547
|
+
* would process below.
|
|
548
|
+
*
|
|
549
|
+
* However we don't commit the LSN after collections are dropped.
|
|
550
|
+
* This prevents the `startAfter` or `resumeToken` from advancing past the drop events.
|
|
551
|
+
* The stream also closes after the drop events.
|
|
552
|
+
* This causes an infinite loop of processing the collection drop events.
|
|
553
|
+
*
|
|
554
|
+
* This check here invalidates the change stream if our `_powersync_checkpoints` collection
|
|
555
|
+
* is dropped. This allows for detecting when the DB is dropped.
|
|
556
|
+
*/
|
|
557
|
+
if (changeDocument.operationType == 'drop') {
|
|
558
|
+
throw new ChangeStreamInvalidatedError('Internal collections have been dropped', new Error('_powersync_checkpoints collection was dropped'));
|
|
559
|
+
}
|
|
560
|
+
if (!(changeDocument.operationType == 'insert' ||
|
|
561
|
+
changeDocument.operationType == 'update' ||
|
|
562
|
+
changeDocument.operationType == 'replace')) {
|
|
560
563
|
continue;
|
|
561
564
|
}
|
|
562
|
-
|
|
563
|
-
|
|
565
|
+
// We handle two types of checkpoint events:
|
|
566
|
+
// 1. "Standalone" checkpoints, typically write checkpoints. We want to process these
|
|
567
|
+
// immediately, regardless of where they were created.
|
|
568
|
+
// 2. "Batch" checkpoints for the current stream. This is used as a form of dynamic rate
|
|
569
|
+
// limiting of commits, so we specifically want to exclude checkpoints from other streams.
|
|
570
|
+
//
|
|
571
|
+
// It may be useful to also throttle commits due to standalone checkpoints in the future.
|
|
572
|
+
// However, these typically have a much lower rate than batch checkpoints, so we don't do that for now.
|
|
573
|
+
const kind = this.checkpointImplementation.event.observe(changeDocument);
|
|
574
|
+
if (kind == 'foreign') {
|
|
575
|
+
// Another stream's barrier - ignore.
|
|
564
576
|
continue;
|
|
565
577
|
}
|
|
566
|
-
else {
|
|
567
|
-
//
|
|
578
|
+
else if (kind == 'standalone') {
|
|
579
|
+
// Standalone / write checkpoint received.
|
|
580
|
+
// When we are caught up, commit immediately to keep write checkpoint latency low.
|
|
581
|
+
// Once there is already a batch checkpoint pending, or the driver has buffered more
|
|
582
|
+
// change stream events, collapse standalone checkpoints into the normal batch
|
|
583
|
+
// checkpoint flow to avoid commit churn under sustained load.
|
|
584
|
+
if (hasBufferedChanges && waitForCheckpointLsn == null) {
|
|
585
|
+
// Buffered changes - create a new batch checkpoint to rate limit commits
|
|
586
|
+
using _ = tracer.span('source_checkpoint');
|
|
587
|
+
waitForCheckpointLsn = await this.createBatchCheckpoint();
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
else if (waitForCheckpointLsn != null) {
|
|
591
|
+
// Skip this checkpoint - wait for the batch checkpoint.
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
else {
|
|
595
|
+
// No buffered changes, and no batch checkpoint pending - commit immediately.
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
// kind == 'own-barrier' falls through to commit.
|
|
599
|
+
const lsn = this.checkpointImplementation.event.lsn(changeDocument);
|
|
600
|
+
if (waitForCheckpointLsn != null &&
|
|
601
|
+
this.checkpointImplementation.event.resolvesBarrier(waitForCheckpointLsn, changeDocument)) {
|
|
602
|
+
waitForCheckpointLsn = null;
|
|
603
|
+
}
|
|
604
|
+
const { checkpointBlocked, checkpointCreated } = await batch.commit(lsn, {
|
|
605
|
+
oldestUncommittedChange: this.replicationLag.oldestUncommittedChange
|
|
606
|
+
});
|
|
607
|
+
if (checkpointCreated) {
|
|
608
|
+
// Only a published checkpoint guarantees persisted progress across all storage versions.
|
|
609
|
+
// In particular, blocked commits in storage v1/v2 do not advance the resume position.
|
|
610
|
+
markProgressPersisted(lsn, this.checkpointImplementation.lsnFromResumeToken(changeDocument._id).timestamp);
|
|
611
|
+
}
|
|
612
|
+
if (!checkpointBlocked || checkpointCreated) {
|
|
613
|
+
this.replicationLag.markCommitted();
|
|
568
614
|
}
|
|
569
615
|
}
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
waitForCheckpointLsn
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
616
|
+
else if (changeDocument.operationType == 'insert' ||
|
|
617
|
+
changeDocument.operationType == 'update' ||
|
|
618
|
+
changeDocument.operationType == 'replace' ||
|
|
619
|
+
changeDocument.operationType == 'delete') {
|
|
620
|
+
if (waitForCheckpointLsn == null) {
|
|
621
|
+
using _ = tracer.span('source_checkpoint');
|
|
622
|
+
waitForCheckpointLsn = await this.createBatchCheckpoint();
|
|
623
|
+
}
|
|
624
|
+
const rel = getMongoRelation(changeDocument.ns, this.connections.connectionTag);
|
|
625
|
+
const tables = await this.getRelations(batch, rel, {
|
|
626
|
+
// In most cases, we should not need to snapshot this. But if this is the first time we see the collection
|
|
627
|
+
// for whatever reason, then we do need to snapshot it.
|
|
628
|
+
// This may result in some duplicate operations when a collection is created for the first time after
|
|
629
|
+
// sync config was deployed.
|
|
630
|
+
snapshot: true
|
|
631
|
+
});
|
|
632
|
+
const tablesToReplicate = tables.filter((table) => table.syncAny);
|
|
633
|
+
if (tablesToReplicate.length > 0) {
|
|
634
|
+
this.replicationLag.trackUncommittedChange(
|
|
635
|
+
// Standard MongoDB uses clusterTime, unchanged. DocumentDB has no
|
|
636
|
+
// clusterTime, so fall back to wallTime there for the lag metric.
|
|
637
|
+
changeDocument.clusterTime != null
|
|
638
|
+
? timestampToDate(changeDocument.clusterTime)
|
|
639
|
+
: (changeDocument.wallTime ?? null));
|
|
640
|
+
const transactionKeyValue = transactionKey(changeDocument);
|
|
641
|
+
if (transactionKeyValue == null || lastTxnKey != transactionKeyValue) {
|
|
642
|
+
// Very crude metric for counting transactions replicated.
|
|
643
|
+
// We ignore operations other than basic CRUD, and ignore changes to _powersync_checkpoints.
|
|
644
|
+
// Individual writes may not have a txnNumber, in which case we count them as separate transactions.
|
|
645
|
+
lastTxnKey = transactionKeyValue;
|
|
646
|
+
transactionsReplicatedMetric.add(1);
|
|
647
|
+
}
|
|
648
|
+
for (const table of tablesToReplicate) {
|
|
649
|
+
await this.writeChange(batch, table, changeDocument);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
590
652
|
}
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
if (tablesToReplicate.length > 0) {
|
|
601
|
-
this.replicationLag.trackUncommittedChange(
|
|
602
|
-
// Standard MongoDB uses clusterTime, unchanged. DocumentDB has no
|
|
603
|
-
// clusterTime, so fall back to wallTime there for the lag metric.
|
|
604
|
-
changeDocument.clusterTime != null
|
|
605
|
-
? timestampToDate(changeDocument.clusterTime)
|
|
606
|
-
: (changeDocument.wallTime ?? null));
|
|
607
|
-
const transactionKeyValue = transactionKey(changeDocument);
|
|
608
|
-
if (transactionKeyValue == null || lastTxnKey != transactionKeyValue) {
|
|
609
|
-
// Very crude metric for counting transactions replicated.
|
|
610
|
-
// We ignore operations other than basic CRUD, and ignore changes to _powersync_checkpoints.
|
|
611
|
-
// Individual writes may not have a txnNumber, in which case we count them as separate transactions.
|
|
612
|
-
lastTxnKey = transactionKeyValue;
|
|
613
|
-
transactionsReplicatedMetric.add(1);
|
|
653
|
+
else if (changeDocument.operationType == 'drop') {
|
|
654
|
+
const rel = getMongoRelation(changeDocument.ns, this.connections.connectionTag);
|
|
655
|
+
const tables = await this.getRelations(batch, rel, {
|
|
656
|
+
// We're "dropping" this collection, so never snapshot it.
|
|
657
|
+
snapshot: false
|
|
658
|
+
});
|
|
659
|
+
const tablesToDrop = tables.filter((table) => table.syncAny);
|
|
660
|
+
if (tablesToDrop.length > 0) {
|
|
661
|
+
await batch.drop(tablesToDrop);
|
|
614
662
|
}
|
|
615
|
-
|
|
616
|
-
|
|
663
|
+
this.relationCache.delete(rel);
|
|
664
|
+
}
|
|
665
|
+
else if (changeDocument.operationType == 'rename') {
|
|
666
|
+
const relFrom = getMongoRelation(changeDocument.ns, this.connections.connectionTag);
|
|
667
|
+
const relTo = getMongoRelation(changeDocument.to, this.connections.connectionTag);
|
|
668
|
+
const tablesFrom = await this.getRelations(batch, relFrom, {
|
|
669
|
+
// We're "dropping" this collection, so never snapshot it.
|
|
670
|
+
snapshot: false
|
|
671
|
+
});
|
|
672
|
+
const tablesToDrop = tablesFrom.filter((table) => table.syncAny);
|
|
673
|
+
if (tablesToDrop.length > 0) {
|
|
674
|
+
await batch.drop(tablesToDrop);
|
|
617
675
|
}
|
|
676
|
+
this.relationCache.delete(relFrom);
|
|
677
|
+
// Here we do need to snapshot the new table
|
|
678
|
+
const collection = await this.getCollectionInfo(relTo.schema, relTo.name);
|
|
679
|
+
await this.handleRelation(batch, relTo, {
|
|
680
|
+
// This is a new (renamed) collection, so always snapshot it.
|
|
681
|
+
snapshot: true,
|
|
682
|
+
collectionInfo: collection
|
|
683
|
+
});
|
|
618
684
|
}
|
|
619
685
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
const tables = await this.getRelations(batch, rel, {
|
|
623
|
-
// We're "dropping" this collection, so never snapshot it.
|
|
624
|
-
snapshot: false
|
|
625
|
-
});
|
|
626
|
-
const tablesToDrop = tables.filter((table) => table.syncAny);
|
|
627
|
-
if (tablesToDrop.length > 0) {
|
|
628
|
-
await batch.drop(tablesToDrop);
|
|
629
|
-
}
|
|
630
|
-
this.relationCache.delete(rel);
|
|
686
|
+
if (this.abortSignal.aborted) {
|
|
687
|
+
break;
|
|
631
688
|
}
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
// We're "dropping" this collection, so never snapshot it.
|
|
637
|
-
snapshot: false
|
|
638
|
-
});
|
|
639
|
-
const tablesToDrop = tablesFrom.filter((table) => table.syncAny);
|
|
640
|
-
if (tablesToDrop.length > 0) {
|
|
641
|
-
await batch.drop(tablesToDrop);
|
|
642
|
-
}
|
|
643
|
-
this.relationCache.delete(relFrom);
|
|
644
|
-
// Here we do need to snapshot the new table
|
|
645
|
-
const collection = await this.getCollectionInfo(relTo.schema, relTo.name);
|
|
646
|
-
await this.handleRelation(batch, relTo, {
|
|
647
|
-
// This is a new (renamed) collection, so always snapshot it.
|
|
648
|
-
snapshot: true,
|
|
649
|
-
collectionInfo: collection
|
|
650
|
-
});
|
|
689
|
+
this.touch();
|
|
690
|
+
const batchFilteredCount = sourceBatch.metadata.filteredCount;
|
|
691
|
+
if (batchFilteredCount != null) {
|
|
692
|
+
filteredSinceProgress = (filteredSinceProgress ?? 0) + batchFilteredCount;
|
|
651
693
|
}
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
694
|
+
const resumeToken = sourceBatch.getResumeToken();
|
|
695
|
+
if (resumeToken != null) {
|
|
696
|
+
const filteredCount = filteredSinceProgress;
|
|
697
|
+
if (changesSinceProgress == 0) {
|
|
698
|
+
// No retained changes since the previous progress boundary: this is either idle or filtered-only traffic.
|
|
699
|
+
// Case 1: No pending barrier and the keepalive interval has elapsed. Advance checkpoints as below,
|
|
700
|
+
// then make the resume token eligible for persistence.
|
|
701
|
+
// Case 2: Idle traffic with a recent keepalive. Skip this resume update, whether or not a barrier
|
|
702
|
+
// is pending, to preserve the idle throttle.
|
|
703
|
+
// Case 3: All other combinations. Make the token eligible without requesting a checkpoint.
|
|
704
|
+
// A pending barrier will provide the checkpoint boundary once replication reaches it. Filtered
|
|
705
|
+
// progress remains eligible during the keepalive interval, so excluded work is resumable.
|
|
706
|
+
const hadRecentKeepalive = performance.now() - lastKeepalive < this.keepaliveIntervalMs;
|
|
707
|
+
if (waitForCheckpointLsn == null && !hadRecentKeepalive) {
|
|
708
|
+
if ((filteredCount ?? 0) > 0) {
|
|
709
|
+
// Case 1a: A transaction can span batches: this batch may contain only filtered changes,
|
|
710
|
+
// while retained changes from the same transaction are still unread. They share a timestamp,
|
|
711
|
+
// so publishing a checkpoint here could acknowledge the transaction before its data is saved.
|
|
712
|
+
// Request a source barrier; reaching it ensures those retained changes have been processed.
|
|
713
|
+
// The progress token can still be saved below for recovery without publishing a checkpoint.
|
|
714
|
+
using _ = tracer.span('source_checkpoint');
|
|
715
|
+
waitForCheckpointLsn = await this.createBatchCheckpoint();
|
|
716
|
+
}
|
|
717
|
+
else {
|
|
718
|
+
// Case 1b: Idle traffic. The timestamp implementation persists a keepalive directly;
|
|
719
|
+
// the sentinel implementation writes a source marker whose event will commit later.
|
|
720
|
+
await this.checkpointImplementation.keepalive(batch, resumeToken);
|
|
721
|
+
this.replicationLag.markStarted();
|
|
722
|
+
}
|
|
723
|
+
this.touch();
|
|
724
|
+
lastKeepalive = performance.now();
|
|
682
725
|
}
|
|
683
|
-
else {
|
|
684
|
-
// Case
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
726
|
+
else if ((filteredCount ?? 0) == 0 && hadRecentKeepalive) {
|
|
727
|
+
// Case 2: Don't refresh idle tokens, but finish any earlier active progress when due.
|
|
728
|
+
if (performance.now() - lastProgressAt >= this.streamingProgressIntervalMs) {
|
|
729
|
+
await persistProgress();
|
|
730
|
+
}
|
|
731
|
+
continue;
|
|
688
732
|
}
|
|
689
|
-
this.touch();
|
|
690
|
-
lastKeepalive = performance.now();
|
|
691
733
|
}
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
734
|
+
const progress = this.checkpointImplementation.lsnFromResumeToken(resumeToken);
|
|
735
|
+
// Only exact equality proves a token is already covered: transaction events can share a
|
|
736
|
+
// timestamp, and sentinel tokens are opaque. Never deduplicate by timestamp or token order.
|
|
737
|
+
pendingProgress = progress.lsn == durableResumeLsn ? null : progress;
|
|
738
|
+
if (performance.now() - lastProgressAt >= this.streamingProgressIntervalMs) {
|
|
739
|
+
await persistProgress();
|
|
695
740
|
}
|
|
741
|
+
processingSpan?.end();
|
|
742
|
+
const durationsMicroseconds = outerSpan.end();
|
|
743
|
+
const filteringDescription = filteredCount == null ? '' : ` and ${filteredCount} filtered events`;
|
|
744
|
+
this.logger.info(`Processed ${changesSinceProgress} changes${filteringDescription}`, {
|
|
745
|
+
count: changesSinceProgress,
|
|
746
|
+
...(filteredCount == null ? {} : { filteredCount }),
|
|
747
|
+
bytes: receivedBytes,
|
|
748
|
+
duration: processingSpan?.durationMillis,
|
|
749
|
+
t: durationsMicroseconds
|
|
750
|
+
});
|
|
751
|
+
changesSinceProgress = 0;
|
|
752
|
+
filteredSinceProgress = null;
|
|
753
|
+
receivedBytes = 0;
|
|
754
|
+
outerSpan = tracer.span('batch');
|
|
755
|
+
continue;
|
|
696
756
|
}
|
|
697
|
-
const { lsn, timestamp } = this.checkpointImplementation.lsnFromResumeToken(resumeToken);
|
|
698
|
-
// Row writes must be durable before their source token. This advances recovery without
|
|
699
|
-
// publishing a checkpoint ahead of an outstanding barrier, transaction or snapshot.
|
|
700
|
-
await batch.flush({ oldestUncommittedChange: this.replicationLag.oldestUncommittedChange });
|
|
701
|
-
await batch.setResumeLsn(lsn);
|
|
702
|
-
// MongoDB's token timestamp may lag by about 10 seconds. DocumentDB tokens have no timestamp.
|
|
703
|
-
this.lastPersistedResumeTimestamp = timestamp?.getTime() ?? Date.now();
|
|
704
|
-
processingSpan?.end();
|
|
705
|
-
const durationsMicroseconds = outerSpan.end();
|
|
706
|
-
const filteringDescription = filteredCount == null ? '' : ` and ${filteredCount} filtered events`;
|
|
707
|
-
this.logger.info(`Processed ${changesSinceProgress} changes${filteringDescription}`, {
|
|
708
|
-
count: changesSinceProgress,
|
|
709
|
-
...(filteredCount == null ? {} : { filteredCount }),
|
|
710
|
-
bytes: receivedBytes,
|
|
711
|
-
duration: processingSpan?.durationMillis,
|
|
712
|
-
t: durationsMicroseconds
|
|
713
|
-
});
|
|
714
|
-
changesSinceProgress = 0;
|
|
715
|
-
filteredSinceProgress = null;
|
|
716
|
-
receivedBytes = 0;
|
|
717
|
-
outerSpan = tracer.span('batch');
|
|
718
|
-
continue;
|
|
719
757
|
}
|
|
720
758
|
}
|
|
759
|
+
catch (error) {
|
|
760
|
+
// Cursor cancellation can throw instead of ending iteration. Flush only the previously
|
|
761
|
+
// completed safe page; processing/adapter/storage failures must leave progress for replay.
|
|
762
|
+
if (!this.abortSignal.aborted || error !== this.abortSignal.reason) {
|
|
763
|
+
throw error;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
await persistProgress();
|
|
721
767
|
});
|
|
722
768
|
throw new ReplicationAbortedError(`Replication stream aborted`, this.abortSignal.reason);
|
|
723
769
|
}
|