@powersync/service-module-mongodb 0.21.2 → 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.
- package/CHANGELOG.md +51 -0
- package/benchmarks/env.ts +11 -0
- package/benchmarks/replication_branch_throughput.benchmark.ts +240 -0
- package/dist/api/MongoRouteAPIAdapter.d.ts +6 -0
- package/dist/api/MongoRouteAPIAdapter.js +21 -2
- package/dist/api/MongoRouteAPIAdapter.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/module/MongoModule.d.ts +1 -1
- package/dist/module/MongoModule.js +1 -0
- package/dist/module/MongoModule.js.map +1 -1
- package/dist/replication/ChangeStream.d.ts +13 -3
- package/dist/replication/ChangeStream.js +130 -196
- package/dist/replication/ChangeStream.js.map +1 -1
- package/dist/replication/ChangeStreamReplicationJob.d.ts +4 -1
- package/dist/replication/ChangeStreamReplicationJob.js +19 -8
- package/dist/replication/ChangeStreamReplicationJob.js.map +1 -1
- package/dist/replication/ChangeStreamReplicator.d.ts +4 -0
- package/dist/replication/ChangeStreamReplicator.js +6 -0
- package/dist/replication/ChangeStreamReplicator.js.map +1 -1
- package/dist/replication/MongoReplicationQueryProvider.d.ts +85 -0
- package/dist/replication/MongoReplicationQueryProvider.js +23 -0
- package/dist/replication/MongoReplicationQueryProvider.js.map +1 -0
- package/dist/replication/MongoReplicationStream.d.ts +74 -0
- package/dist/replication/MongoReplicationStream.js +228 -0
- package/dist/replication/MongoReplicationStream.js.map +1 -0
- package/dist/replication/MongoReplicationStreamTypes.d.ts +157 -0
- package/dist/replication/MongoReplicationStreamTypes.js +19 -0
- package/dist/replication/MongoReplicationStreamTypes.js.map +1 -0
- package/dist/replication/MongoSnapshotQuery.d.ts +2 -0
- package/dist/replication/MongoSnapshotQuery.js +12 -2
- package/dist/replication/MongoSnapshotQuery.js.map +1 -1
- package/dist/replication/MongoSnapshotter.d.ts +7 -2
- package/dist/replication/MongoSnapshotter.js +90 -88
- package/dist/replication/MongoSnapshotter.js.map +1 -1
- package/dist/replication/RawChangeStream.d.ts +1 -1
- package/dist/replication/RawChangeStream.js +1 -1
- package/dist/replication/RawChangeStream.js.map +1 -1
- package/dist/replication/estimateFilteredSnapshotCount.d.ts +12 -0
- package/dist/replication/estimateFilteredSnapshotCount.js +79 -0
- package/dist/replication/estimateFilteredSnapshotCount.js.map +1 -0
- package/dist/replication/replication-index.d.ts +7 -0
- package/dist/replication/replication-index.js +7 -0
- package/dist/replication/replication-index.js.map +1 -1
- package/dist/test-utils/ChangeStreamTestContext.d.ts +131 -0
- package/dist/test-utils/ChangeStreamTestContext.js +390 -0
- package/dist/test-utils/ChangeStreamTestContext.js.map +1 -0
- package/dist/test-utils/test-utils-index.d.ts +1 -0
- package/dist/test-utils/test-utils-index.js +2 -0
- package/dist/test-utils/test-utils-index.js.map +1 -0
- package/package.json +11 -10
- package/src/api/MongoRouteAPIAdapter.ts +26 -2
- package/src/index.ts +1 -0
- package/src/module/MongoModule.ts +2 -1
- package/src/replication/ChangeStream.ts +143 -226
- package/src/replication/ChangeStreamReplicationJob.ts +21 -9
- package/src/replication/ChangeStreamReplicator.ts +9 -0
- package/src/replication/MongoReplicationQueryProvider.ts +106 -0
- package/src/replication/MongoReplicationStream.ts +314 -0
- package/src/replication/MongoReplicationStreamTypes.ts +169 -0
- package/src/replication/MongoSnapshotQuery.ts +19 -3
- package/src/replication/MongoSnapshotter.ts +101 -92
- package/src/replication/RawChangeStream.ts +2 -2
- package/src/replication/estimateFilteredSnapshotCount.ts +93 -0
- package/src/replication/replication-index.ts +7 -0
- package/src/test-utils/ChangeStreamTestContext.ts +520 -0
- package/src/test-utils/test-utils-index.ts +1 -0
- package/test/src/change_event_memory.test.ts +33 -0
- package/test/src/change_stream.test.ts +3 -3
- package/test/src/change_stream_abort.test.ts +110 -0
- package/test/src/change_stream_test_setup.ts +38 -0
- package/test/src/chunked_snapshot.test.ts +3 -3
- package/test/src/documentdb_mode.test.ts +3 -3
- package/test/src/filtering_example.test.ts +65 -0
- package/test/src/filtering_lifecycle.test.ts +101 -0
- package/test/src/query_provider_availability.test.ts +77 -0
- package/test/src/query_provider_diagnostics.test.ts +55 -0
- package/test/src/replication_stream.test.ts +688 -0
- package/test/src/resume.test.ts +10 -4
- package/test/src/resuming_snapshots.test.ts +3 -3
- package/test/src/slow_tests.test.ts +3 -3
- package/test/src/snapshot_count.test.ts +146 -0
- package/test/src/snapshot_count_integration.test.ts +70 -0
- package/test/src/snapshot_query_provider.test.ts +122 -0
- package/test/src/stream_progress.test.ts +334 -0
- package/test/tsconfig.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
- package/vitest.benchmark.config.ts +15 -0
- 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
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
|
});
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import type { mongo } from '@powersync/lib-service-mongodb';
|
|
2
|
+
import type { Logger } from '@powersync/lib-services-framework';
|
|
3
|
+
import type { ProjectedChangeStreamDocument } from './RawChangeStream.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* An unparsed MongoDB response batch. Consumers parse its entries incrementally and retain unfinished
|
|
7
|
+
* split events across batches before deciding whether its resume token is safe to persist.
|
|
8
|
+
*/
|
|
9
|
+
export interface RawMongoReplicationStreamBatch {
|
|
10
|
+
/**
|
|
11
|
+
* Original BSON entries in source order, including possible split-event fragments.
|
|
12
|
+
*/
|
|
13
|
+
events: Buffer[];
|
|
14
|
+
/**
|
|
15
|
+
* Transport position after this batch. It may cover an incomplete event and is not yet safe progress.
|
|
16
|
+
*/
|
|
17
|
+
resumeToken: mongo.ResumeToken;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A complete event and its position within the original source batch.
|
|
22
|
+
*/
|
|
23
|
+
export interface MongoReplicationStreamChange {
|
|
24
|
+
event: ProjectedChangeStreamDocument;
|
|
25
|
+
/**
|
|
26
|
+
* MongoDB returned more entries after this event, even if a provider later excludes them or the
|
|
27
|
+
* parser retains them as unfinished split fragments. For [checkpoint, excluded change], preserve
|
|
28
|
+
* true on the checkpoint so ChangeStream groups commits instead of treating it as caught up.
|
|
29
|
+
* Providers must preserve this value when forwarding or transforming events.
|
|
30
|
+
*/
|
|
31
|
+
hasBufferedChanges: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Statistics for one fully consumed batch, independent of whether its resume token is safe.
|
|
36
|
+
*/
|
|
37
|
+
export interface MongoReplicationStreamBatchMetadata {
|
|
38
|
+
/**
|
|
39
|
+
* Complete events excluded from this batch. Null means no filtering was applied; zero means
|
|
40
|
+
* filtering was applied but no events were excluded. Counts do not carry across batches.
|
|
41
|
+
*/
|
|
42
|
+
readonly filteredCount: number | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A single-use batch of complete events, parsed or filtered lazily as the consumer iterates.
|
|
47
|
+
* Exhaust events before reading its resume token, metadata or the next batch.
|
|
48
|
+
*/
|
|
49
|
+
export interface MongoReplicationStreamBatch {
|
|
50
|
+
/**
|
|
51
|
+
* Complete changes in source order, parsed or filtered lazily during synchronous iteration.
|
|
52
|
+
* Consume once and fully. It may be empty after filtering or while assembling a split event.
|
|
53
|
+
*/
|
|
54
|
+
events: Iterable<MongoReplicationStreamChange>;
|
|
55
|
+
/**
|
|
56
|
+
* Returns the safe resume token after events are fully consumed, or undefined while a split event
|
|
57
|
+
* is unfinished. Throws before exhaustion. The result remains stable after later batches.
|
|
58
|
+
*/
|
|
59
|
+
getResumeToken(): mongo.ResumeToken | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* Final statistics for this batch, available even without a safe resume token.
|
|
62
|
+
* Throws before events are fully consumed; the result is immutable and cached afterward.
|
|
63
|
+
*/
|
|
64
|
+
readonly metadata: MongoReplicationStreamBatchMetadata;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Provider-controlled additions to the shared cursor setup. Source scope, resume position, post-image
|
|
69
|
+
* requirements and cancellation remain controlled by the MongoDB replication module.
|
|
70
|
+
*/
|
|
71
|
+
export interface MongoReplicationStreamOptions {
|
|
72
|
+
/**
|
|
73
|
+
* Inserted after namespace selection and before the final large-event split stage.
|
|
74
|
+
*/
|
|
75
|
+
pipelineStages?: mongo.Document[];
|
|
76
|
+
/**
|
|
77
|
+
* Request pre-images without overriding the reader's post-image, resume or scope options.
|
|
78
|
+
*/
|
|
79
|
+
imageOptions?: Pick<mongo.ChangeStreamOptions, 'fullDocumentBeforeChange'>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Bound source opener supplied to a query provider for one stream invocation.
|
|
84
|
+
* Providers may wrap the lazy event iterables to filter or transform complete changes.
|
|
85
|
+
*/
|
|
86
|
+
export interface MongoReplicationStreamContext {
|
|
87
|
+
/**
|
|
88
|
+
* Open batches whose events are parsed lazily, with cursor scope, position, cancellation and
|
|
89
|
+
* accounting already bound. Each call owns independent split-event assembly and parser state.
|
|
90
|
+
* Events are complete; progress is withheld while a split event is unfinished.
|
|
91
|
+
* Close the iterator on completion, cancellation or failure (for await handles this).
|
|
92
|
+
*/
|
|
93
|
+
open(options: MongoReplicationStreamOptions): AsyncIterableIterator<MongoReplicationStreamBatch>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Source context for lazy parsing of raw BSON events in default and filtering providers.
|
|
98
|
+
* These options control namespace normalization, legacy timestamp skipping and cancellation; split-event
|
|
99
|
+
* state belongs to each parser instance and must not be shared between independently opened streams.
|
|
100
|
+
*/
|
|
101
|
+
export interface MongoReplicationParserOptions {
|
|
102
|
+
/**
|
|
103
|
+
* Expected database name when correcting Atlas Flex's prefixed namespaces in single-database mode.
|
|
104
|
+
*/
|
|
105
|
+
defaultSchema: string;
|
|
106
|
+
/**
|
|
107
|
+
* Preserve database names when the stream covers multiple databases instead of normalizing them.
|
|
108
|
+
*/
|
|
109
|
+
multipleDatabases: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Exclude complete events at or before this legacy resume timestamp. Leave unset for exact-token
|
|
112
|
+
* resumes, where later events can share the same timestamp, and for snapshot barrier probes.
|
|
113
|
+
*/
|
|
114
|
+
startAfter?: mongo.Timestamp | null;
|
|
115
|
+
/**
|
|
116
|
+
* Abort parsing when the owning replication attempt is cancelled. Resolving a batch's progress is not
|
|
117
|
+
* interrupted, so consumers must check the signal themselves before persisting a token.
|
|
118
|
+
*/
|
|
119
|
+
signal?: AbortSignal;
|
|
120
|
+
/**
|
|
121
|
+
* Receives the namespace-correction warning, at most once per parser instance.
|
|
122
|
+
*/
|
|
123
|
+
logger?: Logger;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* A complete data change eligible for filtering. Checkpoints and DDL bypass the filter.
|
|
128
|
+
*/
|
|
129
|
+
export type MongoReplicationDataChange = Extract<
|
|
130
|
+
ProjectedChangeStreamDocument,
|
|
131
|
+
{ operationType: 'insert' | 'update' | 'replace' | 'delete' }
|
|
132
|
+
>;
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The action to apply to a complete data change after evaluating filter membership.
|
|
136
|
+
*/
|
|
137
|
+
export enum MongoReplicationFilterResult {
|
|
138
|
+
/**
|
|
139
|
+
* Forward the original change.
|
|
140
|
+
*/
|
|
141
|
+
KEEP = 'keep',
|
|
142
|
+
/**
|
|
143
|
+
* Omit the change while retaining its batch's recovery progress.
|
|
144
|
+
*/
|
|
145
|
+
EXCLUDE = 'exclude',
|
|
146
|
+
/**
|
|
147
|
+
* Emit a delete because the document left the filtered set.
|
|
148
|
+
*/
|
|
149
|
+
DELETE = 'delete'
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Synchronously decide how to replicate a complete data change. Checkpoints and DDL bypass this callback.
|
|
154
|
+
*/
|
|
155
|
+
export type MongoReplicationFilter = (event: MongoReplicationDataChange) => MongoReplicationFilterResult;
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Source batches and membership decisions for the shared replication filter.
|
|
159
|
+
*/
|
|
160
|
+
export interface MongoReplicationFilterOptions {
|
|
161
|
+
/**
|
|
162
|
+
* Ordered source batches whose boundaries and recovery progress must be preserved.
|
|
163
|
+
*/
|
|
164
|
+
batches: AsyncIterable<MongoReplicationStreamBatch>;
|
|
165
|
+
/**
|
|
166
|
+
* Decide whether to keep, exclude or delete each complete data change.
|
|
167
|
+
*/
|
|
168
|
+
filter: MongoReplicationFilter;
|
|
169
|
+
}
|