@powersync/service-module-mongodb 0.21.1 → 0.22.0

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 (108) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/benchmarks/env.ts +11 -0
  3. package/benchmarks/replication_branch_throughput.benchmark.ts +240 -0
  4. package/ci/test-connection.yaml +12 -0
  5. package/dist/api/MongoRouteAPIAdapter.d.ts +6 -0
  6. package/dist/api/MongoRouteAPIAdapter.js +33 -4
  7. package/dist/api/MongoRouteAPIAdapter.js.map +1 -1
  8. package/dist/api/infer-collection-schema.d.ts +5 -0
  9. package/dist/api/infer-collection-schema.js +24 -0
  10. package/dist/api/infer-collection-schema.js.map +1 -1
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.js +1 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/module/MongoModule.d.ts +1 -2
  15. package/dist/module/MongoModule.js +1 -1
  16. package/dist/module/MongoModule.js.map +1 -1
  17. package/dist/replication/ChangeStream.d.ts +13 -3
  18. package/dist/replication/ChangeStream.js +130 -196
  19. package/dist/replication/ChangeStream.js.map +1 -1
  20. package/dist/replication/ChangeStreamReplicationJob.d.ts +4 -1
  21. package/dist/replication/ChangeStreamReplicationJob.js +19 -8
  22. package/dist/replication/ChangeStreamReplicationJob.js.map +1 -1
  23. package/dist/replication/ChangeStreamReplicator.d.ts +4 -0
  24. package/dist/replication/ChangeStreamReplicator.js +6 -0
  25. package/dist/replication/ChangeStreamReplicator.js.map +1 -1
  26. package/dist/replication/MongoRelation.js +5 -2
  27. package/dist/replication/MongoRelation.js.map +1 -1
  28. package/dist/replication/MongoReplicationQueryProvider.d.ts +85 -0
  29. package/dist/replication/MongoReplicationQueryProvider.js +23 -0
  30. package/dist/replication/MongoReplicationQueryProvider.js.map +1 -0
  31. package/dist/replication/MongoReplicationStream.d.ts +74 -0
  32. package/dist/replication/MongoReplicationStream.js +228 -0
  33. package/dist/replication/MongoReplicationStream.js.map +1 -0
  34. package/dist/replication/MongoReplicationStreamTypes.d.ts +157 -0
  35. package/dist/replication/MongoReplicationStreamTypes.js +19 -0
  36. package/dist/replication/MongoReplicationStreamTypes.js.map +1 -0
  37. package/dist/replication/MongoSnapshotQuery.d.ts +2 -0
  38. package/dist/replication/MongoSnapshotQuery.js +12 -2
  39. package/dist/replication/MongoSnapshotQuery.js.map +1 -1
  40. package/dist/replication/MongoSnapshotter.d.ts +7 -2
  41. package/dist/replication/MongoSnapshotter.js +90 -88
  42. package/dist/replication/MongoSnapshotter.js.map +1 -1
  43. package/dist/replication/RawChangeStream.d.ts +1 -1
  44. package/dist/replication/RawChangeStream.js +1 -1
  45. package/dist/replication/RawChangeStream.js.map +1 -1
  46. package/dist/replication/SourceRowConverter.d.ts +1 -0
  47. package/dist/replication/SourceRowConverter.js +4 -2
  48. package/dist/replication/SourceRowConverter.js.map +1 -1
  49. package/dist/replication/bufferToSqlite.d.ts +3 -1
  50. package/dist/replication/bufferToSqlite.js +35 -23
  51. package/dist/replication/bufferToSqlite.js.map +1 -1
  52. package/dist/replication/estimateFilteredSnapshotCount.d.ts +12 -0
  53. package/dist/replication/estimateFilteredSnapshotCount.js +79 -0
  54. package/dist/replication/estimateFilteredSnapshotCount.js.map +1 -0
  55. package/dist/replication/replication-index.d.ts +7 -0
  56. package/dist/replication/replication-index.js +7 -0
  57. package/dist/replication/replication-index.js.map +1 -1
  58. package/dist/test-utils/ChangeStreamTestContext.d.ts +131 -0
  59. package/dist/test-utils/ChangeStreamTestContext.js +390 -0
  60. package/dist/test-utils/ChangeStreamTestContext.js.map +1 -0
  61. package/dist/test-utils/test-utils-index.d.ts +1 -0
  62. package/dist/test-utils/test-utils-index.js +2 -0
  63. package/dist/test-utils/test-utils-index.js.map +1 -0
  64. package/package.json +11 -10
  65. package/src/api/MongoRouteAPIAdapter.ts +38 -4
  66. package/src/api/infer-collection-schema.ts +26 -0
  67. package/src/index.ts +1 -0
  68. package/src/module/MongoModule.ts +2 -3
  69. package/src/replication/ChangeStream.ts +143 -226
  70. package/src/replication/ChangeStreamReplicationJob.ts +21 -9
  71. package/src/replication/ChangeStreamReplicator.ts +9 -0
  72. package/src/replication/MongoRelation.ts +8 -1
  73. package/src/replication/MongoReplicationQueryProvider.ts +106 -0
  74. package/src/replication/MongoReplicationStream.ts +314 -0
  75. package/src/replication/MongoReplicationStreamTypes.ts +169 -0
  76. package/src/replication/MongoSnapshotQuery.ts +19 -3
  77. package/src/replication/MongoSnapshotter.ts +101 -92
  78. package/src/replication/RawChangeStream.ts +2 -2
  79. package/src/replication/SourceRowConverter.ts +4 -2
  80. package/src/replication/bufferToSqlite.ts +43 -23
  81. package/src/replication/estimateFilteredSnapshotCount.ts +93 -0
  82. package/src/replication/replication-index.ts +7 -0
  83. package/src/test-utils/ChangeStreamTestContext.ts +520 -0
  84. package/src/test-utils/test-utils-index.ts +1 -0
  85. package/test/src/buffer_to_sqlite.test.ts +9 -0
  86. package/test/src/change_event_memory.test.ts +33 -0
  87. package/test/src/change_stream.test.ts +3 -3
  88. package/test/src/change_stream_abort.test.ts +110 -0
  89. package/test/src/change_stream_test_setup.ts +38 -0
  90. package/test/src/chunked_snapshot.test.ts +3 -3
  91. package/test/src/documentdb_mode.test.ts +3 -3
  92. package/test/src/filtering_example.test.ts +65 -0
  93. package/test/src/filtering_lifecycle.test.ts +101 -0
  94. package/test/src/query_provider_availability.test.ts +77 -0
  95. package/test/src/query_provider_diagnostics.test.ts +55 -0
  96. package/test/src/replication_stream.test.ts +688 -0
  97. package/test/src/resume.test.ts +10 -4
  98. package/test/src/resuming_snapshots.test.ts +3 -3
  99. package/test/src/schema.test.ts +62 -19
  100. package/test/src/slow_tests.test.ts +3 -3
  101. package/test/src/snapshot_count.test.ts +146 -0
  102. package/test/src/snapshot_count_integration.test.ts +70 -0
  103. package/test/src/snapshot_query_provider.test.ts +122 -0
  104. package/test/src/stream_progress.test.ts +334 -0
  105. package/test/tsconfig.json +2 -2
  106. package/tsconfig.tsbuildinfo +1 -1
  107. package/vitest.benchmark.config.ts +15 -0
  108. package/test/src/change_stream_utils.ts +0 -375
@@ -3,18 +3,22 @@ import { replication } from '@powersync/service-core';
3
3
 
4
4
  import { ChangeStream, ChangeStreamInvalidatedError } from './ChangeStream.js';
5
5
  import { ConnectionManagerFactory } from './ConnectionManagerFactory.js';
6
+ import { MongoReplicationQueryProviderFactory } from './MongoReplicationQueryProvider.js';
6
7
 
7
8
  export interface ChangeStreamReplicationJobOptions extends replication.AbstractReplicationJobOptions {
8
9
  connectionFactory: ConnectionManagerFactory;
10
+ createReplicationQueryProvider?: MongoReplicationQueryProviderFactory;
9
11
  }
10
12
 
11
13
  export class ChangeStreamReplicationJob extends replication.AbstractReplicationJob {
12
- private connectionFactory: ConnectionManagerFactory;
14
+ private readonly connectionFactory: ConnectionManagerFactory;
15
+ private readonly createReplicationQueryProvider: MongoReplicationQueryProviderFactory | undefined;
13
16
  private lastStream: ChangeStream | null = null;
14
17
 
15
18
  constructor(options: ChangeStreamReplicationJobOptions) {
16
19
  super(options);
17
20
  this.connectionFactory = options.connectionFactory;
21
+ this.createReplicationQueryProvider = options.createReplicationQueryProvider;
18
22
  // We use a custom formatter to process the prefix
19
23
  this.logger = options.storage.logger;
20
24
  }
@@ -66,14 +70,22 @@ export class ChangeStreamReplicationJob extends replication.AbstractReplicationJ
66
70
  if (this.isStopped) {
67
71
  return;
68
72
  }
69
- const stream = new ChangeStream({
70
- abort_signal: this.abortController.signal,
71
- storage: this.options.storage,
72
- metrics: this.options.metrics,
73
- connections: connectionManager,
74
- keepaliveIntervalMs: connectionManager.options.heartbeat_interval_seconds * 1_000,
75
- logger: this.logger
76
- });
73
+ let stream: ChangeStream;
74
+ try {
75
+ stream = new ChangeStream({
76
+ abort_signal: this.abortController.signal,
77
+ storage: this.options.storage,
78
+ metrics: this.options.metrics,
79
+ connections: connectionManager,
80
+ keepaliveIntervalMs: connectionManager.options.heartbeat_interval_seconds * 1_000,
81
+ logger: this.logger,
82
+ createReplicationQueryProvider: this.createReplicationQueryProvider
83
+ });
84
+ } catch (error) {
85
+ // Construction can fail before ChangeStream.replicate() reports errors.
86
+ await this.storage.reportError(error);
87
+ throw error;
88
+ }
77
89
  this.lastStream = stream;
78
90
  await stream.replicate();
79
91
  } finally {
@@ -2,17 +2,25 @@ import { replication, storage } from '@powersync/service-core';
2
2
  import { MongoModule } from '../module/MongoModule.js';
3
3
  import { ChangeStreamReplicationJob } from './ChangeStreamReplicationJob.js';
4
4
  import { ConnectionManagerFactory } from './ConnectionManagerFactory.js';
5
+ import { MongoReplicationQueryProviderFactory } from './MongoReplicationQueryProvider.js';
5
6
 
6
7
  export interface ChangeStreamReplicatorOptions extends replication.AbstractReplicatorOptions {
7
8
  connectionFactory: ConnectionManagerFactory;
9
+ createReplicationQueryProvider?: MongoReplicationQueryProviderFactory;
8
10
  }
9
11
 
10
12
  export class ChangeStreamReplicator extends replication.AbstractReplicator<ChangeStreamReplicationJob> {
11
13
  private readonly connectionFactory: ConnectionManagerFactory;
14
+ private readonly createReplicationQueryProvider: MongoReplicationQueryProviderFactory | undefined;
12
15
 
13
16
  constructor(options: ChangeStreamReplicatorOptions) {
14
17
  super(options);
15
18
  this.connectionFactory = options.connectionFactory;
19
+ this.createReplicationQueryProvider = options.createReplicationQueryProvider;
20
+ }
21
+
22
+ protected get defaultSchema(): string {
23
+ return this.connectionFactory.dbConnectionConfig.database;
16
24
  }
17
25
 
18
26
  createJob(options: replication.CreateJobOptions): ChangeStreamReplicationJob {
@@ -21,6 +29,7 @@ export class ChangeStreamReplicator extends replication.AbstractReplicator<Chang
21
29
  storage: options.storage,
22
30
  metrics: this.metrics,
23
31
  connectionFactory: this.connectionFactory,
32
+ createReplicationQueryProvider: this.createReplicationQueryProvider,
24
33
  lock: options.lock,
25
34
  rateLimiter: this.rateLimiter
26
35
  });
@@ -3,11 +3,14 @@ import { storage } from '@powersync/service-core';
3
3
  import { JsonContainer } from '@powersync/service-jsonbig';
4
4
  import {
5
5
  CompatibilityContext,
6
+ CompatibilityOption,
6
7
  CustomArray,
7
8
  CustomObject,
8
9
  CustomSqliteValue,
9
10
  DateTimeSourceOptions,
10
11
  DateTimeValue,
12
+ SQLITE_FALSE,
13
+ SQLITE_TRUE,
11
14
  SqliteInputRow,
12
15
  SqliteInputValue,
13
16
  TimeValuePrecision
@@ -127,7 +130,11 @@ function filterJsonData(data: any, context: CompatibilityContext, depth = 0): an
127
130
  return data;
128
131
  }
129
132
  } else if (typeof data == 'boolean') {
130
- return data ? 1n : 0n;
133
+ if (context.isEnabled(CompatibilityOption.fixedBooleanInJson)) {
134
+ return data;
135
+ }
136
+
137
+ return data ? SQLITE_TRUE : SQLITE_FALSE;
131
138
  } else if (typeof data == 'bigint') {
132
139
  return data;
133
140
  } else if (data instanceof Date) {
@@ -0,0 +1,106 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { SourceTable } from '@powersync/service-core';
3
+ import { HydratedSyncConfig } from '@powersync/service-sync-rules';
4
+ import { MongoManager } from './MongoManager.js';
5
+ import type { MongoReplicationStreamBatch, MongoReplicationStreamContext } from './MongoReplicationStreamTypes.js';
6
+
7
+ /**
8
+ * Sync config and source namespace information used to construct a provider for a replication attempt.
9
+ */
10
+ export interface MongoReplicationQueryProviderContext {
11
+ /**
12
+ * Hydrated sync config from which the provider can read its connection-specific options.
13
+ */
14
+ syncConfig: HydratedSyncConfig;
15
+ /**
16
+ * Identifies the source connection whose options and tables this provider handles.
17
+ */
18
+ connectionTag: string;
19
+ /**
20
+ * MongoDB database used to resolve table references without an explicit schema.
21
+ */
22
+ defaultSchema: string;
23
+ }
24
+
25
+ /**
26
+ * Adapts snapshot selection and the stream of source changes for one replication implementation.
27
+ * The MongoDB module owns cursor options, namespaces, BSON parsing, large-event reassembly and durable progress.
28
+ */
29
+ export interface MongoReplicationQueryProvider {
30
+ /**
31
+ * Validate source capabilities before either snapshot queries or streaming cursors are opened.
32
+ * Throw if required capabilities are unavailable. Both the stream and snapshotter may call this hook
33
+ * on the same provider, so validation must be safe to repeat.
34
+ */
35
+ validateSource?(options: { connectionManager: MongoManager; isDocumentDb: boolean }): Promise<void>;
36
+
37
+ /**
38
+ * Call context.open() with any additional stages/pre-image options. For filtering, pass its result
39
+ * to filterMongoReplicationStream({ batches, filter }) with a MongoReplicationFilter callback.
40
+ * The helper preserves checkpoints, DDL, batch boundaries, buffered-change flags and safe progress,
41
+ * counts excluded events, and closes the source iterator on failure or early exit.
42
+ * The default provider returns the opener's batches directly.
43
+ * Each invocation is independent and also serves snapshot barriers and resume validation; keep
44
+ * filter state local to that invocation. Snapshot selection must agree with streaming decisions.
45
+ */
46
+ openChangeStream(context: MongoReplicationStreamContext): AsyncIterableIterator<MongoReplicationStreamBatch>;
47
+
48
+ /**
49
+ * Returns an additional MongoDB find predicate for a physical source table.
50
+ * Return null to snapshot without an additional filter. Snapshot selection must agree with the
51
+ * provider's streaming rules so both paths replicate the same set of documents.
52
+ * Expressions can be supplied as { $expr: ... }. The snapshot query combines the filter with its
53
+ * _id continuation predicate and uses simple collation whenever a filter is supplied.
54
+ */
55
+ getSnapshotFilter(table: SourceTable): mongo.Filter<mongo.Document> | null;
56
+ }
57
+
58
+ /**
59
+ * Creates a provider shared by a replication attempt's change stream, snapshotter and source probes.
60
+ */
61
+ export type MongoReplicationQueryProviderFactory = (
62
+ context: MongoReplicationQueryProviderContext
63
+ ) => MongoReplicationQueryProvider;
64
+
65
+ /**
66
+ * Uses the standard MongoDB reader and snapshot selection without additional filtering or event translation.
67
+ */
68
+ export const DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER: MongoReplicationQueryProvider = {
69
+ getSnapshotFilter: () => null,
70
+ openChangeStream: ({ open }) => open({})
71
+ };
72
+
73
+ /**
74
+ * Places provider stages after namespace selection and before optional large-event splitting.
75
+ * This lets provider stages inspect complete events; the shared reader reassembles any resulting fragments.
76
+ */
77
+ export function buildMongoChangeStreamPipeline(options: {
78
+ /**
79
+ * Shared reader options, including resume position, stream scope and requested document images.
80
+ */
81
+ streamOptions: mongo.ChangeStreamOptions & mongo.Document;
82
+ /**
83
+ * Namespace predicate restricting the stream to the selected source collections and checkpoint events.
84
+ */
85
+ namespaceMatch: mongo.Document;
86
+ /**
87
+ * Additional aggregation stages supplied by the provider, in execution order.
88
+ */
89
+ pipelineStages: mongo.Document[];
90
+ /**
91
+ * Append MongoDB's large-event split stage. Disabled for DocumentDB by the shared reader.
92
+ */
93
+ includeSplitLargeEvent: boolean;
94
+ }): mongo.Document[] {
95
+ const pipeline: mongo.Document[] = [
96
+ { $changeStream: options.streamOptions },
97
+ { $match: options.namespaceMatch },
98
+ ...options.pipelineStages
99
+ ];
100
+
101
+ if (options.includeSplitLargeEvent) {
102
+ pipeline.push({ $changeStreamSplitLargeEvent: {} });
103
+ }
104
+
105
+ return pipeline;
106
+ }
@@ -0,0 +1,314 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { ReplicationAssertionError } from '@powersync/lib-services-framework';
3
+ import { buildMongoChangeStreamPipeline, MongoReplicationQueryProvider } from './MongoReplicationQueryProvider.js';
4
+ import {
5
+ MongoReplicationFilterOptions,
6
+ MongoReplicationFilterResult,
7
+ MongoReplicationParserOptions,
8
+ MongoReplicationStreamBatch,
9
+ MongoReplicationStreamBatchMetadata,
10
+ MongoReplicationStreamChange,
11
+ MongoReplicationStreamOptions,
12
+ RawMongoReplicationStreamBatch
13
+ } from './MongoReplicationStreamTypes.js';
14
+ import {
15
+ ChangeStreamBatch,
16
+ parseChangeDocument,
17
+ ProjectedChangeStreamDocument,
18
+ rawChangeStream,
19
+ RawChangeStreamOptions
20
+ } from './RawChangeStream.js';
21
+ import { CHECKPOINTS_COLLECTION } from './replication-utils.js';
22
+
23
+ /**
24
+ * Wraps changes with a single-use iterator. Caches the token and metadata after successful exhaustion.
25
+ */
26
+ export function createMongoReplicationStreamBatch({
27
+ events,
28
+ resolveResumeToken,
29
+ resolveMetadata = () => ({ filteredCount: null })
30
+ }: {
31
+ /**
32
+ * Complete changes, optionally produced by a lazy parsing or filtering generator.
33
+ */
34
+ events: Iterable<MongoReplicationStreamChange>;
35
+ /**
36
+ * Compute a safe resume token once after successful exhaustion, using the final parser state.
37
+ */
38
+ resolveResumeToken: () => mongo.ResumeToken | undefined;
39
+ /**
40
+ * Compute this batch's final statistics after exhaustion. Defaults to no filtering.
41
+ */
42
+ resolveMetadata?: () => MongoReplicationStreamBatchMetadata;
43
+ }): MongoReplicationStreamBatch {
44
+ let started = false;
45
+ let complete = false;
46
+ let resumeToken: mongo.ResumeToken | undefined;
47
+ let metadata: MongoReplicationStreamBatchMetadata;
48
+ function assertComplete() {
49
+ // Progress is only safe to read after every event has been consumed and finalization succeeds.
50
+ if (!complete) {
51
+ throw new ReplicationAssertionError('Consume all batch events before requesting token or metadata');
52
+ }
53
+ }
54
+ return {
55
+ events: {
56
+ [Symbol.iterator](): Iterator<MongoReplicationStreamChange> {
57
+ // A second pass would repeat parsing/filtering against state that has already advanced.
58
+ if (started) {
59
+ throw new ReplicationAssertionError('Batch events can only be consumed once');
60
+ }
61
+ started = true;
62
+ return iterate();
63
+ }
64
+ },
65
+ getResumeToken() {
66
+ assertComplete();
67
+ return resumeToken;
68
+ },
69
+ get metadata() {
70
+ assertComplete();
71
+ return metadata;
72
+ }
73
+ };
74
+
75
+ function* iterate() {
76
+ // Delegate lazily; an error or early return skips the finalization below.
77
+ yield* events;
78
+ // Cache this batch's final results before later batches can change the parser or filter state.
79
+ resumeToken = resolveResumeToken();
80
+ metadata = Object.freeze({ ...resolveMetadata() });
81
+ complete = true;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Filter complete data changes while retaining source batch boundaries and recovery bookkeeping.
87
+ * Return MongoReplicationFilterResult.KEEP to forward a change, EXCLUDE to omit it, or DELETE for an exit.
88
+ * Synthetic deletes retain the source identity, resume token and transaction metadata.
89
+ * The callback runs synchronously and lazily; failures and early exits close the underlying stream.
90
+ */
91
+ export async function* filterMongoReplicationStream({
92
+ batches,
93
+ filter
94
+ }: MongoReplicationFilterOptions): AsyncGenerator<MongoReplicationStreamBatch> {
95
+ for await (const sourceBatch of batches) {
96
+ let filteredCount = 0;
97
+ const batch = createMongoReplicationStreamBatch({
98
+ events: filterEvents(),
99
+ resolveResumeToken: () => sourceBatch.getResumeToken(),
100
+ resolveMetadata: () => ({ filteredCount: (sourceBatch.metadata.filteredCount ?? 0) + filteredCount })
101
+ });
102
+ yield batch;
103
+ // Assert that the consumer exhausted this batch before requesting the next one, even if every event
104
+ // was filtered out. The token value is unused; getResumeToken() throws if consumption is incomplete.
105
+ batch.getResumeToken();
106
+
107
+ function* filterEvents(): Generator<MongoReplicationStreamChange> {
108
+ for (const change of sourceBatch.events) {
109
+ const { event } = change;
110
+ if (
111
+ (event.operationType != 'insert' &&
112
+ event.operationType != 'update' &&
113
+ event.operationType != 'replace' &&
114
+ event.operationType != 'delete') ||
115
+ event.ns.coll == CHECKPOINTS_COLLECTION
116
+ ) {
117
+ yield change;
118
+ continue;
119
+ }
120
+ const result = filter(event);
121
+ if (result == MongoReplicationFilterResult.EXCLUDE) {
122
+ filteredCount++;
123
+ } else if (result == MongoReplicationFilterResult.DELETE) {
124
+ yield { ...change, event: { ...event, operationType: 'delete' } };
125
+ } else {
126
+ yield change;
127
+ }
128
+ }
129
+ }
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Shared opening path for ongoing replication, snapshot barriers and resume validation.
135
+ */
136
+ export function openMongoReplicationStream({
137
+ db,
138
+ queryProvider,
139
+ namespaceFilter,
140
+ isDocumentDb,
141
+ usePostImages,
142
+ position,
143
+ skipInitialTimestamp = false,
144
+ options,
145
+ onBatch
146
+ }: {
147
+ db: mongo.Db;
148
+ queryProvider: MongoReplicationQueryProvider;
149
+ namespaceFilter: { $match: mongo.Document; multipleDatabases: boolean };
150
+ isDocumentDb: boolean;
151
+ usePostImages: boolean;
152
+ position: { resumeAfter?: mongo.ResumeToken | null; startAfter?: mongo.Timestamp | null } | null;
153
+ /**
154
+ * Legacy streaming positions exclude the initial timestamp; snapshot barrier probes must include it.
155
+ */
156
+ skipInitialTimestamp?: boolean;
157
+ options: RawChangeStreamOptions;
158
+ onBatch?: (batch: ChangeStreamBatch) => Disposable | void;
159
+ }): AsyncIterableIterator<MongoReplicationStreamBatch> {
160
+ const parsing = {
161
+ defaultSchema: db.databaseName,
162
+ multipleDatabases: namespaceFilter.multipleDatabases,
163
+ startAfter: skipInitialTimestamp && position?.resumeAfter == null ? position?.startAfter : undefined,
164
+ signal: options.signal,
165
+ logger: options.logger
166
+ };
167
+
168
+ const openRaw = async function* ({
169
+ pipelineStages = [],
170
+ imageOptions = {}
171
+ }: MongoReplicationStreamOptions): AsyncIterableIterator<RawMongoReplicationStreamBatch> {
172
+ const clusterScope = isDocumentDb || namespaceFilter.multipleDatabases;
173
+ const streamOptions: mongo.Document = {
174
+ ...imageOptions,
175
+ fullDocument: !isDocumentDb && usePostImages ? 'required' : 'updateLookup',
176
+ ...(!isDocumentDb ? { showExpandedEvents: true } : {}),
177
+ ...(clusterScope ? { allChangesForCluster: true } : {})
178
+ };
179
+ // Only one resume option is legal. Legacy MongoDB snapshot positions may contain just a timestamp;
180
+ // a fresh DocumentDB stream has neither and opens from now.
181
+ if (position?.resumeAfter != null) {
182
+ streamOptions.resumeAfter = position.resumeAfter;
183
+ } else if (position?.startAfter != null) {
184
+ streamOptions.startAtOperationTime = position.startAfter;
185
+ }
186
+ const pipeline = buildMongoChangeStreamPipeline({
187
+ streamOptions,
188
+ namespaceMatch: namespaceFilter.$match,
189
+ pipelineStages,
190
+ includeSplitLargeEvent: !isDocumentDb
191
+ });
192
+ for await (const batch of rawChangeStream(clusterScope ? db.client.db('admin') : db, pipeline, options)) {
193
+ options.signal?.throwIfAborted();
194
+ using batchScope = onBatch?.(batch) || undefined;
195
+ yield { events: batch.events, resumeToken: batch.resumeToken };
196
+ }
197
+ };
198
+
199
+ return queryProvider.openChangeStream({
200
+ open: (options) => parseMongoReplicationStream({ batches: openRaw(options), ...parsing })
201
+ });
202
+ }
203
+
204
+ /**
205
+ * Creates a stateful parser for one raw MongoDB stream. Parses BSON entries, joins split-event
206
+ * fragments across batches, normalizes namespaces and skips events covered by legacy timestamps.
207
+ * After processing a batch, callers can request safe progress. Check completion on natural EOF,
208
+ * not cancellation.
209
+ */
210
+ export function createMongoReplicationStreamParser({
211
+ defaultSchema,
212
+ multipleDatabases,
213
+ startAfter,
214
+ signal,
215
+ logger
216
+ }: MongoReplicationParserOptions) {
217
+ let splitDocument: ProjectedChangeStreamDocument | null = null;
218
+ let flexDbNameWorkaroundLogged = false;
219
+ return {
220
+ parse(rawEvent: Buffer): ProjectedChangeStreamDocument | null {
221
+ signal?.throwIfAborted();
222
+ let event = parseChangeDocument(rawEvent);
223
+ const fragment = event.splitEvent;
224
+ if (fragment != null) {
225
+ // A retry can resume after a received fragment inside the raw reader. Keep the partial event in
226
+ // memory across batches/retries, but never expose its token as a durable recovery boundary.
227
+ const expectedFragment = splitDocument == null ? 1 : splitDocument.splitEvent!.fragment + 1;
228
+ if (
229
+ fragment.fragment != expectedFragment ||
230
+ fragment.fragment > fragment.of ||
231
+ (splitDocument != null && fragment.of != splitDocument.splitEvent!.of)
232
+ ) {
233
+ throw new ReplicationAssertionError(`Unexpected splitEvent: ${JSON.stringify(fragment)}`);
234
+ }
235
+ splitDocument = splitDocument == null ? event : Object.assign(splitDocument, event);
236
+ if (fragment.fragment != fragment.of) {
237
+ return null;
238
+ }
239
+ event = splitDocument;
240
+ splitDocument = null;
241
+ } else if (splitDocument != null) {
242
+ throw new ReplicationAssertionError(`Incomplete splitEvent: ${JSON.stringify(splitDocument.splitEvent)}`);
243
+ }
244
+
245
+ if (startAfter != null && event.clusterTime?.lte(startAfter)) {
246
+ return null;
247
+ }
248
+
249
+ if (
250
+ !multipleDatabases &&
251
+ 'ns' in event &&
252
+ event.ns.db != defaultSchema &&
253
+ event.ns.db.endsWith(`_${defaultSchema}`)
254
+ ) {
255
+ // Atlas Flex can prefix the database name on events recorded while replication was paused.
256
+ // Normalize before adapters inspect namespaces, just as the ordinary replication loop does.
257
+ const originalDatabase = event.ns.db;
258
+ event.ns.db = defaultSchema;
259
+ if (!flexDbNameWorkaroundLogged) {
260
+ flexDbNameWorkaroundLogged = true;
261
+ logger?.warn(`Incorrect DB name in change stream: ${originalDatabase}. Changed to ${defaultSchema}.`);
262
+ }
263
+ }
264
+ return event;
265
+ },
266
+ /**
267
+ * Returns the given transport token if it is safe to persist, or undefined while a split event is unfinished.
268
+ */
269
+ getSafeResumeToken(resumeToken: mongo.ResumeToken) {
270
+ return splitDocument == null ? resumeToken : undefined;
271
+ },
272
+ assertComplete() {
273
+ if (splitDocument != null) {
274
+ throw new ReplicationAssertionError(`Incomplete splitEvent: ${JSON.stringify(splitDocument.splitEvent)}`);
275
+ }
276
+ }
277
+ };
278
+ }
279
+
280
+ /**
281
+ * Wrap raw batches in lazy event iterables. BSON parsing and split-event assembly happen
282
+ * as consumers request events, without building a parsed array. After exhaustion, each batch retains
283
+ * its own resume-token result even when later batches change the parser state.
284
+ * Consume each batch completely before requesting the next; returning early closes the source.
285
+ */
286
+ export async function* parseMongoReplicationStream({
287
+ batches,
288
+ ...options
289
+ }: MongoReplicationParserOptions & {
290
+ batches: AsyncIterable<RawMongoReplicationStreamBatch>;
291
+ }): AsyncGenerator<MongoReplicationStreamBatch> {
292
+ const parser = createMongoReplicationStreamParser(options);
293
+ for await (const sourceBatch of batches) {
294
+ options.signal?.throwIfAborted();
295
+ const batch = createMongoReplicationStreamBatch({
296
+ events: parseEvents(sourceBatch.events),
297
+ resolveResumeToken: () => parser.getSafeResumeToken(sourceBatch.resumeToken)
298
+ });
299
+ yield batch;
300
+ // Split-event state is shared across batches, so the consumer must finish this one before the next is read.
301
+ // This also covers empty batches.
302
+ batch.getResumeToken();
303
+ }
304
+ parser.assertComplete();
305
+
306
+ function* parseEvents(rawEvents: Buffer[]): Generator<MongoReplicationStreamChange> {
307
+ for (let index = 0; index < rawEvents.length; index++) {
308
+ const event = parser.parse(rawEvents[index]);
309
+ if (event != null) {
310
+ yield { event, hasBufferedChanges: index < rawEvents.length - 1 };
311
+ }
312
+ }
313
+ }
314
+ }