@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.
Files changed (27) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/replication/MongoReplicationQueryProvider.d.ts +50 -5
  3. package/dist/replication/MongoReplicationQueryProvider.js +24 -1
  4. package/dist/replication/MongoReplicationQueryProvider.js.map +1 -1
  5. package/dist/replication/MongoSnapshotPartitionResume.d.ts +36 -0
  6. package/dist/replication/MongoSnapshotPartitionResume.js +95 -0
  7. package/dist/replication/MongoSnapshotPartitionResume.js.map +1 -0
  8. package/dist/replication/MongoSnapshotQuery.d.ts +5 -0
  9. package/dist/replication/MongoSnapshotQuery.js +15 -0
  10. package/dist/replication/MongoSnapshotQuery.js.map +1 -1
  11. package/dist/replication/MongoSnapshotter.js +144 -84
  12. package/dist/replication/MongoSnapshotter.js.map +1 -1
  13. package/dist/replication/estimateFilteredSnapshotCount.d.ts +12 -0
  14. package/dist/replication/estimateFilteredSnapshotCount.js +37 -0
  15. package/dist/replication/estimateFilteredSnapshotCount.js.map +1 -1
  16. package/package.json +5 -4
  17. package/src/replication/MongoReplicationQueryProvider.ts +73 -6
  18. package/src/replication/MongoSnapshotPartitionResume.ts +133 -0
  19. package/src/replication/MongoSnapshotQuery.ts +15 -0
  20. package/src/replication/MongoSnapshotter.ts +157 -93
  21. package/src/replication/estimateFilteredSnapshotCount.ts +43 -0
  22. package/test/src/filtering_example.test.ts +4 -2
  23. package/test/src/filtering_lifecycle.test.ts +3 -2
  24. package/test/src/partitioned_snapshot.test.ts +205 -0
  25. package/test/src/snapshot_query_provider.test.ts +26 -19
  26. package/test/src/snapshot_resume_key.test.ts +108 -0
  27. package/tsconfig.tsbuildinfo +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @powersync/service-module-mongodb
2
2
 
3
+ ## 0.23.0-dev-20261205085725
4
+
5
+ ### Minor Changes
6
+
7
+ - 12564e4: Allow MongoDB replication query providers to split a table snapshot into partitions, each paged in `_id` order and resumable. Providers implement `getSnapshotPartitions` in place of `getSnapshotFilter`. This lets a filter such as a large `$in` be read in smaller batches of values, each served efficiently by an index such as `{ store_id: 1, _id: 1 }`.
8
+
9
+ ### Patch Changes
10
+
11
+ - 2a84275: Stop paging a bounded MongoDB snapshot query once it reaches the upper bound, instead of running one more query that returns nothing. Filtered snapshots that use an upper bound on the highest matching `_id` now finish their range after the page containing that document.
12
+ - @powersync/service-core@1.31.1-dev-20261205085725
13
+
3
14
  ## 0.22.9
4
15
 
5
16
  ### Patch Changes
@@ -20,6 +20,40 @@ export interface MongoReplicationQueryProviderContext {
20
20
  */
21
21
  defaultSchema: string;
22
22
  }
23
+ /**
24
+ * One part of a table snapshot. The snapshot pages each partition in `_id` order, one partition after another.
25
+ */
26
+ export interface MongoSnapshotPartition {
27
+ /**
28
+ * Stable identifier recorded in snapshot resume keys. The snapshotter treats it as opaque, but it must be unique
29
+ * within the plan and must not contain NUL characters, since resume keys store it as a BSON field name.
30
+ */
31
+ id: string;
32
+ /**
33
+ * Find predicate selecting this partition's documents, or null to snapshot the whole collection.
34
+ * Filtered partitions use simple collation, combined with the `_id` continuation predicate.
35
+ */
36
+ filter: mongo.Filter<mongo.Document> | null;
37
+ /**
38
+ * Optional superset of `filter` that MongoDB can count from index keys alone, used for progress estimates.
39
+ */
40
+ estimateFilter?: mongo.Filter<mongo.Document>;
41
+ }
42
+ /**
43
+ * How a table snapshot is split into partitions.
44
+ *
45
+ * Together the partitions must match exactly the documents that streaming treats as selected. They should not
46
+ * overlap: overlapping partitions stay correct, because the snapshot writer skips rows it already wrote, but read the
47
+ * same documents more than once. The same sync config and source indexes must produce the same partitions, in the
48
+ * same order and with the same IDs, while a table's snapshot is in progress.
49
+ */
50
+ export interface MongoSnapshotPartitionPlan {
51
+ /**
52
+ * Identifies the partitioning, so a resumed snapshot can detect a different plan and restart the table.
53
+ */
54
+ fingerprint: string;
55
+ partitions: MongoSnapshotPartition[];
56
+ }
23
57
  /**
24
58
  * Adapts snapshot selection and the stream of source changes for one replication implementation.
25
59
  * The MongoDB module owns cursor options, namespaces, BSON parsing, large-event reassembly and durable progress.
@@ -45,13 +79,15 @@ export interface MongoReplicationQueryProvider {
45
79
  */
46
80
  openChangeStream(context: MongoReplicationStreamContext): AsyncIterableIterator<MongoReplicationStreamBatch>;
47
81
  /**
48
- * Returns an additional MongoDB find predicate for a physical source table.
49
- * Return null to snapshot without an additional filter. Snapshot selection must agree with the
82
+ * Returns the partitions to snapshot for a physical source table. Return a single partition, for example with
83
+ * {@link singleSnapshotPartition}, for one filtered or unfiltered query. Snapshot selection must agree with the
50
84
  * provider's streaming rules so both paths replicate the same set of documents.
51
- * Expressions can be supplied as { $expr: ... }. The snapshot query combines the filter with its
52
- * _id continuation predicate and uses simple collation whenever a filter is supplied.
85
+ * Expressions can be supplied as { $expr: ... }. The collection handle allows checks such as listing indexes.
53
86
  */
54
- getSnapshotFilter(table: SourceTable): mongo.Filter<mongo.Document> | null;
87
+ getSnapshotPartitions(options: {
88
+ table: SourceTable;
89
+ collection: mongo.Collection;
90
+ }): Promise<MongoSnapshotPartitionPlan>;
55
91
  }
56
92
  /**
57
93
  * Creates a provider shared by a replication attempt's change stream, snapshotter and source probes.
@@ -61,6 +97,15 @@ export type MongoReplicationQueryProviderFactory = (context: MongoReplicationQue
61
97
  * Uses the standard MongoDB reader and snapshot selection without additional filtering or event translation.
62
98
  */
63
99
  export declare const DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER: MongoReplicationQueryProvider;
100
+ /**
101
+ * A plan that snapshots the table with one query, optionally filtered.
102
+ */
103
+ export declare function singleSnapshotPartition(filter: mongo.Filter<mongo.Document> | null): MongoSnapshotPartitionPlan;
104
+ /**
105
+ * Checks the parts of a plan's contract that the snapshotter relies on: at least one partition, and unique partition
106
+ * IDs that resume keys can store as BSON field names.
107
+ */
108
+ export declare function assertSnapshotPartitionPlan(plan: MongoSnapshotPartitionPlan): void;
64
109
  /**
65
110
  * Places provider stages after namespace selection and before optional large-event splitting.
66
111
  * This lets provider stages inspect complete events; the shared reader reassembles any resulting fragments.
@@ -1,10 +1,33 @@
1
+ import { ReplicationAssertionError } from '@powersync/lib-services-framework';
1
2
  /**
2
3
  * Uses the standard MongoDB reader and snapshot selection without additional filtering or event translation.
3
4
  */
4
5
  export const DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER = {
5
- getSnapshotFilter: () => null,
6
+ getSnapshotPartitions: async () => singleSnapshotPartition(null),
6
7
  openChangeStream: ({ open }) => open({})
7
8
  };
9
+ /**
10
+ * A plan that snapshots the table with one query, optionally filtered.
11
+ */
12
+ export function singleSnapshotPartition(filter) {
13
+ return { fingerprint: 'single', partitions: [{ id: 'all', filter }] };
14
+ }
15
+ /**
16
+ * Checks the parts of a plan's contract that the snapshotter relies on: at least one partition, and unique partition
17
+ * IDs that resume keys can store as BSON field names.
18
+ */
19
+ export function assertSnapshotPartitionPlan(plan) {
20
+ if (plan.partitions.length == 0) {
21
+ throw new ReplicationAssertionError(`Snapshot partition plan ${JSON.stringify(plan.fingerprint)} has no partitions`);
22
+ }
23
+ const ids = new Set();
24
+ for (const { id } of plan.partitions) {
25
+ if (id.includes('\0') || ids.has(id)) {
26
+ throw new ReplicationAssertionError(`Snapshot partition plan ${JSON.stringify(plan.fingerprint)} has a duplicate partition ID or one containing a NUL character: ${JSON.stringify(id)}`);
27
+ }
28
+ ids.add(id);
29
+ }
30
+ }
8
31
  /**
9
32
  * Places provider stages after namespace selection and before optional large-event splitting.
10
33
  * This lets provider stages inspect complete events; the shared reader reassembles any resulting fragments.
@@ -1 +1 @@
1
- {"version":3,"file":"MongoReplicationQueryProvider.js","sourceRoot":"","sources":["../../src/replication/MongoReplicationQueryProvider.ts"],"names":[],"mappings":"AAgEA;;GAEG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAAkC;IACrF,iBAAiB,EAAE,GAAG,EAAE,CAAC,IAAI;IAC7B,gBAAgB,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;CACzC,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,8BAA8B,CAAC,OAiB9C;IACC,MAAM,QAAQ,GAAqB;QACjC,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE;QACxC,EAAE,MAAM,EAAE,OAAO,CAAC,cAAc,EAAE;QAClC,GAAG,OAAO,CAAC,cAAc;KAC1B,CAAC;IAEF,IAAI,OAAO,CAAC,sBAAsB,EAAE,CAAC;QACnC,QAAQ,CAAC,IAAI,CAAC,EAAE,4BAA4B,EAAE,EAAE,EAAE,CAAC,CAAC;IACtD,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC"}
1
+ {"version":3,"file":"MongoReplicationQueryProvider.js","sourceRoot":"","sources":["../../src/replication/MongoReplicationQueryProvider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAsG9E;;GAEG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAAkC;IACrF,qBAAqB,EAAE,KAAK,IAAI,EAAE,CAAC,uBAAuB,CAAC,IAAI,CAAC;IAChE,gBAAgB,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;CACzC,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,uBAAuB,CAAC,MAA2C;IACjF,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;AACxE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,2BAA2B,CAAC,IAAgC;IAC1E,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;QAChC,MAAM,IAAI,yBAAyB,CACjC,2BAA2B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,oBAAoB,CAChF,CAAC;IACJ,CAAC;IACD,MAAM,GAAG,GAAG,IAAI,GAAG,EAAU,CAAC;IAC9B,KAAK,MAAM,EAAE,EAAE,EAAE,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;QACrC,IAAI,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;YACrC,MAAM,IAAI,yBAAyB,CACjC,2BAA2B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,oEAAoE,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,EAAE,CACpJ,CAAC;QACJ,CAAC;QACD,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,8BAA8B,CAAC,OAiB9C;IACC,MAAM,QAAQ,GAAqB;QACjC,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE;QACxC,EAAE,MAAM,EAAE,OAAO,CAAC,cAAc,EAAE;QAClC,GAAG,OAAO,CAAC,cAAc;KAC1B,CAAC;IAEF,IAAI,OAAO,CAAC,sBAAsB,EAAE,CAAC;QACnC,QAAQ,CAAC,IAAI,CAAC,EAAE,4BAA4B,EAAE,EAAE,EAAE,CAAC,CAAC;IACtD,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,36 @@
1
+ import type { MongoSnapshotPartitionPlan } from './MongoReplicationQueryProvider.js';
2
+ /**
3
+ * Progress of one started partition: finished, or the serialized `{ _id }` of its last copied document, as accepted by
4
+ * `ChunkedSnapshotQuery`.
5
+ */
6
+ export type SnapshotPartitionProgress = {
7
+ done: true;
8
+ } | {
9
+ lastKey: Uint8Array;
10
+ };
11
+ /**
12
+ * Where a table snapshot continues.
13
+ */
14
+ export interface SnapshotResumeState {
15
+ /**
16
+ * Progress by partition ID. Partitions without an entry have not started.
17
+ */
18
+ progress: Map<string, SnapshotPartitionProgress>;
19
+ /**
20
+ * Why saved progress could not be used with the current plan. The table snapshot then restarts.
21
+ */
22
+ discardedReason?: string;
23
+ }
24
+ /**
25
+ * Finds where to continue a table snapshot from its saved key.
26
+ *
27
+ * Single-partition plans save `{ _id }`, the format used before partitions. Multi-partition plans save a
28
+ * `PartitionedResumeKey`. Progress saved under a different plan, or that doesn't match the plan's partitions, is
29
+ * discarded instead of misread.
30
+ */
31
+ export declare function resolveSnapshotResumeState(plan: MongoSnapshotPartitionPlan, savedKey: Uint8Array | null | undefined): SnapshotResumeState;
32
+ /**
33
+ * Builds the saved key from the progress of every started partition. Single-partition plans keep the `{ _id }` of the
34
+ * last copied document; others save a `PartitionedResumeKey`.
35
+ */
36
+ export declare function encodeSnapshotResumeKey(plan: MongoSnapshotPartitionPlan, progress: ReadonlyMap<string, SnapshotPartitionProgress>): Uint8Array;
@@ -0,0 +1,95 @@
1
+ import { ReplicationAssertionError } from '@powersync/lib-services-framework';
2
+ import { bson } from '@powersync/service-core';
3
+ import { z } from 'zod';
4
+ /**
5
+ * Saved progress of one partition: either the `_id` of its last copied document, or `done`.
6
+ *
7
+ * This uses zod rather than ts-codec, which the rest of the module uses: ts-codec objects drop unknown fields and its
8
+ * unions take the first branch that decodes, so an entry with both fields would silently read as one of them. Strict
9
+ * zod objects in a union accept exactly one shape. `_id` may be `null`, which MongoDB allows, but not missing.
10
+ */
11
+ const PartitionProgress = z.union([
12
+ z.strictObject({ _id: z.unknown().refine((id) => id !== undefined) }),
13
+ z.strictObject({ done: z.literal(true) })
14
+ ]);
15
+ /**
16
+ * Saved progress of a multi-partition snapshot.
17
+ *
18
+ * `partitions` maps the ID of every started partition to its progress; partitions without an entry have not started.
19
+ * Progress doesn't depend on partition order, so the same shape works whether partitions are copied one at a time, as
20
+ * now, or concurrently.
21
+ *
22
+ * There is deliberately no top-level `_id`: a service version that predates partitions reads `lastKey._id`, and
23
+ * without it pages the whole table again instead of resuming after one partition's `_id`.
24
+ */
25
+ const PartitionedResumeKey = z.strictObject({
26
+ fingerprint: z.string(),
27
+ partitions: z.record(z.string(), PartitionProgress)
28
+ });
29
+ /**
30
+ * Finds where to continue a table snapshot from its saved key.
31
+ *
32
+ * Single-partition plans save `{ _id }`, the format used before partitions. Multi-partition plans save a
33
+ * `PartitionedResumeKey`. Progress saved under a different plan, or that doesn't match the plan's partitions, is
34
+ * discarded instead of misread.
35
+ */
36
+ export function resolveSnapshotResumeState(plan, savedKey) {
37
+ if (savedKey == null) {
38
+ return { progress: new Map() };
39
+ }
40
+ const restart = (discardedReason) => ({ progress: new Map(), discardedReason });
41
+ const saved = bson.deserialize(savedKey, { useBigInt64: true });
42
+ const isIdKey = Object.keys(saved).length == 1 && '_id' in saved;
43
+ if (plan.partitions.length == 1) {
44
+ return isIdKey
45
+ ? { progress: new Map([[plan.partitions[0].id, { lastKey: savedKey }]]) }
46
+ : restart('progress was saved for a partitioned snapshot, but the snapshot is no longer partitioned');
47
+ }
48
+ if (isIdKey) {
49
+ return restart(`progress was saved without partitions, but the snapshot uses partition plan ${JSON.stringify(plan.fingerprint)}`);
50
+ }
51
+ const parsed = PartitionedResumeKey.safeParse(saved);
52
+ if (!parsed.success) {
53
+ return restart('saved partition progress has an unsupported shape');
54
+ }
55
+ const key = parsed.data;
56
+ if (key.fingerprint !== plan.fingerprint) {
57
+ return restart(`progress was saved for partition plan ${JSON.stringify(key.fingerprint)}, but the snapshot uses ${JSON.stringify(plan.fingerprint)}`);
58
+ }
59
+ const ids = new Set(plan.partitions.map((partition) => partition.id));
60
+ // Re-read the _id values without promoting them, so resumed keys keep their exact BSON types.
61
+ const exact = bson.deserialize(savedKey, { promoteValues: false }).partitions;
62
+ const progress = new Map();
63
+ for (const [id, entry] of Object.entries(key.partitions)) {
64
+ if (!ids.has(id)) {
65
+ return restart(`saved progress names partition ${JSON.stringify(id)}, which partition plan ${JSON.stringify(key.fingerprint)} does not have`);
66
+ }
67
+ progress.set(id, 'done' in entry ? { done: true } : { lastKey: bson.serialize({ _id: exact[id]._id }) });
68
+ }
69
+ return { progress };
70
+ }
71
+ /**
72
+ * Builds the saved key from the progress of every started partition. Single-partition plans keep the `{ _id }` of the
73
+ * last copied document; others save a `PartitionedResumeKey`.
74
+ */
75
+ export function encodeSnapshotResumeKey(plan, progress) {
76
+ if (plan.partitions.length == 1) {
77
+ const only = progress.get(plan.partitions[0].id);
78
+ if (only == null || !('lastKey' in only)) {
79
+ throw new ReplicationAssertionError('A single-partition snapshot saves progress only after copying a page');
80
+ }
81
+ return only.lastKey;
82
+ }
83
+ const partitions = {};
84
+ for (const [id, entry] of progress) {
85
+ // The key must keep each _id's exact BSON type, as the single-partition key does by storing the raw bytes. A
86
+ // default round trip through JS values can change it, for example writing the double 1.0 back as the int32 1.
87
+ // promoteValues: false keeps every value in its BSON wrapper (Double, Int32, Long, ...), so it is serialized
88
+ // again unchanged.
89
+ partitions[id] =
90
+ 'lastKey' in entry ? { _id: bson.deserialize(entry.lastKey, { promoteValues: false })._id } : { done: true };
91
+ }
92
+ const key = { fingerprint: plan.fingerprint, partitions };
93
+ return bson.serialize(key);
94
+ }
95
+ //# sourceMappingURL=MongoSnapshotPartitionResume.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MongoSnapshotPartitionResume.js","sourceRoot":"","sources":["../../src/replication/MongoSnapshotPartitionResume.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAuBxB;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC;IAChC,CAAC,CAAC,YAAY,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,KAAK,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AAE,IAAI,CAAC,WAAW,EAAE,UAAU,EAAE,CAAC;IAChF,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC"}
@@ -12,6 +12,11 @@ export declare class ChunkedSnapshotQuery implements AsyncDisposable {
12
12
  private batchSize;
13
13
  private readonly filter;
14
14
  private readonly upperKey;
15
+ /**
16
+ * Serialized `{ _id: upperKey }`. Reading a document with this key means the bounded range is complete.
17
+ */
18
+ private readonly upperKeyBuffer;
19
+ private finished;
15
20
  constructor(options: {
16
21
  collection: mongo.Collection;
17
22
  batchSize: number;
@@ -15,6 +15,11 @@ export class ChunkedSnapshotQuery {
15
15
  batchSize;
16
16
  filter;
17
17
  upperKey;
18
+ /**
19
+ * Serialized `{ _id: upperKey }`. Reading a document with this key means the bounded range is complete.
20
+ */
21
+ upperKeyBuffer;
22
+ finished = false;
18
23
  constructor(options) {
19
24
  this.lastKey = options.key ? bson.deserialize(options.key, { useBigInt64: true })._id : null;
20
25
  this.lastCursor = null;
@@ -22,8 +27,13 @@ export class ChunkedSnapshotQuery {
22
27
  this.batchSize = options.batchSize;
23
28
  this.filter = options.filter ?? null;
24
29
  this.upperKey = options.upperKey;
30
+ this.upperKeyBuffer =
31
+ options.upperKey === undefined ? null : Buffer.from(bson.serialize({ _id: options.upperKey }));
25
32
  }
26
33
  async nextChunk() {
34
+ if (this.finished) {
35
+ return { docs: [], lastKey: null, bytes: 0 };
36
+ }
27
37
  let cursor = this.lastCursor;
28
38
  let newCursor = false;
29
39
  if (cursor == null || cursor.closed) {
@@ -83,6 +93,11 @@ export class ChunkedSnapshotQuery {
83
93
  const lastDoc = docBatch[docBatch.length - 1];
84
94
  const { id: lastKey, idBuffer } = parseDocumentId(lastDoc);
85
95
  this.lastKey = lastKey;
96
+ // The upper bound is the last matching document, so reaching it saves a final query that would return nothing.
97
+ // If its re-serialized type differs from the source bytes, the final query still ends the range.
98
+ if (this.upperKeyBuffer?.equals(idBuffer)) {
99
+ this.finished = true;
100
+ }
86
101
  return { docs: docBatch, lastKey: idBuffer, bytes };
87
102
  }
88
103
  async [Symbol.asyncDispose]() {
@@ -1 +1 @@
1
- {"version":3,"file":"MongoSnapshotQuery.js","sourceRoot":"","sources":["../../src/replication/MongoSnapshotQuery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE;;;;;GAKG;AACH,MAAM,OAAO,oBAAoB;IAC/B,OAAO,GAAQ,IAAI,CAAC;IACZ,UAAU,GAA4B,IAAI,CAAC;IAC3C,UAAU,CAAmB;IAC7B,SAAS,CAAS;IACT,MAAM,CAAsC;IAC5C,QAAQ,CAAU;IAEnC,YAAmB,OAMlB;QACC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;QAC7F,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACrC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC;QACrC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,SAAS;QAGb,IAAI,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,IAAI,SAAS,GAAG,KAAK,CAAC;QACtB,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC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,UAAU,GAAG,MAAM,CAAC;QACzB,IAAI,QAAQ,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;YACzB,MAAM,IAAI,yBAAyB,CAAC,yEAAyE,CAAC,CAAC;QACjH,CAAC;QACD,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC9C,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;QAC3D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,+GAA+G;QAC/G,iGAAiG;QACjG,IAAI,IAAI,CAAC,cAAc,EAAE,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC1C,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACvB,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC;QACzB,MAAM,IAAI,CAAC,UAAU,EAAE,KAAK,EAAE,CAAC;IACjC,CAAC;CACF"}
@@ -8,10 +8,11 @@ import { PostImagesOption } from '../types/types.js';
8
8
  import { escapeRegExp } from '../utils.js';
9
9
  import { parseDocumentId } from './bufferToSqlite.js';
10
10
  import { createCheckpointImplementation } from './checkpoints/create-checkpoint-implementation.js';
11
- import { estimateFilteredSnapshotCount } from './estimateFilteredSnapshotCount.js';
11
+ import { estimateFilteredSnapshotCount, estimatePartitionedSnapshotCount } from './estimateFilteredSnapshotCount.js';
12
12
  import { getMongoRelation } from './MongoRelation.js';
13
- import { DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER } from './MongoReplicationQueryProvider.js';
13
+ import { assertSnapshotPartitionPlan, DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER } from './MongoReplicationQueryProvider.js';
14
14
  import { openMongoReplicationStream } from './MongoReplicationStream.js';
15
+ import { encodeSnapshotResumeKey, resolveSnapshotResumeState } from './MongoSnapshotPartitionResume.js';
15
16
  import { ChunkedSnapshotQuery } from './MongoSnapshotQuery.js';
16
17
  import { CHECKPOINTS_COLLECTION, detectDocumentDb } from './replication-utils.js';
17
18
  import { DirectSourceRowConverter } from './SourceRowConverter.js';
@@ -410,41 +411,39 @@ export class MongoSnapshotter {
410
411
  const rowsReplicatedMetric = this.metrics.getCounter(ReplicationMetric.ROWS_REPLICATED);
411
412
  const bytesReplicatedMetric = this.metrics.getCounter(ReplicationMetric.DATA_REPLICATED_BYTES);
412
413
  const chunksReplicatedMetric = this.metrics.getCounter(ReplicationMetric.CHUNKS_REPLICATED);
413
- const filter = this.queryProvider.getSnapshotFilter(table);
414
414
  const collection = this.client.db(table.schema).collection(table.name);
415
- const upperBound = filter != null && !this.isDocumentDb && batch.resumeFromLsn != null
416
- ? await this.findSnapshotUpperBound(collection, filter, batch.resumeFromLsn)
417
- : { kind: 'unavailable' };
418
- if (upperBound.kind === 'empty') {
419
- // The lookup saw no matches in a majority read at least as recent as the resume LSN.
420
- // The caller still marks the snapshot complete, and the change stream handles later matches.
421
- this.logger.info(`Skipping replication of ${table.qualifiedName} - no documents match the snapshot filter`);
422
- return;
423
- }
424
- // Reuse known filtered estimates to avoid repeating an expensive count and sample. Unknown totals
425
- // (-1) can also represent uninitialized progress, so retry them. Unfiltered metadata counts are cheap
426
- // and refreshed before copying rows.
427
- const previousEstimate = table.snapshotStatus?.totalEstimatedCount ?? -1;
428
- const totalEstimatedCount = filter != null && previousEstimate >= 0 ? previousEstimate : await this.estimatedCountNumber(table, filter);
415
+ const plan = await this.queryProvider.getSnapshotPartitions({ table, collection });
416
+ assertSnapshotPartitionPlan(plan);
417
+ const partitionCount = plan.partitions.length;
418
+ const resume = resolveSnapshotResumeState(plan, table.snapshotStatus?.lastKey);
419
+ // Progress by partition ID, updated as pages are copied and partitions finish, and saved as the resume key.
420
+ const progress = resume.progress;
429
421
  let at = table.snapshotStatus?.replicatedCount ?? 0;
422
+ if (resume.discardedReason != null) {
423
+ // Rows already copied are skipped by the snapshot writer, so restarting the table only costs reads.
424
+ this.logger.warn(`Restarting snapshot of ${table.qualifiedName}: ${resume.discardedReason}`);
425
+ at = 0;
426
+ }
430
427
  // When supported by the storage batch, pass raw BSON instead of decoding rows here.
431
428
  const saveBson = batch.prepareUndecodedSave?.('bson');
432
- await using query = new ChunkedSnapshotQuery({
433
- collection,
434
- key: table.snapshotStatus?.lastKey,
435
- batchSize: this.snapshotChunkLength,
436
- filter,
437
- upperKey: upperBound.kind === 'found' ? upperBound.key : undefined
438
- });
439
- if (query.lastKey != null) {
440
- this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()} - resuming at _id > ${query.lastKey}`);
441
- }
442
- else {
443
- this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()}`);
444
- }
429
+ // Upper-bound lookups need a causal read at the resume LSN. After one times out, page the rest without bounds.
430
+ let lookupsAvailable = !this.isDocumentDb && batch.resumeFromLsn != null;
431
+ // Reuse known filtered estimates to avoid repeating expensive counts. Unknown totals (-1) can also represent
432
+ // uninitialized progress, so retry them. Unfiltered metadata counts are cheap and refreshed before copying rows.
433
+ const filtered = plan.partitions.some((partition) => partition.filter != null);
434
+ const previousEstimate = table.snapshotStatus?.totalEstimatedCount ?? -1;
435
+ let totalEstimatedCount = filtered && previousEstimate >= 0 ? previousEstimate : null;
436
+ let partitionIndex = 0;
437
+ let announced = false;
445
438
  let lastProgressAt = performance.now();
446
- let pendingKey = null;
447
439
  let pendingProgress = false;
440
+ // Uses the current counts rather than the persisted status, which can lag behind a restart or a new estimate.
441
+ // The final progress is persisted after the loop, when the index is past the last partition.
442
+ const describeProgress = () => {
443
+ const total = totalEstimatedCount == null || totalEstimatedCount < 0 ? '?' : `~${totalEstimatedCount}`;
444
+ const position = partitionCount > 1 ? ` partition ${Math.min(partitionIndex + 1, partitionCount)}/${partitionCount}` : '';
445
+ return `${at}/${total}${position}`;
446
+ };
448
447
  const persistProgress = async () => {
449
448
  if (!pendingProgress) {
450
449
  return;
@@ -453,72 +452,123 @@ export class MongoSnapshotter {
453
452
  // keep storage work bounded between these less frequent durable barriers.
454
453
  await batch.flush();
455
454
  table = await batch.updateTableProgress(table, {
456
- lastKey: pendingKey,
455
+ lastKey: encodeSnapshotResumeKey(plan, progress),
457
456
  replicatedCount: at,
458
- totalEstimatedCount
457
+ totalEstimatedCount: totalEstimatedCount ?? -1
459
458
  });
460
459
  const now = performance.now();
461
- this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()} in ${(now - lastProgressAt).toFixed(0)}ms`);
460
+ this.logger.info(`Replicating ${table.qualifiedName} ${describeProgress()} in ${(now - lastProgressAt).toFixed(0)}ms`);
462
461
  lastProgressAt = now;
463
462
  pendingProgress = false;
464
463
  };
465
- let nextChunkPromise = query.nextChunk();
466
- try {
467
- while (true) {
468
- const { docs: docBatch, lastKey, bytes: chunkBytes } = await nextChunkPromise;
469
- if (docBatch.length == 0) {
470
- // No more data - stop iterating
471
- break;
472
- }
473
- bytesReplicatedMetric.add(chunkBytes);
474
- chunksReplicatedMetric.add(1);
475
- if (this.abortSignal.aborted) {
476
- // Preserve the last complete page on graceful shutdown, even if the
477
- // persistence interval has not elapsed. Never advance into this page.
478
- await persistProgress();
479
- throw new ReplicationAbortedError(`Aborted initial replication`, this.abortSignal.reason);
480
- }
481
- // Pre-fetch next batch, so that we can read and write concurrently
482
- nextChunkPromise = query.nextChunk();
483
- for (const buffer of docBatch) {
484
- // These auto-flush when the batch reaches its size limit
485
- if (saveBson != null) {
486
- await saveBson({
464
+ const finishPartition = async (id) => {
465
+ // A single-partition table is marked complete instead.
466
+ if (partitionCount == 1) {
467
+ return;
468
+ }
469
+ progress.set(id, { done: true });
470
+ pendingProgress = true;
471
+ if (performance.now() - lastProgressAt >= this.snapshotProgressIntervalMs) {
472
+ await persistProgress();
473
+ }
474
+ };
475
+ for (; partitionIndex < partitionCount; partitionIndex++) {
476
+ const partition = plan.partitions[partitionIndex];
477
+ const saved = progress.get(partition.id);
478
+ if (saved != null && 'done' in saved) {
479
+ continue;
480
+ }
481
+ const upperBound = partition.filter != null && lookupsAvailable
482
+ ? await this.findSnapshotUpperBound(collection, partition.filter, batch.resumeFromLsn)
483
+ : { kind: 'unavailable' };
484
+ if (upperBound.kind === 'empty') {
485
+ // The lookup saw no matches in a majority read at least as recent as the resume LSN.
486
+ // The change stream handles later matches, and the caller still marks the snapshot complete.
487
+ await finishPartition(partition.id);
488
+ continue;
489
+ }
490
+ if (upperBound.kind === 'unavailable' && partition.filter != null) {
491
+ lookupsAvailable = false;
492
+ }
493
+ // Count only once there is something to copy, so an empty single-partition table skips the count.
494
+ totalEstimatedCount ??= await this.estimatedCountNumber(table, plan);
495
+ const key = saved != null && 'lastKey' in saved ? saved.lastKey : null;
496
+ await using query = new ChunkedSnapshotQuery({
497
+ collection,
498
+ key,
499
+ batchSize: this.snapshotChunkLength,
500
+ filter: partition.filter,
501
+ upperKey: upperBound.kind === 'found' ? upperBound.key : undefined
502
+ });
503
+ if (!announced) {
504
+ // Log the start once per table, at the first partition with documents to copy.
505
+ this.logger.info(`Replicating ${table.qualifiedName} ${describeProgress()}${key != null ? ` - resuming at _id > ${query.lastKey}` : ''}`);
506
+ announced = true;
507
+ }
508
+ let nextChunkPromise = query.nextChunk();
509
+ try {
510
+ while (true) {
511
+ const { docs: docBatch, lastKey, bytes: chunkBytes } = await nextChunkPromise;
512
+ if (docBatch.length == 0) {
513
+ // No more data in this partition - stop iterating
514
+ break;
515
+ }
516
+ bytesReplicatedMetric.add(chunkBytes);
517
+ chunksReplicatedMetric.add(1);
518
+ if (this.abortSignal.aborted) {
519
+ // Preserve the last complete page on graceful shutdown, even if the
520
+ // persistence interval has not elapsed. Never advance into this page.
521
+ await persistProgress();
522
+ throw new ReplicationAbortedError(`Aborted initial replication`, this.abortSignal.reason);
523
+ }
524
+ // Pre-fetch next batch, so that we can read and write concurrently
525
+ nextChunkPromise = query.nextChunk();
526
+ for (const buffer of docBatch) {
527
+ // These auto-flush when the batch reaches its size limit
528
+ if (saveBson != null) {
529
+ await saveBson({
530
+ tag: SaveOperationTag.INSERT,
531
+ sourceTable: table,
532
+ after: buffer,
533
+ afterReplicaId: this.sourceRowConverter.rawToReplica(buffer)
534
+ });
535
+ continue;
536
+ }
537
+ const { row, replicaId } = this.sourceRowConverter.rawToSqliteRow(buffer);
538
+ await batch.save({
487
539
  tag: SaveOperationTag.INSERT,
488
540
  sourceTable: table,
489
- after: buffer,
490
- afterReplicaId: this.sourceRowConverter.rawToReplica(buffer)
541
+ before: undefined,
542
+ beforeReplicaId: undefined,
543
+ after: row,
544
+ afterReplicaId: replicaId
491
545
  });
492
- continue;
493
546
  }
494
- const { row, replicaId } = this.sourceRowConverter.rawToSqliteRow(buffer);
495
- await batch.save({
496
- tag: SaveOperationTag.INSERT,
497
- sourceTable: table,
498
- before: undefined,
499
- beforeReplicaId: undefined,
500
- after: row,
501
- afterReplicaId: replicaId
502
- });
503
- }
504
- at += docBatch.length;
505
- // Activity counters track processed source rows; the table cursor and
506
- // progress log advance only at a durable persistence boundary.
507
- rowsReplicatedMetric.add(docBatch.length);
508
- pendingKey = lastKey;
509
- pendingProgress = true;
510
- if (performance.now() - lastProgressAt >= this.snapshotProgressIntervalMs || this.abortSignal.aborted) {
511
- await persistProgress();
547
+ at += docBatch.length;
548
+ // Activity counters track processed source rows; the table cursor and
549
+ // progress log advance only at a durable persistence boundary.
550
+ rowsReplicatedMetric.add(docBatch.length);
551
+ // A non-empty chunk always has a last key.
552
+ progress.set(partition.id, { lastKey: lastKey });
553
+ pendingProgress = true;
554
+ if (performance.now() - lastProgressAt >= this.snapshotProgressIntervalMs || this.abortSignal.aborted) {
555
+ await persistProgress();
556
+ }
557
+ this.touch();
512
558
  }
513
- this.touch();
514
559
  }
515
- // A short snapshot must persist its final page too, before table completion.
516
- await persistProgress();
560
+ finally {
561
+ // In case the loop was interrupted, make sure we await the last promise.
562
+ await nextChunkPromise.catch(() => { });
563
+ }
564
+ await finishPartition(partition.id);
517
565
  }
518
- finally {
519
- // In case the loop was interrupted, make sure we await the last promise.
520
- await nextChunkPromise.catch(() => { });
566
+ if (!announced) {
567
+ // Every remaining partition was already finished or skipped by its upper-bound lookup.
568
+ this.logger.info(`Skipping replication of ${table.qualifiedName} - no ${resume.progress.size > 0 ? 'remaining ' : ''}documents match the snapshot filter`);
521
569
  }
570
+ // A short snapshot must persist its final page too, before table completion.
571
+ await persistProgress();
522
572
  }
523
573
  async handleRelation(batch, descriptor, options) {
524
574
  if (options.collectionInfo != null) {
@@ -543,8 +593,18 @@ export class MongoSnapshotter {
543
593
  }
544
594
  return result.tables;
545
595
  }
546
- async estimatedCountNumber(table, filter = this.queryProvider.getSnapshotFilter(table)) {
596
+ async estimatedCountNumber(table, plan) {
547
597
  const collection = this.client.db(table.schema).collection(table.name);
598
+ plan ??= await this.queryProvider.getSnapshotPartitions({ table, collection });
599
+ if (plan.partitions.length > 1) {
600
+ return await estimatePartitionedSnapshotCount({
601
+ collection,
602
+ partitions: plan.partitions,
603
+ signal: this.abortSignal,
604
+ logger: this.logger
605
+ });
606
+ }
607
+ const filter = plan.partitions[0]?.filter ?? null;
548
608
  if (filter != null) {
549
609
  return await estimateFilteredSnapshotCount({
550
610
  collection,