@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
|
@@ -56,6 +56,21 @@ export interface ChangeStreamOptions {
|
|
|
56
56
|
*/
|
|
57
57
|
snapshotChunkLength?: number;
|
|
58
58
|
|
|
59
|
+
/**
|
|
60
|
+
* Minimum time between durable snapshot progress updates, checked between pages.
|
|
61
|
+
* Defaults to 10_000ms; 0 persists every page. Final progress is always persisted.
|
|
62
|
+
* Automatic size-based storage flushes are independent of this interval.
|
|
63
|
+
*/
|
|
64
|
+
snapshotProgressIntervalMs?: number;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Minimum time between restart-only resume updates, checked at safe source page boundaries.
|
|
68
|
+
* Defaults to 10_000ms; 0 persists every eligible page. Checkpoint commits remain immediate;
|
|
69
|
+
* published checkpoints count toward this interval. Shutdown persists the last fully consumed safe page.
|
|
70
|
+
* Automatic size-based storage flushes are independent of this interval.
|
|
71
|
+
*/
|
|
72
|
+
streamingProgressIntervalMs?: number;
|
|
73
|
+
|
|
59
74
|
/**
|
|
60
75
|
* Override keepalive interval for testing (defaults to 60_000ms).
|
|
61
76
|
*/
|
|
@@ -128,6 +143,7 @@ export class ChangeStream {
|
|
|
128
143
|
private readonly hasQueryProviderFactory: boolean;
|
|
129
144
|
|
|
130
145
|
private keepaliveIntervalMs: number;
|
|
146
|
+
private readonly streamingProgressIntervalMs: number;
|
|
131
147
|
|
|
132
148
|
private isDocumentDb = false;
|
|
133
149
|
private _checkpointImplementation: CheckpointImplementation | null = null;
|
|
@@ -145,6 +161,7 @@ export class ChangeStream {
|
|
|
145
161
|
this.connections = options.connections;
|
|
146
162
|
this.snapshotChunkLength = options.snapshotChunkLength ?? 6_000;
|
|
147
163
|
this.keepaliveIntervalMs = options.keepaliveIntervalMs ?? 60_000;
|
|
164
|
+
this.streamingProgressIntervalMs = options.streamingProgressIntervalMs ?? 10_000;
|
|
148
165
|
if (options.maxAwaitTimeMS) {
|
|
149
166
|
this.maxAwaitTimeMS = options.maxAwaitTimeMS;
|
|
150
167
|
} else {
|
|
@@ -613,7 +630,8 @@ export class ChangeStream {
|
|
|
613
630
|
// We get a complete postimage for every change, so we don't need to store the current data.
|
|
614
631
|
storeCurrentData: false,
|
|
615
632
|
hooks: this.storageHooks,
|
|
616
|
-
|
|
633
|
+
// Let the source loop stop on cancellation, then drain its last safe progress below.
|
|
634
|
+
// Storage still uses the replication lease signal to cancel work if ownership is lost.
|
|
617
635
|
tracer
|
|
618
636
|
},
|
|
619
637
|
async (batch) => {
|
|
@@ -633,6 +651,28 @@ export class ChangeStream {
|
|
|
633
651
|
let receivedBytes = 0;
|
|
634
652
|
let changesSinceProgress = 0;
|
|
635
653
|
let filteredSinceProgress: number | null = null;
|
|
654
|
+
let lastProgressAt = performance.now();
|
|
655
|
+
let durableResumeLsn = resumeFromLsn;
|
|
656
|
+
let pendingProgress: { lsn: string; timestamp: Date | null } | null = null;
|
|
657
|
+
const markProgressPersisted = (lsn: string, timestamp: Date | null) => {
|
|
658
|
+
durableResumeLsn = lsn;
|
|
659
|
+
lastProgressAt = performance.now();
|
|
660
|
+
// MongoDB's token timestamp may lag by about 10 seconds. DocumentDB tokens have no timestamp.
|
|
661
|
+
this.lastPersistedResumeTimestamp = timestamp?.getTime() ?? Date.now();
|
|
662
|
+
// A persisted position covers every earlier page in source order.
|
|
663
|
+
pendingProgress = null;
|
|
664
|
+
};
|
|
665
|
+
const persistProgress = async () => {
|
|
666
|
+
if (pendingProgress == null) {
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
const { lsn, timestamp } = pendingProgress;
|
|
670
|
+
// Row writes must be durable before their source token. This advances recovery without
|
|
671
|
+
// publishing a checkpoint ahead of an outstanding barrier, transaction or snapshot.
|
|
672
|
+
await batch.flush({ oldestUncommittedChange: this.replicationLag.oldestUncommittedChange });
|
|
673
|
+
await batch.setResumeLsn(lsn);
|
|
674
|
+
markProgressPersisted(lsn, timestamp);
|
|
675
|
+
};
|
|
636
676
|
const stream = this.openChangeStream({
|
|
637
677
|
lsn: resumeFromLsn,
|
|
638
678
|
filters,
|
|
@@ -656,235 +696,262 @@ export class ChangeStream {
|
|
|
656
696
|
let lastKeepalive = performance.now();
|
|
657
697
|
let lastTxnKey: string | null = null;
|
|
658
698
|
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
if (ns?.coll == CHECKPOINTS_COLLECTION) {
|
|
668
|
-
/**
|
|
669
|
-
* Dropping the database does not provide an `invalidate` event.
|
|
670
|
-
* We typically would receive `drop` events for the collection which we
|
|
671
|
-
* would process below.
|
|
672
|
-
*
|
|
673
|
-
* However we don't commit the LSN after collections are dropped.
|
|
674
|
-
* This prevents the `startAfter` or `resumeToken` from advancing past the drop events.
|
|
675
|
-
* The stream also closes after the drop events.
|
|
676
|
-
* This causes an infinite loop of processing the collection drop events.
|
|
677
|
-
*
|
|
678
|
-
* This check here invalidates the change stream if our `_powersync_checkpoints` collection
|
|
679
|
-
* is dropped. This allows for detecting when the DB is dropped.
|
|
680
|
-
*/
|
|
681
|
-
if (changeDocument.operationType == 'drop') {
|
|
682
|
-
throw new ChangeStreamInvalidatedError(
|
|
683
|
-
'Internal collections have been dropped',
|
|
684
|
-
new Error('_powersync_checkpoints collection was dropped')
|
|
685
|
-
);
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
if (
|
|
689
|
-
!(
|
|
690
|
-
changeDocument.operationType == 'insert' ||
|
|
691
|
-
changeDocument.operationType == 'update' ||
|
|
692
|
-
changeDocument.operationType == 'replace'
|
|
693
|
-
)
|
|
694
|
-
) {
|
|
695
|
-
continue;
|
|
699
|
+
try {
|
|
700
|
+
streamLoop: for await (const sourceBatch of stream) {
|
|
701
|
+
if (this.abortSignal.aborted) {
|
|
702
|
+
break;
|
|
703
|
+
}
|
|
704
|
+
for (const { event: changeDocument, hasBufferedChanges } of sourceBatch.events) {
|
|
705
|
+
if (this.abortSignal.aborted) {
|
|
706
|
+
break streamLoop;
|
|
696
707
|
}
|
|
708
|
+
this.touch();
|
|
709
|
+
changesSinceProgress++;
|
|
710
|
+
const ns = 'ns' in changeDocument && 'coll' in changeDocument.ns ? changeDocument.ns : undefined;
|
|
711
|
+
|
|
712
|
+
if (ns?.coll == CHECKPOINTS_COLLECTION) {
|
|
713
|
+
/**
|
|
714
|
+
* Dropping the database does not provide an `invalidate` event.
|
|
715
|
+
* We typically would receive `drop` events for the collection which we
|
|
716
|
+
* would process below.
|
|
717
|
+
*
|
|
718
|
+
* However we don't commit the LSN after collections are dropped.
|
|
719
|
+
* This prevents the `startAfter` or `resumeToken` from advancing past the drop events.
|
|
720
|
+
* The stream also closes after the drop events.
|
|
721
|
+
* This causes an infinite loop of processing the collection drop events.
|
|
722
|
+
*
|
|
723
|
+
* This check here invalidates the change stream if our `_powersync_checkpoints` collection
|
|
724
|
+
* is dropped. This allows for detecting when the DB is dropped.
|
|
725
|
+
*/
|
|
726
|
+
if (changeDocument.operationType == 'drop') {
|
|
727
|
+
throw new ChangeStreamInvalidatedError(
|
|
728
|
+
'Internal collections have been dropped',
|
|
729
|
+
new Error('_powersync_checkpoints collection was dropped')
|
|
730
|
+
);
|
|
731
|
+
}
|
|
697
732
|
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
// However, these typically have a much lower rate than batch checkpoints, so we don't do that for now.
|
|
706
|
-
|
|
707
|
-
const kind = this.checkpointImplementation.event.observe(changeDocument);
|
|
708
|
-
|
|
709
|
-
if (kind == 'foreign') {
|
|
710
|
-
// Another stream's barrier - ignore.
|
|
711
|
-
continue;
|
|
712
|
-
} else if (kind == 'standalone') {
|
|
713
|
-
// Standalone / write checkpoint received.
|
|
714
|
-
// When we are caught up, commit immediately to keep write checkpoint latency low.
|
|
715
|
-
// Once there is already a batch checkpoint pending, or the driver has buffered more
|
|
716
|
-
// change stream events, collapse standalone checkpoints into the normal batch
|
|
717
|
-
// checkpoint flow to avoid commit churn under sustained load.
|
|
718
|
-
if (hasBufferedChanges && waitForCheckpointLsn == null) {
|
|
719
|
-
// Buffered changes - create a new batch checkpoint to rate limit commits
|
|
720
|
-
using _ = tracer.span('source_checkpoint');
|
|
721
|
-
waitForCheckpointLsn = await this.createBatchCheckpoint();
|
|
733
|
+
if (
|
|
734
|
+
!(
|
|
735
|
+
changeDocument.operationType == 'insert' ||
|
|
736
|
+
changeDocument.operationType == 'update' ||
|
|
737
|
+
changeDocument.operationType == 'replace'
|
|
738
|
+
)
|
|
739
|
+
) {
|
|
722
740
|
continue;
|
|
723
|
-
} else if (waitForCheckpointLsn != null) {
|
|
724
|
-
// Skip this checkpoint - wait for the batch checkpoint.
|
|
725
|
-
continue;
|
|
726
|
-
} else {
|
|
727
|
-
// No buffered changes, and no batch checkpoint pending - commit immediately.
|
|
728
741
|
}
|
|
729
|
-
}
|
|
730
|
-
// kind == 'own-barrier' falls through to commit.
|
|
731
742
|
|
|
732
|
-
|
|
743
|
+
// We handle two types of checkpoint events:
|
|
744
|
+
// 1. "Standalone" checkpoints, typically write checkpoints. We want to process these
|
|
745
|
+
// immediately, regardless of where they were created.
|
|
746
|
+
// 2. "Batch" checkpoints for the current stream. This is used as a form of dynamic rate
|
|
747
|
+
// limiting of commits, so we specifically want to exclude checkpoints from other streams.
|
|
748
|
+
//
|
|
749
|
+
// It may be useful to also throttle commits due to standalone checkpoints in the future.
|
|
750
|
+
// However, these typically have a much lower rate than batch checkpoints, so we don't do that for now.
|
|
733
751
|
|
|
734
|
-
|
|
735
|
-
waitForCheckpointLsn != null &&
|
|
736
|
-
this.checkpointImplementation.event.resolvesBarrier(waitForCheckpointLsn, changeDocument)
|
|
737
|
-
) {
|
|
738
|
-
waitForCheckpointLsn = null;
|
|
739
|
-
}
|
|
740
|
-
const { checkpointBlocked, checkpointCreated } = await batch.commit(lsn, {
|
|
741
|
-
oldestUncommittedChange: this.replicationLag.oldestUncommittedChange
|
|
742
|
-
});
|
|
752
|
+
const kind = this.checkpointImplementation.event.observe(changeDocument);
|
|
743
753
|
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
754
|
+
if (kind == 'foreign') {
|
|
755
|
+
// Another stream's barrier - ignore.
|
|
756
|
+
continue;
|
|
757
|
+
} else if (kind == 'standalone') {
|
|
758
|
+
// Standalone / write checkpoint received.
|
|
759
|
+
// When we are caught up, commit immediately to keep write checkpoint latency low.
|
|
760
|
+
// Once there is already a batch checkpoint pending, or the driver has buffered more
|
|
761
|
+
// change stream events, collapse standalone checkpoints into the normal batch
|
|
762
|
+
// checkpoint flow to avoid commit churn under sustained load.
|
|
763
|
+
if (hasBufferedChanges && waitForCheckpointLsn == null) {
|
|
764
|
+
// Buffered changes - create a new batch checkpoint to rate limit commits
|
|
765
|
+
using _ = tracer.span('source_checkpoint');
|
|
766
|
+
waitForCheckpointLsn = await this.createBatchCheckpoint();
|
|
767
|
+
continue;
|
|
768
|
+
} else if (waitForCheckpointLsn != null) {
|
|
769
|
+
// Skip this checkpoint - wait for the batch checkpoint.
|
|
770
|
+
continue;
|
|
771
|
+
} else {
|
|
772
|
+
// No buffered changes, and no batch checkpoint pending - commit immediately.
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
// kind == 'own-barrier' falls through to commit.
|
|
757
776
|
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
if (transactionKeyValue == null || lastTxnKey != transactionKeyValue) {
|
|
779
|
-
// Very crude metric for counting transactions replicated.
|
|
780
|
-
// We ignore operations other than basic CRUD, and ignore changes to _powersync_checkpoints.
|
|
781
|
-
// Individual writes may not have a txnNumber, in which case we count them as separate transactions.
|
|
782
|
-
lastTxnKey = transactionKeyValue;
|
|
783
|
-
transactionsReplicatedMetric.add(1);
|
|
777
|
+
const lsn = this.checkpointImplementation.event.lsn(changeDocument);
|
|
778
|
+
|
|
779
|
+
if (
|
|
780
|
+
waitForCheckpointLsn != null &&
|
|
781
|
+
this.checkpointImplementation.event.resolvesBarrier(waitForCheckpointLsn, changeDocument)
|
|
782
|
+
) {
|
|
783
|
+
waitForCheckpointLsn = null;
|
|
784
|
+
}
|
|
785
|
+
const { checkpointBlocked, checkpointCreated } = await batch.commit(lsn, {
|
|
786
|
+
oldestUncommittedChange: this.replicationLag.oldestUncommittedChange
|
|
787
|
+
});
|
|
788
|
+
|
|
789
|
+
if (checkpointCreated) {
|
|
790
|
+
// Only a published checkpoint guarantees persisted progress across all storage versions.
|
|
791
|
+
// In particular, blocked commits in storage v1/v2 do not advance the resume position.
|
|
792
|
+
markProgressPersisted(
|
|
793
|
+
lsn,
|
|
794
|
+
this.checkpointImplementation.lsnFromResumeToken(changeDocument._id).timestamp
|
|
795
|
+
);
|
|
784
796
|
}
|
|
785
797
|
|
|
786
|
-
|
|
787
|
-
|
|
798
|
+
if (!checkpointBlocked || checkpointCreated) {
|
|
799
|
+
this.replicationLag.markCommitted();
|
|
788
800
|
}
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
const tablesToDrop = tables.filter((table) => table.syncAny);
|
|
797
|
-
if (tablesToDrop.length > 0) {
|
|
798
|
-
await batch.drop(tablesToDrop);
|
|
799
|
-
}
|
|
800
|
-
this.relationCache.delete(rel);
|
|
801
|
-
} else if (changeDocument.operationType == 'rename') {
|
|
802
|
-
const relFrom = getMongoRelation(changeDocument.ns, this.connections.connectionTag);
|
|
803
|
-
const relTo = getMongoRelation(changeDocument.to, this.connections.connectionTag);
|
|
804
|
-
const tablesFrom = await this.getRelations(batch, relFrom, {
|
|
805
|
-
// We're "dropping" this collection, so never snapshot it.
|
|
806
|
-
snapshot: false
|
|
807
|
-
});
|
|
808
|
-
const tablesToDrop = tablesFrom.filter((table) => table.syncAny);
|
|
809
|
-
if (tablesToDrop.length > 0) {
|
|
810
|
-
await batch.drop(tablesToDrop);
|
|
811
|
-
}
|
|
812
|
-
this.relationCache.delete(relFrom);
|
|
813
|
-
// Here we do need to snapshot the new table
|
|
814
|
-
const collection = await this.getCollectionInfo(relTo.schema, relTo.name);
|
|
815
|
-
await this.handleRelation(batch, relTo, {
|
|
816
|
-
// This is a new (renamed) collection, so always snapshot it.
|
|
817
|
-
snapshot: true,
|
|
818
|
-
collectionInfo: collection
|
|
819
|
-
});
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
if (this.abortSignal.aborted) break;
|
|
823
|
-
this.touch();
|
|
824
|
-
const batchFilteredCount = sourceBatch.metadata.filteredCount;
|
|
825
|
-
if (batchFilteredCount != null) {
|
|
826
|
-
filteredSinceProgress = (filteredSinceProgress ?? 0) + batchFilteredCount;
|
|
827
|
-
}
|
|
828
|
-
const resumeToken = sourceBatch.getResumeToken();
|
|
829
|
-
if (resumeToken != null) {
|
|
830
|
-
const filteredCount = filteredSinceProgress;
|
|
831
|
-
if (changesSinceProgress == 0) {
|
|
832
|
-
// No retained changes since the previous progress boundary: this is either idle or filtered-only traffic.
|
|
833
|
-
// Case 1: No pending barrier and the keepalive interval has elapsed. Advance checkpoints as below,
|
|
834
|
-
// then flush and save the resume token.
|
|
835
|
-
// Case 2: Idle traffic with a recent keepalive. Skip this resume update, whether or not a barrier
|
|
836
|
-
// is pending, to preserve the idle throttle.
|
|
837
|
-
// Case 3: All other combinations. Flush and save the resume token without requesting a checkpoint.
|
|
838
|
-
// A pending barrier will provide the checkpoint boundary once replication reaches it. Filtered
|
|
839
|
-
// progress still saves its token even during the keepalive interval, so excluded work is resumable.
|
|
840
|
-
const hadRecentKeepalive = performance.now() - lastKeepalive < this.keepaliveIntervalMs;
|
|
841
|
-
if (waitForCheckpointLsn == null && !hadRecentKeepalive) {
|
|
842
|
-
if ((filteredCount ?? 0) > 0) {
|
|
843
|
-
// Case 1a: A transaction can span batches: this batch may contain only filtered changes,
|
|
844
|
-
// while retained changes from the same transaction are still unread. They share a timestamp,
|
|
845
|
-
// so publishing a checkpoint here could acknowledge the transaction before its data is saved.
|
|
846
|
-
// Request a source barrier; reaching it ensures those retained changes have been processed.
|
|
847
|
-
// The progress token can still be saved below for recovery without publishing a checkpoint.
|
|
801
|
+
} else if (
|
|
802
|
+
changeDocument.operationType == 'insert' ||
|
|
803
|
+
changeDocument.operationType == 'update' ||
|
|
804
|
+
changeDocument.operationType == 'replace' ||
|
|
805
|
+
changeDocument.operationType == 'delete'
|
|
806
|
+
) {
|
|
807
|
+
if (waitForCheckpointLsn == null) {
|
|
848
808
|
using _ = tracer.span('source_checkpoint');
|
|
849
809
|
waitForCheckpointLsn = await this.createBatchCheckpoint();
|
|
850
|
-
} else {
|
|
851
|
-
// Case 1b: Idle traffic. The timestamp implementation persists a keepalive directly;
|
|
852
|
-
// the sentinel implementation writes a source marker whose event will commit later.
|
|
853
|
-
await this.checkpointImplementation.keepalive(batch, resumeToken);
|
|
854
|
-
this.replicationLag.markStarted();
|
|
855
810
|
}
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
811
|
+
|
|
812
|
+
const rel = getMongoRelation(changeDocument.ns, this.connections.connectionTag);
|
|
813
|
+
const tables = await this.getRelations(batch, rel, {
|
|
814
|
+
// In most cases, we should not need to snapshot this. But if this is the first time we see the collection
|
|
815
|
+
// for whatever reason, then we do need to snapshot it.
|
|
816
|
+
// This may result in some duplicate operations when a collection is created for the first time after
|
|
817
|
+
// sync config was deployed.
|
|
818
|
+
snapshot: true
|
|
819
|
+
});
|
|
820
|
+
const tablesToReplicate = tables.filter((table) => table.syncAny);
|
|
821
|
+
if (tablesToReplicate.length > 0) {
|
|
822
|
+
this.replicationLag.trackUncommittedChange(
|
|
823
|
+
// Standard MongoDB uses clusterTime, unchanged. DocumentDB has no
|
|
824
|
+
// clusterTime, so fall back to wallTime there for the lag metric.
|
|
825
|
+
changeDocument.clusterTime != null
|
|
826
|
+
? timestampToDate(changeDocument.clusterTime)
|
|
827
|
+
: ((changeDocument as any).wallTime ?? null)
|
|
828
|
+
);
|
|
829
|
+
|
|
830
|
+
const transactionKeyValue = transactionKey(changeDocument);
|
|
831
|
+
|
|
832
|
+
if (transactionKeyValue == null || lastTxnKey != transactionKeyValue) {
|
|
833
|
+
// Very crude metric for counting transactions replicated.
|
|
834
|
+
// We ignore operations other than basic CRUD, and ignore changes to _powersync_checkpoints.
|
|
835
|
+
// Individual writes may not have a txnNumber, in which case we count them as separate transactions.
|
|
836
|
+
lastTxnKey = transactionKeyValue;
|
|
837
|
+
transactionsReplicatedMetric.add(1);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
for (const table of tablesToReplicate) {
|
|
841
|
+
await this.writeChange(batch, table, changeDocument);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
} else if (changeDocument.operationType == 'drop') {
|
|
845
|
+
const rel = getMongoRelation(changeDocument.ns, this.connections.connectionTag);
|
|
846
|
+
const tables = await this.getRelations(batch, rel, {
|
|
847
|
+
// We're "dropping" this collection, so never snapshot it.
|
|
848
|
+
snapshot: false
|
|
849
|
+
});
|
|
850
|
+
const tablesToDrop = tables.filter((table) => table.syncAny);
|
|
851
|
+
if (tablesToDrop.length > 0) {
|
|
852
|
+
await batch.drop(tablesToDrop);
|
|
853
|
+
}
|
|
854
|
+
this.relationCache.delete(rel);
|
|
855
|
+
} else if (changeDocument.operationType == 'rename') {
|
|
856
|
+
const relFrom = getMongoRelation(changeDocument.ns, this.connections.connectionTag);
|
|
857
|
+
const relTo = getMongoRelation(changeDocument.to, this.connections.connectionTag);
|
|
858
|
+
const tablesFrom = await this.getRelations(batch, relFrom, {
|
|
859
|
+
// We're "dropping" this collection, so never snapshot it.
|
|
860
|
+
snapshot: false
|
|
861
|
+
});
|
|
862
|
+
const tablesToDrop = tablesFrom.filter((table) => table.syncAny);
|
|
863
|
+
if (tablesToDrop.length > 0) {
|
|
864
|
+
await batch.drop(tablesToDrop);
|
|
865
|
+
}
|
|
866
|
+
this.relationCache.delete(relFrom);
|
|
867
|
+
// Here we do need to snapshot the new table
|
|
868
|
+
const collection = await this.getCollectionInfo(relTo.schema, relTo.name);
|
|
869
|
+
await this.handleRelation(batch, relTo, {
|
|
870
|
+
// This is a new (renamed) collection, so always snapshot it.
|
|
871
|
+
snapshot: true,
|
|
872
|
+
collectionInfo: collection
|
|
873
|
+
});
|
|
861
874
|
}
|
|
862
875
|
}
|
|
876
|
+
if (this.abortSignal.aborted) {
|
|
877
|
+
break;
|
|
878
|
+
}
|
|
879
|
+
this.touch();
|
|
880
|
+
const batchFilteredCount = sourceBatch.metadata.filteredCount;
|
|
881
|
+
if (batchFilteredCount != null) {
|
|
882
|
+
filteredSinceProgress = (filteredSinceProgress ?? 0) + batchFilteredCount;
|
|
883
|
+
}
|
|
884
|
+
const resumeToken = sourceBatch.getResumeToken();
|
|
885
|
+
if (resumeToken != null) {
|
|
886
|
+
const filteredCount = filteredSinceProgress;
|
|
887
|
+
if (changesSinceProgress == 0) {
|
|
888
|
+
// No retained changes since the previous progress boundary: this is either idle or filtered-only traffic.
|
|
889
|
+
// Case 1: No pending barrier and the keepalive interval has elapsed. Advance checkpoints as below,
|
|
890
|
+
// then make the resume token eligible for persistence.
|
|
891
|
+
// Case 2: Idle traffic with a recent keepalive. Skip this resume update, whether or not a barrier
|
|
892
|
+
// is pending, to preserve the idle throttle.
|
|
893
|
+
// Case 3: All other combinations. Make the token eligible without requesting a checkpoint.
|
|
894
|
+
// A pending barrier will provide the checkpoint boundary once replication reaches it. Filtered
|
|
895
|
+
// progress remains eligible during the keepalive interval, so excluded work is resumable.
|
|
896
|
+
const hadRecentKeepalive = performance.now() - lastKeepalive < this.keepaliveIntervalMs;
|
|
897
|
+
if (waitForCheckpointLsn == null && !hadRecentKeepalive) {
|
|
898
|
+
if ((filteredCount ?? 0) > 0) {
|
|
899
|
+
// Case 1a: A transaction can span batches: this batch may contain only filtered changes,
|
|
900
|
+
// while retained changes from the same transaction are still unread. They share a timestamp,
|
|
901
|
+
// so publishing a checkpoint here could acknowledge the transaction before its data is saved.
|
|
902
|
+
// Request a source barrier; reaching it ensures those retained changes have been processed.
|
|
903
|
+
// The progress token can still be saved below for recovery without publishing a checkpoint.
|
|
904
|
+
using _ = tracer.span('source_checkpoint');
|
|
905
|
+
waitForCheckpointLsn = await this.createBatchCheckpoint();
|
|
906
|
+
} else {
|
|
907
|
+
// Case 1b: Idle traffic. The timestamp implementation persists a keepalive directly;
|
|
908
|
+
// the sentinel implementation writes a source marker whose event will commit later.
|
|
909
|
+
await this.checkpointImplementation.keepalive(batch, resumeToken);
|
|
910
|
+
this.replicationLag.markStarted();
|
|
911
|
+
}
|
|
912
|
+
this.touch();
|
|
913
|
+
lastKeepalive = performance.now();
|
|
914
|
+
} else if ((filteredCount ?? 0) == 0 && hadRecentKeepalive) {
|
|
915
|
+
// Case 2: Don't refresh idle tokens, but finish any earlier active progress when due.
|
|
916
|
+
if (performance.now() - lastProgressAt >= this.streamingProgressIntervalMs) {
|
|
917
|
+
await persistProgress();
|
|
918
|
+
}
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
}
|
|
863
922
|
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
923
|
+
const progress = this.checkpointImplementation.lsnFromResumeToken(resumeToken);
|
|
924
|
+
// Only exact equality proves a token is already covered: transaction events can share a
|
|
925
|
+
// timestamp, and sentinel tokens are opaque. Never deduplicate by timestamp or token order.
|
|
926
|
+
pendingProgress = progress.lsn == durableResumeLsn ? null : progress;
|
|
927
|
+
if (performance.now() - lastProgressAt >= this.streamingProgressIntervalMs) {
|
|
928
|
+
await persistProgress();
|
|
929
|
+
}
|
|
930
|
+
processingSpan?.end();
|
|
931
|
+
const durationsMicroseconds = outerSpan.end();
|
|
932
|
+
const filteringDescription = filteredCount == null ? '' : ` and ${filteredCount} filtered events`;
|
|
933
|
+
this.logger.info(`Processed ${changesSinceProgress} changes${filteringDescription}`, {
|
|
934
|
+
count: changesSinceProgress,
|
|
935
|
+
...(filteredCount == null ? {} : { filteredCount }),
|
|
936
|
+
bytes: receivedBytes,
|
|
937
|
+
duration: processingSpan?.durationMillis,
|
|
938
|
+
t: durationsMicroseconds
|
|
939
|
+
});
|
|
940
|
+
changesSinceProgress = 0;
|
|
941
|
+
filteredSinceProgress = null;
|
|
942
|
+
receivedBytes = 0;
|
|
943
|
+
outerSpan = tracer.span('batch');
|
|
944
|
+
continue;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
} catch (error) {
|
|
948
|
+
// Cursor cancellation can throw instead of ending iteration. Flush only the previously
|
|
949
|
+
// completed safe page; processing/adapter/storage failures must leave progress for replay.
|
|
950
|
+
if (!this.abortSignal.aborted || error !== this.abortSignal.reason) {
|
|
951
|
+
throw error;
|
|
886
952
|
}
|
|
887
953
|
}
|
|
954
|
+
await persistProgress();
|
|
888
955
|
}
|
|
889
956
|
);
|
|
890
957
|
|