@powersync/service-module-mongodb 0.22.9 → 0.23.0-dev-20261205085725
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 +11 -0
- package/dist/replication/MongoReplicationQueryProvider.d.ts +50 -5
- package/dist/replication/MongoReplicationQueryProvider.js +24 -1
- package/dist/replication/MongoReplicationQueryProvider.js.map +1 -1
- package/dist/replication/MongoSnapshotPartitionResume.d.ts +36 -0
- package/dist/replication/MongoSnapshotPartitionResume.js +95 -0
- package/dist/replication/MongoSnapshotPartitionResume.js.map +1 -0
- package/dist/replication/MongoSnapshotQuery.d.ts +5 -0
- package/dist/replication/MongoSnapshotQuery.js +15 -0
- package/dist/replication/MongoSnapshotQuery.js.map +1 -1
- package/dist/replication/MongoSnapshotter.js +144 -84
- package/dist/replication/MongoSnapshotter.js.map +1 -1
- package/dist/replication/estimateFilteredSnapshotCount.d.ts +12 -0
- package/dist/replication/estimateFilteredSnapshotCount.js +37 -0
- package/dist/replication/estimateFilteredSnapshotCount.js.map +1 -1
- package/package.json +5 -4
- package/src/replication/MongoReplicationQueryProvider.ts +73 -6
- package/src/replication/MongoSnapshotPartitionResume.ts +133 -0
- package/src/replication/MongoSnapshotQuery.ts +15 -0
- package/src/replication/MongoSnapshotter.ts +157 -93
- package/src/replication/estimateFilteredSnapshotCount.ts +43 -0
- package/test/src/filtering_example.test.ts +4 -2
- package/test/src/filtering_lifecycle.test.ts +3 -2
- package/test/src/partitioned_snapshot.test.ts +205 -0
- package/test/src/snapshot_query_provider.test.ts +26 -19
- package/test/src/snapshot_resume_key.test.ts +108 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -17,15 +17,18 @@ import { escapeRegExp } from '../utils.js';
|
|
|
17
17
|
import { parseDocumentId } from './bufferToSqlite.js';
|
|
18
18
|
import { CheckpointImplementation } from './checkpoints/CheckpointImplementation.js';
|
|
19
19
|
import { createCheckpointImplementation } from './checkpoints/create-checkpoint-implementation.js';
|
|
20
|
-
import { estimateFilteredSnapshotCount } from './estimateFilteredSnapshotCount.js';
|
|
20
|
+
import { estimateFilteredSnapshotCount, estimatePartitionedSnapshotCount } from './estimateFilteredSnapshotCount.js';
|
|
21
21
|
import { MongoManager } from './MongoManager.js';
|
|
22
22
|
import { getMongoRelation } from './MongoRelation.js';
|
|
23
23
|
import {
|
|
24
|
+
assertSnapshotPartitionPlan,
|
|
24
25
|
DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER,
|
|
25
|
-
MongoReplicationQueryProvider
|
|
26
|
+
MongoReplicationQueryProvider,
|
|
27
|
+
MongoSnapshotPartitionPlan
|
|
26
28
|
} from './MongoReplicationQueryProvider.js';
|
|
27
29
|
import { openMongoReplicationStream } from './MongoReplicationStream.js';
|
|
28
30
|
import type { MongoReplicationStreamBatch } from './MongoReplicationStreamTypes.js';
|
|
31
|
+
import { encodeSnapshotResumeKey, resolveSnapshotResumeState } from './MongoSnapshotPartitionResume.js';
|
|
29
32
|
import { ChunkedSnapshotQuery } from './MongoSnapshotQuery.js';
|
|
30
33
|
import { ChangeStreamBatch } from './RawChangeStream.js';
|
|
31
34
|
import { CHECKPOINTS_COLLECTION, detectDocumentDb } from './replication-utils.js';
|
|
@@ -529,46 +532,41 @@ export class MongoSnapshotter {
|
|
|
529
532
|
const bytesReplicatedMetric = this.metrics.getCounter(ReplicationMetric.DATA_REPLICATED_BYTES);
|
|
530
533
|
const chunksReplicatedMetric = this.metrics.getCounter(ReplicationMetric.CHUNKS_REPLICATED);
|
|
531
534
|
|
|
532
|
-
const filter = this.queryProvider.getSnapshotFilter(table);
|
|
533
535
|
const collection = this.client.db(table.schema).collection(table.name);
|
|
534
|
-
const
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
// The caller still marks the snapshot complete, and the change stream handles later matches.
|
|
541
|
-
this.logger.info(`Skipping replication of ${table.qualifiedName} - no documents match the snapshot filter`);
|
|
542
|
-
return;
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
// Reuse known filtered estimates to avoid repeating an expensive count and sample. Unknown totals
|
|
546
|
-
// (-1) can also represent uninitialized progress, so retry them. Unfiltered metadata counts are cheap
|
|
547
|
-
// and refreshed before copying rows.
|
|
548
|
-
const previousEstimate = table.snapshotStatus?.totalEstimatedCount ?? -1;
|
|
549
|
-
const totalEstimatedCount =
|
|
550
|
-
filter != null && previousEstimate >= 0 ? previousEstimate : await this.estimatedCountNumber(table, filter);
|
|
536
|
+
const plan = await this.queryProvider.getSnapshotPartitions({ table, collection });
|
|
537
|
+
assertSnapshotPartitionPlan(plan);
|
|
538
|
+
const partitionCount = plan.partitions.length;
|
|
539
|
+
const resume = resolveSnapshotResumeState(plan, table.snapshotStatus?.lastKey);
|
|
540
|
+
// Progress by partition ID, updated as pages are copied and partitions finish, and saved as the resume key.
|
|
541
|
+
const progress = resume.progress;
|
|
551
542
|
let at = table.snapshotStatus?.replicatedCount ?? 0;
|
|
543
|
+
if (resume.discardedReason != null) {
|
|
544
|
+
// Rows already copied are skipped by the snapshot writer, so restarting the table only costs reads.
|
|
545
|
+
this.logger.warn(`Restarting snapshot of ${table.qualifiedName}: ${resume.discardedReason}`);
|
|
546
|
+
at = 0;
|
|
547
|
+
}
|
|
552
548
|
// When supported by the storage batch, pass raw BSON instead of decoding rows here.
|
|
553
549
|
const saveBson = batch.prepareUndecodedSave?.('bson');
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
if (query.lastKey != null) {
|
|
562
|
-
this.logger.info(
|
|
563
|
-
`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()} - resuming at _id > ${query.lastKey}`
|
|
564
|
-
);
|
|
565
|
-
} else {
|
|
566
|
-
this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()}`);
|
|
567
|
-
}
|
|
550
|
+
// Upper-bound lookups need a causal read at the resume LSN. After one times out, page the rest without bounds.
|
|
551
|
+
let lookupsAvailable = !this.isDocumentDb && batch.resumeFromLsn != null;
|
|
552
|
+
// Reuse known filtered estimates to avoid repeating expensive counts. Unknown totals (-1) can also represent
|
|
553
|
+
// uninitialized progress, so retry them. Unfiltered metadata counts are cheap and refreshed before copying rows.
|
|
554
|
+
const filtered = plan.partitions.some((partition) => partition.filter != null);
|
|
555
|
+
const previousEstimate = table.snapshotStatus?.totalEstimatedCount ?? -1;
|
|
556
|
+
let totalEstimatedCount: number | null = filtered && previousEstimate >= 0 ? previousEstimate : null;
|
|
568
557
|
|
|
558
|
+
let partitionIndex = 0;
|
|
559
|
+
let announced = false;
|
|
569
560
|
let lastProgressAt = performance.now();
|
|
570
|
-
let pendingKey: Uint8Array | null = null;
|
|
571
561
|
let pendingProgress = false;
|
|
562
|
+
// Uses the current counts rather than the persisted status, which can lag behind a restart or a new estimate.
|
|
563
|
+
// The final progress is persisted after the loop, when the index is past the last partition.
|
|
564
|
+
const describeProgress = () => {
|
|
565
|
+
const total = totalEstimatedCount == null || totalEstimatedCount < 0 ? '?' : `~${totalEstimatedCount}`;
|
|
566
|
+
const position =
|
|
567
|
+
partitionCount > 1 ? ` partition ${Math.min(partitionIndex + 1, partitionCount)}/${partitionCount}` : '';
|
|
568
|
+
return `${at}/${total}${position}`;
|
|
569
|
+
};
|
|
572
570
|
const persistProgress = async () => {
|
|
573
571
|
if (!pendingProgress) {
|
|
574
572
|
return;
|
|
@@ -577,77 +575,136 @@ export class MongoSnapshotter {
|
|
|
577
575
|
// keep storage work bounded between these less frequent durable barriers.
|
|
578
576
|
await batch.flush();
|
|
579
577
|
table = await batch.updateTableProgress(table, {
|
|
580
|
-
lastKey:
|
|
578
|
+
lastKey: encodeSnapshotResumeKey(plan, progress),
|
|
581
579
|
replicatedCount: at,
|
|
582
|
-
totalEstimatedCount
|
|
580
|
+
totalEstimatedCount: totalEstimatedCount ?? -1
|
|
583
581
|
});
|
|
584
582
|
const now = performance.now();
|
|
585
583
|
this.logger.info(
|
|
586
|
-
`Replicating ${table.qualifiedName} ${
|
|
584
|
+
`Replicating ${table.qualifiedName} ${describeProgress()} in ${(now - lastProgressAt).toFixed(0)}ms`
|
|
587
585
|
);
|
|
588
586
|
lastProgressAt = now;
|
|
589
587
|
pendingProgress = false;
|
|
590
588
|
};
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
if (this.abortSignal.aborted) {
|
|
603
|
-
// Preserve the last complete page on graceful shutdown, even if the
|
|
604
|
-
// persistence interval has not elapsed. Never advance into this page.
|
|
605
|
-
await persistProgress();
|
|
606
|
-
throw new ReplicationAbortedError(`Aborted initial replication`, this.abortSignal.reason);
|
|
607
|
-
}
|
|
589
|
+
const finishPartition = async (id: string) => {
|
|
590
|
+
// A single-partition table is marked complete instead.
|
|
591
|
+
if (partitionCount == 1) {
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
progress.set(id, { done: true });
|
|
595
|
+
pendingProgress = true;
|
|
596
|
+
if (performance.now() - lastProgressAt >= this.snapshotProgressIntervalMs) {
|
|
597
|
+
await persistProgress();
|
|
598
|
+
}
|
|
599
|
+
};
|
|
608
600
|
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
601
|
+
for (; partitionIndex < partitionCount; partitionIndex++) {
|
|
602
|
+
const partition = plan.partitions[partitionIndex];
|
|
603
|
+
const saved = progress.get(partition.id);
|
|
604
|
+
if (saved != null && 'done' in saved) {
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
const upperBound: SnapshotUpperBoundResult =
|
|
608
|
+
partition.filter != null && lookupsAvailable
|
|
609
|
+
? await this.findSnapshotUpperBound(collection, partition.filter, batch.resumeFromLsn!)
|
|
610
|
+
: { kind: 'unavailable' };
|
|
611
|
+
if (upperBound.kind === 'empty') {
|
|
612
|
+
// The lookup saw no matches in a majority read at least as recent as the resume LSN.
|
|
613
|
+
// The change stream handles later matches, and the caller still marks the snapshot complete.
|
|
614
|
+
await finishPartition(partition.id);
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
if (upperBound.kind === 'unavailable' && partition.filter != null) {
|
|
618
|
+
lookupsAvailable = false;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// Count only once there is something to copy, so an empty single-partition table skips the count.
|
|
622
|
+
totalEstimatedCount ??= await this.estimatedCountNumber(table, plan);
|
|
623
|
+
const key = saved != null && 'lastKey' in saved ? saved.lastKey : null;
|
|
624
|
+
await using query = new ChunkedSnapshotQuery({
|
|
625
|
+
collection,
|
|
626
|
+
key,
|
|
627
|
+
batchSize: this.snapshotChunkLength,
|
|
628
|
+
filter: partition.filter,
|
|
629
|
+
upperKey: upperBound.kind === 'found' ? upperBound.key : undefined
|
|
630
|
+
});
|
|
631
|
+
if (!announced) {
|
|
632
|
+
// Log the start once per table, at the first partition with documents to copy.
|
|
633
|
+
this.logger.info(
|
|
634
|
+
`Replicating ${table.qualifiedName} ${describeProgress()}${key != null ? ` - resuming at _id > ${query.lastKey}` : ''}`
|
|
635
|
+
);
|
|
636
|
+
announced = true;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
let nextChunkPromise = query.nextChunk();
|
|
640
|
+
try {
|
|
641
|
+
while (true) {
|
|
642
|
+
const { docs: docBatch, lastKey, bytes: chunkBytes } = await nextChunkPromise;
|
|
643
|
+
if (docBatch.length == 0) {
|
|
644
|
+
// No more data in this partition - stop iterating
|
|
645
|
+
break;
|
|
646
|
+
}
|
|
647
|
+
bytesReplicatedMetric.add(chunkBytes);
|
|
648
|
+
chunksReplicatedMetric.add(1);
|
|
649
|
+
|
|
650
|
+
if (this.abortSignal.aborted) {
|
|
651
|
+
// Preserve the last complete page on graceful shutdown, even if the
|
|
652
|
+
// persistence interval has not elapsed. Never advance into this page.
|
|
653
|
+
await persistProgress();
|
|
654
|
+
throw new ReplicationAbortedError(`Aborted initial replication`, this.abortSignal.reason);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// Pre-fetch next batch, so that we can read and write concurrently
|
|
658
|
+
nextChunkPromise = query.nextChunk();
|
|
659
|
+
for (const buffer of docBatch) {
|
|
660
|
+
// These auto-flush when the batch reaches its size limit
|
|
661
|
+
if (saveBson != null) {
|
|
662
|
+
await saveBson({
|
|
663
|
+
tag: SaveOperationTag.INSERT,
|
|
664
|
+
sourceTable: table,
|
|
665
|
+
after: buffer,
|
|
666
|
+
afterReplicaId: this.sourceRowConverter.rawToReplica(buffer)
|
|
667
|
+
});
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
const { row, replicaId } = this.sourceRowConverter.rawToSqliteRow(buffer);
|
|
672
|
+
await batch.save({
|
|
615
673
|
tag: SaveOperationTag.INSERT,
|
|
616
674
|
sourceTable: table,
|
|
617
|
-
|
|
618
|
-
|
|
675
|
+
before: undefined,
|
|
676
|
+
beforeReplicaId: undefined,
|
|
677
|
+
after: row,
|
|
678
|
+
afterReplicaId: replicaId
|
|
619
679
|
});
|
|
620
|
-
continue;
|
|
621
680
|
}
|
|
622
681
|
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
at += docBatch.length;
|
|
635
|
-
// Activity counters track processed source rows; the table cursor and
|
|
636
|
-
// progress log advance only at a durable persistence boundary.
|
|
637
|
-
rowsReplicatedMetric.add(docBatch.length);
|
|
638
|
-
pendingKey = lastKey;
|
|
639
|
-
pendingProgress = true;
|
|
640
|
-
if (performance.now() - lastProgressAt >= this.snapshotProgressIntervalMs || this.abortSignal.aborted) {
|
|
641
|
-
await persistProgress();
|
|
682
|
+
at += docBatch.length;
|
|
683
|
+
// Activity counters track processed source rows; the table cursor and
|
|
684
|
+
// progress log advance only at a durable persistence boundary.
|
|
685
|
+
rowsReplicatedMetric.add(docBatch.length);
|
|
686
|
+
// A non-empty chunk always has a last key.
|
|
687
|
+
progress.set(partition.id, { lastKey: lastKey! });
|
|
688
|
+
pendingProgress = true;
|
|
689
|
+
if (performance.now() - lastProgressAt >= this.snapshotProgressIntervalMs || this.abortSignal.aborted) {
|
|
690
|
+
await persistProgress();
|
|
691
|
+
}
|
|
692
|
+
this.touch();
|
|
642
693
|
}
|
|
643
|
-
|
|
694
|
+
} finally {
|
|
695
|
+
// In case the loop was interrupted, make sure we await the last promise.
|
|
696
|
+
await nextChunkPromise.catch(() => {});
|
|
644
697
|
}
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
//
|
|
649
|
-
|
|
698
|
+
await finishPartition(partition.id);
|
|
699
|
+
}
|
|
700
|
+
if (!announced) {
|
|
701
|
+
// Every remaining partition was already finished or skipped by its upper-bound lookup.
|
|
702
|
+
this.logger.info(
|
|
703
|
+
`Skipping replication of ${table.qualifiedName} - no ${resume.progress.size > 0 ? 'remaining ' : ''}documents match the snapshot filter`
|
|
704
|
+
);
|
|
650
705
|
}
|
|
706
|
+
// A short snapshot must persist its final page too, before table completion.
|
|
707
|
+
await persistProgress();
|
|
651
708
|
}
|
|
652
709
|
|
|
653
710
|
private async handleRelation(
|
|
@@ -682,11 +739,18 @@ export class MongoSnapshotter {
|
|
|
682
739
|
return result.tables;
|
|
683
740
|
}
|
|
684
741
|
|
|
685
|
-
private async estimatedCountNumber(
|
|
686
|
-
table: storage.SourceTable,
|
|
687
|
-
filter = this.queryProvider.getSnapshotFilter(table)
|
|
688
|
-
): Promise<number> {
|
|
742
|
+
private async estimatedCountNumber(table: storage.SourceTable, plan?: MongoSnapshotPartitionPlan): Promise<number> {
|
|
689
743
|
const collection = this.client.db(table.schema).collection(table.name);
|
|
744
|
+
plan ??= await this.queryProvider.getSnapshotPartitions({ table, collection });
|
|
745
|
+
if (plan.partitions.length > 1) {
|
|
746
|
+
return await estimatePartitionedSnapshotCount({
|
|
747
|
+
collection,
|
|
748
|
+
partitions: plan.partitions,
|
|
749
|
+
signal: this.abortSignal,
|
|
750
|
+
logger: this.logger
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
const filter = plan.partitions[0]?.filter ?? null;
|
|
690
754
|
if (filter != null) {
|
|
691
755
|
return await estimateFilteredSnapshotCount({
|
|
692
756
|
collection,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { mongo } from '@powersync/lib-service-mongodb';
|
|
2
2
|
import type { Logger } from '@powersync/lib-services-framework';
|
|
3
3
|
import { performance } from 'node:perf_hooks';
|
|
4
|
+
import type { MongoSnapshotPartition } from './MongoReplicationQueryProvider.js';
|
|
4
5
|
|
|
5
6
|
const COUNT_TIMEOUT_MS = 10_000;
|
|
6
7
|
/**
|
|
@@ -9,6 +10,11 @@ const COUNT_TIMEOUT_MS = 10_000;
|
|
|
9
10
|
*/
|
|
10
11
|
const SAMPLE_FRACTION = 0.01;
|
|
11
12
|
const MAX_SAMPLE_SIZE = 10_000;
|
|
13
|
+
/**
|
|
14
|
+
* Total time for all partition counts of a table, matching the count and sample budgets of an unsplit estimate.
|
|
15
|
+
* Counts run before copying and again after restarts, so a plan with many partitions must not delay snapshots.
|
|
16
|
+
*/
|
|
17
|
+
const PARTITIONED_COUNT_BUDGET_MS = 2 * COUNT_TIMEOUT_MS;
|
|
12
18
|
|
|
13
19
|
interface SampleCounts {
|
|
14
20
|
sampled: { count: number }[];
|
|
@@ -91,3 +97,40 @@ export async function estimateFilteredSnapshotCount(options: {
|
|
|
91
97
|
return -1;
|
|
92
98
|
}
|
|
93
99
|
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Sum exact counts of each partition's estimate filter, which providers can make countable from index keys alone.
|
|
103
|
+
* All counts share one time budget. The first failed count, or running out of budget, leaves progress unknown (-1);
|
|
104
|
+
* a per-partition sample would cost a collection sample each.
|
|
105
|
+
*/
|
|
106
|
+
export async function estimatePartitionedSnapshotCount(options: {
|
|
107
|
+
collection: mongo.Collection;
|
|
108
|
+
partitions: MongoSnapshotPartition[];
|
|
109
|
+
signal: AbortSignal;
|
|
110
|
+
logger: Logger;
|
|
111
|
+
}): Promise<number> {
|
|
112
|
+
const { collection, partitions, signal, logger } = options;
|
|
113
|
+
const deadline = performance.now() + PARTITIONED_COUNT_BUDGET_MS;
|
|
114
|
+
let total = 0;
|
|
115
|
+
for (const partition of partitions) {
|
|
116
|
+
signal.throwIfAborted();
|
|
117
|
+
const remaining = deadline - performance.now();
|
|
118
|
+
if (remaining <= 0) {
|
|
119
|
+
logger.debug(`Partitioned snapshot count for ${collection.namespace} ran out of time; total remains unknown`);
|
|
120
|
+
return -1;
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
total += await collection.countDocuments(partition.estimateFilter ?? partition.filter ?? {}, {
|
|
124
|
+
collation: { locale: 'simple' },
|
|
125
|
+
readConcern: 'majority',
|
|
126
|
+
timeoutMS: Math.min(COUNT_TIMEOUT_MS, Math.ceil(remaining)),
|
|
127
|
+
signal
|
|
128
|
+
});
|
|
129
|
+
} catch (error) {
|
|
130
|
+
signal.throwIfAborted();
|
|
131
|
+
logger.debug(`Partitioned snapshot count unavailable for ${collection.namespace}; total remains unknown`, error);
|
|
132
|
+
return -1;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return total;
|
|
136
|
+
}
|
|
@@ -4,7 +4,8 @@ import {
|
|
|
4
4
|
MongoReplicationFilterResult,
|
|
5
5
|
MongoReplicationQueryProvider,
|
|
6
6
|
parseMongoReplicationStream,
|
|
7
|
-
RawMongoReplicationStreamBatch
|
|
7
|
+
RawMongoReplicationStreamBatch,
|
|
8
|
+
singleSnapshotPartition
|
|
8
9
|
} from '@module/index.js';
|
|
9
10
|
import { mongo } from '@powersync/lib-service-mongodb';
|
|
10
11
|
import { expect, test } from 'vitest';
|
|
@@ -19,7 +20,8 @@ test('example: replicate only documents with public IDs and preserve filtered pr
|
|
|
19
20
|
? MongoReplicationFilterResult.KEEP
|
|
20
21
|
: MongoReplicationFilterResult.EXCLUDE;
|
|
21
22
|
const provider: MongoReplicationQueryProvider = {
|
|
22
|
-
|
|
23
|
+
getSnapshotPartitions: async () =>
|
|
24
|
+
singleSnapshotPartition({ $expr: { $regexMatch: { input: '$_id', regex: '^public-' } } }),
|
|
23
25
|
openChangeStream: ({ open }) => filterMongoReplicationStream({ batches: open({}), filter })
|
|
24
26
|
};
|
|
25
27
|
|
|
@@ -2,7 +2,8 @@ import {
|
|
|
2
2
|
filterMongoReplicationStream,
|
|
3
3
|
MongoReplicationFilterResult,
|
|
4
4
|
MongoReplicationQueryProvider,
|
|
5
|
-
PostImagesOption
|
|
5
|
+
PostImagesOption,
|
|
6
|
+
singleSnapshotPartition
|
|
6
7
|
} from '@module/index.js';
|
|
7
8
|
import { mongo } from '@powersync/lib-service-mongodb';
|
|
8
9
|
import { describe, expect, test } from 'vitest';
|
|
@@ -24,7 +25,7 @@ const CONFIG = /* yaml */ `
|
|
|
24
25
|
* Required pre/post-images let the provider distinguish entries, exits and source deletes precisely.
|
|
25
26
|
*/
|
|
26
27
|
const PROVIDER: MongoReplicationQueryProvider = {
|
|
27
|
-
|
|
28
|
+
getSnapshotPartitions: async () => singleSnapshotPartition({ active: true }),
|
|
28
29
|
openChangeStream: ({ open }) =>
|
|
29
30
|
filterMongoReplicationStream({
|
|
30
31
|
batches: open({ imageOptions: { fullDocumentBeforeChange: 'required' } }),
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER,
|
|
3
|
+
MongoSnapshotPartitionPlan
|
|
4
|
+
} from '@module/replication/MongoReplicationQueryProvider.js';
|
|
5
|
+
import { mongo } from '@powersync/lib-service-mongodb';
|
|
6
|
+
import { TestStorageFactory } from '@powersync/service-core';
|
|
7
|
+
import { describe, expect, test, vi } from 'vitest';
|
|
8
|
+
import { openChangeStreamTestContext } from './change_stream_test_setup.js';
|
|
9
|
+
import { DATABASE_TYPE, DatabaseType } from './DatabaseType.js';
|
|
10
|
+
import { describeWithStorage } from './util.js';
|
|
11
|
+
|
|
12
|
+
type FixtureDocument = mongo.Document & { _id: unknown };
|
|
13
|
+
|
|
14
|
+
const STORES: unknown[] = ['a', 'missing', 'b', 1];
|
|
15
|
+
const STORE_VALUES: unknown[] = ['a', 'b', 1, 'excluded', ['a']];
|
|
16
|
+
// Mixed BSON types for _id and the partition values; arrays and unlisted stores are excluded by the filters.
|
|
17
|
+
// Numeric ids start at 3: a document with _id 0 is currently not replicated, even without partitions or filters.
|
|
18
|
+
const DOCUMENTS: FixtureDocument[] = Array.from({ length: 15 }, (_, i) => ({
|
|
19
|
+
_id: i % 3 == 0 ? i + 3 : i % 3 == 1 ? `s${i}` : new mongo.ObjectId(i.toString(16).padStart(24, '0')),
|
|
20
|
+
store: STORE_VALUES[i % STORE_VALUES.length]
|
|
21
|
+
}));
|
|
22
|
+
const EXPECTED_IDS = DOCUMENTS.filter((doc) => STORES.includes(doc.store))
|
|
23
|
+
.map((doc) => String(doc._id))
|
|
24
|
+
.sort();
|
|
25
|
+
const CONFIG = /* yaml */ `
|
|
26
|
+
# Sync config fixture.
|
|
27
|
+
config:
|
|
28
|
+
edition: 3
|
|
29
|
+
streams:
|
|
30
|
+
global:
|
|
31
|
+
query: SELECT _id AS id, store FROM documents
|
|
32
|
+
`;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* One partition per store, in authored order, with position IDs.
|
|
36
|
+
*/
|
|
37
|
+
function storePlan({ fingerprint = 'test-v1', ids }: { fingerprint?: string; ids?: string[] } = {}) {
|
|
38
|
+
return {
|
|
39
|
+
fingerprint,
|
|
40
|
+
partitions: STORES.map((store, index) => ({
|
|
41
|
+
id: ids?.[index] ?? String(index),
|
|
42
|
+
filter: { $and: [{ store: { $eq: store } }, { $expr: { $eq: ['$store', store] } }] },
|
|
43
|
+
estimateFilter: { store }
|
|
44
|
+
}))
|
|
45
|
+
} satisfies MongoSnapshotPartitionPlan;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Arguments of spied collection calls made on the source collection, excluding bucket storage calls.
|
|
50
|
+
*/
|
|
51
|
+
function sourceCalls(spy: { mock: { calls: unknown[][]; contexts: unknown[] } }): unknown[][] {
|
|
52
|
+
return spy.mock.calls.filter(
|
|
53
|
+
(_, index) => (spy.mock.contexts[index] as mongo.Collection | undefined)?.collectionName == 'documents'
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Stores whose partition was read by a snapshot page query. Upper-bound lookups also reach `find` through `findOne`,
|
|
59
|
+
* but only fetch `_id`.
|
|
60
|
+
*/
|
|
61
|
+
function pagedStores(find: { mock: { calls: unknown[][]; contexts: unknown[] } }): unknown[] {
|
|
62
|
+
return sourceCalls(find)
|
|
63
|
+
.filter(([, options]) => {
|
|
64
|
+
const findOptions = options as mongo.FindOptions | undefined;
|
|
65
|
+
return findOptions?.raw && findOptions.projection == null;
|
|
66
|
+
})
|
|
67
|
+
.map(([filter]) => (filter as any).$and?.[0]?.$and?.[0]?.store?.$eq ?? (filter as any).$and?.[0]?.store?.$eq);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function openContext(
|
|
71
|
+
factory: TestStorageFactory,
|
|
72
|
+
storageVersion: number,
|
|
73
|
+
plan: MongoSnapshotPartitionPlan,
|
|
74
|
+
doNotClear = false
|
|
75
|
+
) {
|
|
76
|
+
const context = await openChangeStreamTestContext(factory, {
|
|
77
|
+
storageVersion,
|
|
78
|
+
doNotClear,
|
|
79
|
+
streamOptions: {
|
|
80
|
+
snapshotChunkLength: 2,
|
|
81
|
+
snapshotProgressIntervalMs: 0,
|
|
82
|
+
createReplicationQueryProvider: () => ({
|
|
83
|
+
...DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER,
|
|
84
|
+
getSnapshotPartitions: async () => plan
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
if (doNotClear) {
|
|
89
|
+
await context.loadNextSyncRules();
|
|
90
|
+
} else {
|
|
91
|
+
await context.updateSyncRules(CONFIG);
|
|
92
|
+
await context.db.collection<FixtureDocument>('documents').insertMany(DOCUMENTS);
|
|
93
|
+
}
|
|
94
|
+
return context;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function replicatedIds(context: Awaited<ReturnType<typeof openContext>>): Promise<string[]> {
|
|
98
|
+
const rows = (await context.getBucketData('global|0[]')).filter((op) => op.op == 'PUT');
|
|
99
|
+
return [...new Set(rows.map((op) => String(op.object_id)))].sort();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Interrupts the first snapshot after `rows` saved rows; progress is persisted after every page.
|
|
104
|
+
*/
|
|
105
|
+
async function interruptSnapshot(context: Awaited<ReturnType<typeof openContext>>, rows: number) {
|
|
106
|
+
let saved = 0;
|
|
107
|
+
const create = context.storage!.createWriter.bind(context.storage!);
|
|
108
|
+
using _create = vi.spyOn(context.storage!, 'createWriter').mockImplementation(async (...args) => {
|
|
109
|
+
const writer = await create(...args);
|
|
110
|
+
const save = writer.save.bind(writer);
|
|
111
|
+
vi.spyOn(writer, 'save').mockImplementation(async (record) => {
|
|
112
|
+
const result = await save(record);
|
|
113
|
+
if (++saved == rows) {
|
|
114
|
+
context.abort();
|
|
115
|
+
}
|
|
116
|
+
return result;
|
|
117
|
+
});
|
|
118
|
+
return writer;
|
|
119
|
+
});
|
|
120
|
+
await expect(context.replicateSnapshot()).rejects.toThrow();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('partitioned MongoDB snapshots', () => {
|
|
124
|
+
describeWithStorage({ timeout: 60_000 }, ({ factory, storageVersion }) => {
|
|
125
|
+
test('pages each partition and skips partitions without matches', async () => {
|
|
126
|
+
await using context = await openContext(factory, storageVersion, storePlan());
|
|
127
|
+
using find = vi.spyOn(mongo.Collection.prototype, 'find');
|
|
128
|
+
using findOne = vi.spyOn(mongo.Collection.prototype, 'findOne');
|
|
129
|
+
await context.replicateSnapshot();
|
|
130
|
+
expect(await replicatedIds(context)).toEqual(EXPECTED_IDS);
|
|
131
|
+
// The upper-bound lookup runs per partition and finds no 'missing' documents, so that partition is not paged.
|
|
132
|
+
expect(sourceCalls(findOne)).toHaveLength(STORES.length);
|
|
133
|
+
expect(new Set(pagedStores(find))).toEqual(new Set(['a', 'b', 1]));
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('resumes in the saved partition', async () => {
|
|
137
|
+
{
|
|
138
|
+
await using context = await openContext(factory, storageVersion, storePlan());
|
|
139
|
+
// Partition 'a' has 3 documents; the 4th saved row is in partition 'b', after 'missing' was skipped.
|
|
140
|
+
await interruptSnapshot(context, 4);
|
|
141
|
+
}
|
|
142
|
+
await using context = await openContext(factory, storageVersion, storePlan(), true);
|
|
143
|
+
using find = vi.spyOn(mongo.Collection.prototype, 'find');
|
|
144
|
+
await context.replicateSnapshot();
|
|
145
|
+
expect(await replicatedIds(context)).toEqual(EXPECTED_IDS);
|
|
146
|
+
expect(pagedStores(find)).not.toContain('a');
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test.each([
|
|
150
|
+
{ label: 'a changed fingerprint', plan: storePlan({ fingerprint: 'test-v2' }) },
|
|
151
|
+
{ label: 'a missing partition ID', plan: storePlan({ ids: ['w', 'x', 'y', 'z'] }) }
|
|
152
|
+
])('restarts the table for $label', async ({ plan }) => {
|
|
153
|
+
{
|
|
154
|
+
await using context = await openContext(factory, storageVersion, storePlan());
|
|
155
|
+
await interruptSnapshot(context, 4);
|
|
156
|
+
}
|
|
157
|
+
await using context = await openContext(factory, storageVersion, plan, true);
|
|
158
|
+
using find = vi.spyOn(mongo.Collection.prototype, 'find');
|
|
159
|
+
await context.replicateSnapshot();
|
|
160
|
+
expect(await replicatedIds(context)).toEqual(EXPECTED_IDS);
|
|
161
|
+
expect(pagedStores(find)).toContain('a');
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test('stops upper-bound lookups after the first timeout', async () => {
|
|
165
|
+
await using context = await openContext(factory, storageVersion, storePlan());
|
|
166
|
+
const findOneSource = mongo.Collection.prototype.findOne;
|
|
167
|
+
using findOne = vi.spyOn(mongo.Collection.prototype, 'findOne').mockImplementation(function (
|
|
168
|
+
this: mongo.Collection,
|
|
169
|
+
...args: any[]
|
|
170
|
+
) {
|
|
171
|
+
if (this.collectionName == 'documents') {
|
|
172
|
+
return Promise.reject(new mongo.MongoOperationTimeoutError('lookup timed out'));
|
|
173
|
+
}
|
|
174
|
+
return (findOneSource as any).apply(this, args);
|
|
175
|
+
});
|
|
176
|
+
await context.replicateSnapshot();
|
|
177
|
+
expect(await replicatedIds(context)).toEqual(EXPECTED_IDS);
|
|
178
|
+
expect(sourceCalls(findOne)).toHaveLength(1);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test.each([{ countFails: false }, { countFails: true }])(
|
|
182
|
+
'sums partition counts from their estimate filters: %j',
|
|
183
|
+
async ({ countFails }) => {
|
|
184
|
+
await using context = await openContext(factory, storageVersion, storePlan());
|
|
185
|
+
const countSource = mongo.Collection.prototype.countDocuments;
|
|
186
|
+
let failNext = countFails;
|
|
187
|
+
using count = vi.spyOn(mongo.Collection.prototype, 'countDocuments').mockImplementation(function (
|
|
188
|
+
this: mongo.Collection,
|
|
189
|
+
...args: any[]
|
|
190
|
+
) {
|
|
191
|
+
if (failNext && this.collectionName == 'documents') {
|
|
192
|
+
// The queued estimate becomes unknown after the first failure, then the snapshot counts again.
|
|
193
|
+
failNext = false;
|
|
194
|
+
return Promise.reject(new Error('count unavailable'));
|
|
195
|
+
}
|
|
196
|
+
return (countSource as any).apply(this, args);
|
|
197
|
+
});
|
|
198
|
+
await context.replicateSnapshot();
|
|
199
|
+
const filters = sourceCalls(count).map(([filter]) => filter);
|
|
200
|
+
const allStores = STORES.map((store) => ({ store }));
|
|
201
|
+
expect(filters).toEqual(countFails ? [allStores[0], ...allStores] : allStores);
|
|
202
|
+
}
|
|
203
|
+
);
|
|
204
|
+
});
|
|
205
|
+
});
|