@powersync/service-module-mongodb 0.18.1 → 0.19.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 (60) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/api/MongoRouteAPIAdapter.d.ts +2 -0
  3. package/dist/api/MongoRouteAPIAdapter.js +23 -32
  4. package/dist/api/MongoRouteAPIAdapter.js.map +1 -1
  5. package/dist/common/SentinelLSN.d.ts +37 -0
  6. package/dist/common/SentinelLSN.js +59 -0
  7. package/dist/common/SentinelLSN.js.map +1 -0
  8. package/dist/replication/ChangeStream.d.ts +15 -0
  9. package/dist/replication/ChangeStream.js +105 -44
  10. package/dist/replication/ChangeStream.js.map +1 -1
  11. package/dist/replication/MongoRelation.d.ts +36 -1
  12. package/dist/replication/MongoRelation.js +102 -6
  13. package/dist/replication/MongoRelation.js.map +1 -1
  14. package/dist/replication/MongoSnapshotter.d.ts +9 -0
  15. package/dist/replication/MongoSnapshotter.js +108 -42
  16. package/dist/replication/MongoSnapshotter.js.map +1 -1
  17. package/dist/replication/RawChangeStream.d.ts +12 -1
  18. package/dist/replication/RawChangeStream.js +30 -7
  19. package/dist/replication/RawChangeStream.js.map +1 -1
  20. package/dist/replication/checkpoints/CheckpointImplementation.d.ts +132 -0
  21. package/dist/replication/checkpoints/CheckpointImplementation.js +22 -0
  22. package/dist/replication/checkpoints/CheckpointImplementation.js.map +1 -0
  23. package/dist/replication/checkpoints/SentinelCheckpointImplementation.d.ts +55 -0
  24. package/dist/replication/checkpoints/SentinelCheckpointImplementation.js +222 -0
  25. package/dist/replication/checkpoints/SentinelCheckpointImplementation.js.map +1 -0
  26. package/dist/replication/checkpoints/TimestampCheckpointImplementation.d.ts +24 -0
  27. package/dist/replication/checkpoints/TimestampCheckpointImplementation.js +113 -0
  28. package/dist/replication/checkpoints/TimestampCheckpointImplementation.js.map +1 -0
  29. package/dist/replication/checkpoints/create-checkpoint-implementation.d.ts +6 -0
  30. package/dist/replication/checkpoints/create-checkpoint-implementation.js +10 -0
  31. package/dist/replication/checkpoints/create-checkpoint-implementation.js.map +1 -0
  32. package/dist/replication/replication-utils.d.ts +6 -0
  33. package/dist/replication/replication-utils.js +19 -2
  34. package/dist/replication/replication-utils.js.map +1 -1
  35. package/package.json +9 -9
  36. package/src/api/MongoRouteAPIAdapter.ts +26 -37
  37. package/src/common/SentinelLSN.ts +78 -0
  38. package/src/replication/ChangeStream.ts +118 -50
  39. package/src/replication/MongoRelation.ts +124 -14
  40. package/src/replication/MongoSnapshotter.ts +122 -47
  41. package/src/replication/RawChangeStream.ts +64 -28
  42. package/src/replication/checkpoints/CheckpointImplementation.ts +167 -0
  43. package/src/replication/checkpoints/SentinelCheckpointImplementation.ts +267 -0
  44. package/src/replication/checkpoints/TimestampCheckpointImplementation.ts +142 -0
  45. package/src/replication/checkpoints/create-checkpoint-implementation.ts +14 -0
  46. package/src/replication/replication-utils.ts +23 -2
  47. package/test/DOCUMENTDB_TESTING.md +115 -0
  48. package/test/src/DatabaseType.ts +25 -0
  49. package/test/src/change_stream.test.ts +103 -68
  50. package/test/src/change_stream_utils.ts +85 -9
  51. package/test/src/checkpoint_retry.test.ts +5 -2
  52. package/test/src/documentdb_helpers.test.ts +124 -0
  53. package/test/src/documentdb_mode.test.ts +1040 -0
  54. package/test/src/mongo_test.test.ts +15 -5
  55. package/test/src/raw_change_stream.test.ts +209 -125
  56. package/test/src/resume_token.test.ts +30 -0
  57. package/test/src/slow_tests.test.ts +4 -1
  58. package/test/src/test-timeouts.ts +23 -0
  59. package/test/src/util.ts +1 -2
  60. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,132 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { Logger } from '@powersync/lib-services-framework';
3
+ import { ReplicationHeadCallback, storage } from '@powersync/service-core';
4
+ import { ProjectedChangeStreamDocument } from '../RawChangeStream.js';
5
+ /**
6
+ * Classification of an event on the `_powersync_checkpoints` collection.
7
+ *
8
+ * - 'standalone': source-wide checkpoint (write checkpoints, keepalive bumps,
9
+ * snapshot markers). Processed regardless of which process created it.
10
+ * - 'own-barrier': this stream's private batch barrier document.
11
+ * - 'foreign': another stream's barrier document — ignore.
12
+ */
13
+ export type CheckpointEventKind = 'standalone' | 'own-barrier' | 'foreign';
14
+ export interface StreamResumePosition {
15
+ resumeAfter: mongo.ResumeToken | null;
16
+ /**
17
+ * Legacy startAtOperationTime fallback. Only produced by the timestamp implementation,
18
+ * and only for old LSNs persisted without a resume token.
19
+ */
20
+ startAfter: mongo.Timestamp | null;
21
+ }
22
+ export interface CheckpointImplementationContext {
23
+ client: mongo.MongoClient;
24
+ db: mongo.Db;
25
+ checkpointStreamId: mongo.ObjectId;
26
+ logger: Logger;
27
+ }
28
+ /**
29
+ * Event-interpretation surface of a {@link CheckpointImplementation}. Every method
30
+ * operates on a single raw change event.
31
+ *
32
+ * Ordering contract: {@link observe} must be called before {@link lsn} for a given
33
+ * event, so the sentinel implementation's coordinate is current.
34
+ */
35
+ export interface CheckpointEventApi {
36
+ /**
37
+ * Classify a checkpoint-collection event and absorb any coordinate it
38
+ * carries (sentinel implementation). Must be called for every checkpoint event, in
39
+ * stream order.
40
+ */
41
+ observe(doc: ProjectedChangeStreamDocument): CheckpointEventKind;
42
+ /**
43
+ * Comparable LSN for committing/resuming at this event.
44
+ *
45
+ * Note this is not purely a function of `doc`. The timestamp implementation
46
+ * derives the whole LSN from the event (its coordinate is the event's
47
+ * clusterTime). The sentinel implementation pairs the *tracked* coordinate
48
+ * (updated by {@link observe}) with the event's resume token, because data
49
+ * events carry no coordinate of their own — hence the observe-before-lsn
50
+ * contract.
51
+ */
52
+ lsn(doc: ProjectedChangeStreamDocument): string;
53
+ /** Whether a barrier marker from {@link CheckpointImplementation.createBatchCheckpoint} is resolved by this event. */
54
+ resolvesBarrier(marker: string, doc: ProjectedChangeStreamDocument): boolean;
55
+ }
56
+ /**
57
+ * Strategy for producing and interpreting replication checkpoints.
58
+ *
59
+ * Two implementations exist:
60
+ *
61
+ * - {@link TimestampCheckpointImplementation}: standard MongoDB. The ordered LSN
62
+ * coordinate is the oplog clusterTime, which is unique per operation and
63
+ * parseable from resume tokens.
64
+ * - {@link SentinelCheckpointImplementation}: for sources without a usable clusterTime
65
+ * (DocumentDB, and technically usable on any MongoDB). The ordered coordinate
66
+ * is a shared monotonic counter document, observed through the change
67
+ * stream itself.
68
+ *
69
+ * An implementation instance belongs to a single ChangeStream (or API adapter) and may
70
+ * hold per-stream coordinate state; call {@link seedPosition} at the start of
71
+ * each streaming loop.
72
+ */
73
+ export interface CheckpointImplementation {
74
+ /** LSN representing "before any data". */
75
+ readonly zeroLsn: string;
76
+ /** Parse a stored LSN into change stream resume options. Pure. */
77
+ parseResumePosition(lsn: string): StreamResumePosition;
78
+ /** Reset/seed the implementation's coordinate state for a new stream loop. */
79
+ seedPosition(lsn: string | null): void;
80
+ /** Log the resume position at the start of a streaming loop. */
81
+ logResume(lsn: string): void;
82
+ /**
83
+ * Create a source-wide consistency checkpoint (snapshot boundaries,
84
+ * `no_checkpoint_before` markers). Returns a comparable LSN.
85
+ */
86
+ createStandaloneCheckpoint(): Promise<string>;
87
+ /**
88
+ * Create a batch barrier for this stream. Returns a marker that is resolved
89
+ * by a later change stream event via {@link CheckpointEventApi.resolvesBarrier}.
90
+ */
91
+ createBatchCheckpoint(): Promise<string>;
92
+ /**
93
+ * Create the first batch barrier for snapshot-LSN acquisition and return the
94
+ * LSN to open the change stream from, or null to open from "now".
95
+ *
96
+ * The timestamp implementation's barrier marker is itself a comparable LSN, so
97
+ * the stream resumes from it. The sentinel implementation's marker is opaque
98
+ * (content-matched) and carries no resume position, so it returns null and the
99
+ * stream opens from the current point.
100
+ */
101
+ createFirstBarrier(): Promise<string | null>;
102
+ /**
103
+ * Idle keepalive for an empty change stream batch. May persist a checkpoint
104
+ * directly (timestamp implementation) or nudge the source so that a later event
105
+ * commits (sentinel implementation).
106
+ */
107
+ keepalive(batch: storage.BucketStorageBatch, resumeToken: mongo.ResumeToken): Promise<void>;
108
+ /**
109
+ * Build a comparable LSN from a bare batch-level resume token (no change
110
+ * event). Used for the per-batch `setResumeLsn` progress marker.
111
+ *
112
+ * The timestamp implementation parses the timestamp embedded in the token.
113
+ * The sentinel implementation pairs the token with the current coordinate.
114
+ */
115
+ lsnFromResumeToken(resumeToken: mongo.ResumeToken): string;
116
+ /**
117
+ * Source-side replication head for write checkpoints. The LSN passed to the
118
+ * callback must compare at or below any LSN committed after the caller's
119
+ * preceding writes.
120
+ */
121
+ createReplicationHead<T>(callback: ReplicationHeadCallback<T>): Promise<T>;
122
+ /** Event-interpretation methods, all operating on a single raw change event. */
123
+ readonly event: CheckpointEventApi;
124
+ /** Filter for clearing the checkpoints collection on startup. */
125
+ readonly checkpointClearFilter: mongo.Filter<mongo.Document>;
126
+ }
127
+ /**
128
+ * Extract the event timestamp: clusterTime when present, otherwise wallTime
129
+ * truncated to second precision.
130
+ */
131
+ export declare function getEventTimestamp(changeDocument: ProjectedChangeStreamDocument): mongo.Timestamp;
132
+ export declare function getCheckpointId(doc: ProjectedChangeStreamDocument): string | mongo.ObjectId | null;
@@ -0,0 +1,22 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ /**
3
+ * Extract the event timestamp: clusterTime when present, otherwise wallTime
4
+ * truncated to second precision.
5
+ */
6
+ export function getEventTimestamp(changeDocument) {
7
+ if (changeDocument.clusterTime) {
8
+ return changeDocument.clusterTime;
9
+ }
10
+ const wallTime = changeDocument.wallTime;
11
+ if (wallTime != null) {
12
+ return mongo.Timestamp.fromBits(0, Math.floor(wallTime.getTime() / 1000));
13
+ }
14
+ throw new Error('Change event has neither clusterTime nor wallTime');
15
+ }
16
+ export function getCheckpointId(doc) {
17
+ if (!('documentKey' in doc)) {
18
+ return null;
19
+ }
20
+ return doc.documentKey._id;
21
+ }
22
+ //# sourceMappingURL=CheckpointImplementation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CheckpointImplementation.js","sourceRoot":"","sources":["../../../src/replication/checkpoints/CheckpointImplementation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,gCAAgC,CAAC;AAkJvD;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,cAA6C;IAC7E,IAAI,cAAc,CAAC,WAAW,EAAE,CAAC;QAC/B,OAAO,cAAc,CAAC,WAAW,CAAC;IACpC,CAAC;IACD,MAAM,QAAQ,GAAI,cAAsB,CAAC,QAA4B,CAAC;IACtE,IAAI,QAAQ,IAAI,IAAI,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;IAC5E,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;AACvE,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,GAAkC;IAChE,IAAI,CAAC,CAAC,aAAa,IAAI,GAAG,CAAC,EAAE,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,GAAG,CAAC,WAAW,CAAC,GAA8B,CAAC;AACxD,CAAC"}
@@ -0,0 +1,55 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { ReplicationHeadCallback, storage } from '@powersync/service-core';
3
+ import { CheckpointEventApi, CheckpointImplementation, CheckpointImplementationContext, StreamResumePosition } from './CheckpointImplementation.js';
4
+ /**
5
+ * Sentinel checkpoint implementation, used for sources without a usable clusterTime
6
+ * (DocumentDB). The ordered LSN coordinate is a single shared sentinel checkpoint
7
+ * counter ({@link SENTINEL_CHECKPOINT_ID}), observed through the change stream:
8
+ *
9
+ * - Batch checkpoints advance the global counter and stamp it with this stream's
10
+ * id, so the stream recognises its own private barriers by content (stream_id
11
+ * + counter) rather than by cross-document event ordering.
12
+ * - Standalone bumps (write checkpoint heads, snapshot markers) advance the same
13
+ * counter with a null stream_id; every stream observes these as the global
14
+ * coordinate.
15
+ * - Keepalives advance the counter without persisting; the bump's own event
16
+ * flows through the stream and commits via the standalone handling,
17
+ * preserving the "commit only what the stream has seen" barrier property.
18
+ *
19
+ * See docs/documentdb/documentdb-lsn-sentinel-checkpoints.md for the full design.
20
+ */
21
+ export declare class SentinelCheckpointImplementation implements CheckpointImplementation {
22
+ private context;
23
+ readonly zeroLsn: string;
24
+ /**
25
+ * The highest global sentinel value proven so far, merged monotonically from
26
+ * the resume seed, standalone events and embedded barrier values. Needed
27
+ * for lsnFromResumeToken: per-batch resume markers carry only a resume token,
28
+ * so they need the latest observed coordinate paired in.
29
+ */
30
+ private position;
31
+ constructor(context: CheckpointImplementationContext);
32
+ parseResumePosition(lsn: string): StreamResumePosition;
33
+ seedPosition(lsn: string | null): void;
34
+ logResume(lsn: string): void;
35
+ createStandaloneCheckpoint(): Promise<string>;
36
+ createBatchCheckpoint(): Promise<string>;
37
+ createFirstBarrier(): Promise<string | null>;
38
+ keepalive(_batch: storage.BucketStorageBatch, _resumeToken: mongo.ResumeToken): Promise<void>;
39
+ lsnFromResumeToken(resumeToken: mongo.ResumeToken): string;
40
+ createReplicationHead<T>(callback: ReplicationHeadCallback<T>): Promise<T>;
41
+ readonly event: CheckpointEventApi;
42
+ readonly checkpointClearFilter: mongo.Filter<mongo.Document>;
43
+ /** Never move the position backwards — replayed or reordered events must not regress the coordinate. */
44
+ private mergePosition;
45
+ /**
46
+ * Read the sentinel counter from a sentinel checkpoint post-image.
47
+ *
48
+ * The `i` field is required: every sentinel write `$inc`s it. If it is
49
+ * missing, the document was replaced externally, which destroys the LSN
50
+ * coordinate system (a re-created counter restarts below already-committed
51
+ * LSNs). Invalidate the stream so replication restarts from scratch instead
52
+ * of stalling against a broken coordinate.
53
+ */
54
+ private readSentinel;
55
+ }
@@ -0,0 +1,222 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { JSONBig } from '@powersync/service-jsonbig';
3
+ import { SentinelLSN } from '../../common/SentinelLSN.js';
4
+ import { ChangeStreamInvalidatedError } from '../ChangeStream.js';
5
+ import { createSentinelCheckpointLsn, SENTINEL_CHECKPOINT_ID } from '../MongoRelation.js';
6
+ import { getCheckpointId } from './CheckpointImplementation.js';
7
+ /**
8
+ * Sentinel checkpoint implementation, used for sources without a usable clusterTime
9
+ * (DocumentDB). The ordered LSN coordinate is a single shared sentinel checkpoint
10
+ * counter ({@link SENTINEL_CHECKPOINT_ID}), observed through the change stream:
11
+ *
12
+ * - Batch checkpoints advance the global counter and stamp it with this stream's
13
+ * id, so the stream recognises its own private barriers by content (stream_id
14
+ * + counter) rather than by cross-document event ordering.
15
+ * - Standalone bumps (write checkpoint heads, snapshot markers) advance the same
16
+ * counter with a null stream_id; every stream observes these as the global
17
+ * coordinate.
18
+ * - Keepalives advance the counter without persisting; the bump's own event
19
+ * flows through the stream and commits via the standalone handling,
20
+ * preserving the "commit only what the stream has seen" barrier property.
21
+ *
22
+ * See docs/documentdb/documentdb-lsn-sentinel-checkpoints.md for the full design.
23
+ */
24
+ export class SentinelCheckpointImplementation {
25
+ context;
26
+ zeroLsn = SentinelLSN.ZERO.comparable;
27
+ /**
28
+ * The highest global sentinel value proven so far, merged monotonically from
29
+ * the resume seed, standalone events and embedded barrier values. Needed
30
+ * for lsnFromResumeToken: per-batch resume markers carry only a resume token,
31
+ * so they need the latest observed coordinate paired in.
32
+ */
33
+ position = SentinelLSN.ZERO.sentinel;
34
+ constructor(context) {
35
+ this.context = context;
36
+ }
37
+ parseResumePosition(lsn) {
38
+ const parsed = SentinelLSN.fromSerialized(lsn);
39
+ return { resumeAfter: parsed.resumeToken ?? null, startAfter: null };
40
+ }
41
+ seedPosition(lsn) {
42
+ this.position = lsn == null ? SentinelLSN.ZERO.sentinel : SentinelLSN.fromSerialized(lsn).sentinel;
43
+ }
44
+ logResume(lsn) {
45
+ const parsed = SentinelLSN.fromSerialized(lsn);
46
+ this.context.logger.info(`Resume streaming at sentinel ${parsed.sentinel} / ${parsed}`);
47
+ }
48
+ async createStandaloneCheckpoint() {
49
+ return createSentinelCheckpointLsn(this.context.client, this.context.db);
50
+ }
51
+ async createBatchCheckpoint() {
52
+ // Advance the shared sentinel checkpoint — the global source-database
53
+ // coordinate. It must be shared so the LSN domain survives new
54
+ // ChangeStream instances and new sync rules.
55
+ // This advance is associated with the change stream in order to track stream
56
+ // barriers. The returned LSN (counter only, no resume token) is the barrier
57
+ // marker matched by resolvesBarrier.
58
+ return createSentinelCheckpointLsn(this.context.client, this.context.db, this.context.checkpointStreamId);
59
+ }
60
+ async createFirstBarrier() {
61
+ // The barrier marker is an opaque content-matched marker, not a resume
62
+ // position, so there is no LSN to open the stream from: a fresh DocumentDB
63
+ // stream opens from "now" and the snapshot loop re-creates barriers until
64
+ // one is observed.
65
+ await this.createBatchCheckpoint();
66
+ return null;
67
+ }
68
+ async keepalive(_batch, _resumeToken) {
69
+ // Advance the shared sentinel, but do not persist a checkpoint here. The
70
+ // bump is stamped with this stream's id, so its own change event flows
71
+ // through the stream as an own-barrier event and is committed by the
72
+ // own-barrier handling, which advances the ordered LSN prefix and refreshes
73
+ // the resume token (using the event's own token).
74
+ //
75
+ // Why bump at all: with an unchanged sentinel, LSN comparison against the
76
+ // previously persisted LSN falls to the opaque base64 token suffix, which
77
+ // is not lexicographically meaningful — storage would silently reject
78
+ // roughly half of plain token refreshes, leaving the persisted resume
79
+ // token to go stale on an idle stream. (The timestamp implementation avoids this
80
+ // because its keepalive timestamp is parsed from the resume token itself,
81
+ // so the ordered prefix always advances with the token.)
82
+ //
83
+ // Why not persist immediately: writes that landed after this empty batch
84
+ // was read — including a write checkpoint head — would be covered by the
85
+ // persisted LSN before the stream has processed them, allowing write
86
+ // checkpoints to resolve before the corresponding data is replicated.
87
+ // Committing only when the bump's event is observed preserves the
88
+ // "commit only what the stream has seen" barrier property.
89
+ await createSentinelCheckpointLsn(this.context.client, this.context.db, this.context.checkpointStreamId);
90
+ this.context.logger.info(`Idle change stream (sentinel implementation). Bumped sentinel to advance the checkpoint.`);
91
+ }
92
+ lsnFromResumeToken(resumeToken) {
93
+ // Pair the bare token with the current coordinate. The coordinate is
94
+ // frozen between checkpoint events, so a per-batch resume marker only
95
+ // advances the token; that is all resumption needs (see the design doc).
96
+ return new SentinelLSN({ sentinel: this.position, resume_token: resumeToken }).comparable;
97
+ }
98
+ async createReplicationHead(callback) {
99
+ const head = await createSentinelCheckpointLsn(this.context.client, this.context.db);
100
+ const result = await callback(head);
101
+ // Create another bump to ensure movement after the reported head. This
102
+ // covers the race where the head's own event is committed before the
103
+ // write checkpoint document is stored.
104
+ // Note that this checkpoint should not be associated with a change stream Id.
105
+ await createSentinelCheckpointLsn(this.context.client, this.context.db);
106
+ return result;
107
+ }
108
+ event = {
109
+ observe: (doc) => {
110
+ const checkpointId = getCheckpointId(doc);
111
+ if (checkpointId != SENTINEL_CHECKPOINT_ID) {
112
+ // The sentinel implementation only uses the SENTINEL_CHECKPOINT_ID
113
+ // document; anything else (including the timestamp impl's standalone
114
+ // document) is foreign.
115
+ return 'foreign';
116
+ }
117
+ const fullDoc = deserializeFullDocument(doc);
118
+ if (fullDoc == null) {
119
+ // An insert/update/replace on our sentinel document must carry a
120
+ // post-image. A missing fullDocument means the document was deleted or
121
+ // replaced out from under us, which destroys the coordinate; invalidate
122
+ // so replication restarts clean instead of stalling.
123
+ throw new ChangeStreamInvalidatedError('Sentinel checkpoint event has no fullDocument — cannot read the sentinel', new Error(`Unexpected ${doc.operationType} event on the sentinel checkpoint document`));
124
+ }
125
+ const streamId = fullDoc.stream_id;
126
+ let kind;
127
+ if (streamId == null) {
128
+ // No stream_id: a standalone bump (write checkpoint head, snapshot
129
+ // marker). Every stream tracks these as the global coordinate.
130
+ kind = 'standalone';
131
+ }
132
+ else if (this.context.checkpointStreamId.equals(streamId)) {
133
+ // Stamped with our id: one of our own private batch/keepalive barriers.
134
+ kind = 'own-barrier';
135
+ }
136
+ else {
137
+ // Another stream's private barrier — ignore.
138
+ return 'foreign';
139
+ }
140
+ // Both kinds carry the global coordinate in `i`; keep our position current.
141
+ this.mergePosition(this.readSentinel(fullDoc));
142
+ return kind;
143
+ },
144
+ lsn: (doc) => {
145
+ const fullDoc = deserializeFullDocument(doc);
146
+ if (fullDoc == null) {
147
+ throw new ChangeStreamInvalidatedError('Sentinel checkpoint event has no fullDocument — cannot read the sentinel', new Error(`Unexpected ${doc.operationType} event on the sentinel checkpoint document`));
148
+ }
149
+ // Checkpoint events carry the global coordinate in `i`; pair that exact
150
+ // coordinate with this event's resume token. Plain data-batch resume
151
+ // markers use lsnFromResumeToken, which pairs the token with the tracked
152
+ // position instead.
153
+ return new SentinelLSN({
154
+ sentinel: this.readSentinel(fullDoc),
155
+ resume_token: doc._id
156
+ }).comparable;
157
+ },
158
+ resolvesBarrier: (marker, doc) => {
159
+ const fullDoc = deserializeFullDocument(doc);
160
+ if (fullDoc == null) {
161
+ this.context.logger.warn('Checkpoint event missing fullDocument — cannot match sentinel barrier');
162
+ return false;
163
+ }
164
+ const parsed = SentinelLSN.fromSerialized(marker);
165
+ return this.context.checkpointStreamId.equals(fullDoc.stream_id) && fullDoc.i >= parsed.sentinel;
166
+ }
167
+ };
168
+ // The sentinel checkpoint document must survive restarts (hence the $ne
169
+ // below — the startup cleanup deletes every other checkpoint document). Its
170
+ // counter is the globally-ordered component of every committed LSN, including
171
+ // write checkpoint heads. Deleting it would re-seed the counter on the next
172
+ // upsert, risking moving the LSN coordinate system backwards: new commits
173
+ // could compare below the persisted last_checkpoint_lsn (so storage rejects
174
+ // them via checkpointBlocked and the checkpoint stalls), and new write
175
+ // checkpoint heads could resolve against old, higher committed LSNs before
176
+ // their data has actually replicated.
177
+ //
178
+ // Note: this only protects against our own startup cleanup. The global
179
+ // LSN coordinate still lives in a user-visible collection, so a consumer
180
+ // can delete it in their source database. Dropping the whole checkpoints
181
+ // collection is detected (the streaming loop invalidates the stream on the
182
+ // collection drop event). Deleting just this document is mitigated by
183
+ // createSentinelCheckpointLsn seeding re-created counters at the current
184
+ // epoch seconds, so the coordinate jumps forward instead of resetting
185
+ // below already-committed LSNs.
186
+ checkpointClearFilter = { _id: { $ne: SENTINEL_CHECKPOINT_ID } };
187
+ /** Never move the position backwards — replayed or reordered events must not regress the coordinate. */
188
+ mergePosition(observed) {
189
+ if (observed > this.position) {
190
+ this.position = observed;
191
+ }
192
+ }
193
+ /**
194
+ * Read the sentinel counter from a sentinel checkpoint post-image.
195
+ *
196
+ * The `i` field is required: every sentinel write `$inc`s it. If it is
197
+ * missing, the document was replaced externally, which destroys the LSN
198
+ * coordinate system (a re-created counter restarts below already-committed
199
+ * LSNs). Invalidate the stream so replication restarts from scratch instead
200
+ * of stalling against a broken coordinate.
201
+ */
202
+ readSentinel(fullDoc) {
203
+ if (fullDoc.i == null) {
204
+ throw new ChangeStreamInvalidatedError('Sentinel checkpoint document has no `i` field — cannot read the sentinel',
205
+ // JSONBig.stringify, since the post-image is deserialized with useBigInt64.
206
+ new Error(`Sentinel checkpoint document: ${JSONBig.stringify(fullDoc)}`));
207
+ }
208
+ return fullDoc.i;
209
+ }
210
+ }
211
+ function deserializeFullDocument(doc) {
212
+ const memo = doc;
213
+ if (memo.parsedFullDocument !== undefined) {
214
+ return memo.parsedFullDocument;
215
+ }
216
+ const fullDocument = 'fullDocument' in doc ? doc.fullDocument : null;
217
+ // fullDocument is a raw BSON Buffer from parseChangeDocument.
218
+ const parsed = fullDocument ? mongo.BSON.deserialize(fullDocument, { useBigInt64: true }) : null;
219
+ memo.parsedFullDocument = parsed;
220
+ return parsed;
221
+ }
222
+ //# sourceMappingURL=SentinelCheckpointImplementation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SentinelCheckpointImplementation.js","sourceRoot":"","sources":["../../../src/replication/checkpoints/SentinelCheckpointImplementation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,gCAAgC,CAAC;AAEvD,OAAO,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAA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C,WAAW,CAAC,YAAsB,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3G,IAAI,CAAC,kBAAkB,GAAG,MAAM,CAAC;IACjC,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { ReplicationHeadCallback, storage } from '@powersync/service-core';
3
+ import { CheckpointEventApi, CheckpointImplementation, CheckpointImplementationContext, StreamResumePosition } from './CheckpointImplementation.js';
4
+ /**
5
+ * Standard MongoDB checkpoint implementation. The ordered LSN coordinate is the oplog
6
+ * clusterTime — unique per operation, monotonic, and parseable from resume
7
+ * tokens. Barriers and event LSNs are plain comparable LSN strings.
8
+ */
9
+ export declare class TimestampCheckpointImplementation implements CheckpointImplementation {
10
+ private context;
11
+ readonly zeroLsn: string;
12
+ constructor(context: CheckpointImplementationContext);
13
+ parseResumePosition(lsn: string): StreamResumePosition;
14
+ seedPosition(_lsn: string | null): void;
15
+ logResume(lsn: string): void;
16
+ createStandaloneCheckpoint(): Promise<string>;
17
+ createBatchCheckpoint(): Promise<string>;
18
+ createFirstBarrier(): Promise<string | null>;
19
+ keepalive(batch: storage.BucketStorageBatch, resumeToken: mongo.ResumeToken): Promise<void>;
20
+ lsnFromResumeToken(resumeToken: mongo.ResumeToken): string;
21
+ createReplicationHead<T>(callback: ReplicationHeadCallback<T>): Promise<T>;
22
+ readonly event: CheckpointEventApi;
23
+ readonly checkpointClearFilter: mongo.Filter<mongo.Document>;
24
+ }
@@ -0,0 +1,113 @@
1
+ import { ServiceAssertionError } from '@powersync/lib-services-framework';
2
+ import { MongoLSN } from '../../common/MongoLSN.js';
3
+ import { createCheckpoint, SENTINEL_CHECKPOINT_ID, STANDALONE_CHECKPOINT_ID } from '../MongoRelation.js';
4
+ import { CHECKPOINTS_COLLECTION, timestampToDate } from '../replication-utils.js';
5
+ import { getCheckpointId, getEventTimestamp } from './CheckpointImplementation.js';
6
+ /**
7
+ * Standard MongoDB checkpoint implementation. The ordered LSN coordinate is the oplog
8
+ * clusterTime — unique per operation, monotonic, and parseable from resume
9
+ * tokens. Barriers and event LSNs are plain comparable LSN strings.
10
+ */
11
+ export class TimestampCheckpointImplementation {
12
+ context;
13
+ zeroLsn = MongoLSN.ZERO.comparable;
14
+ constructor(context) {
15
+ this.context = context;
16
+ }
17
+ parseResumePosition(lsn) {
18
+ const parsed = MongoLSN.fromSerialized(lsn);
19
+ return { resumeAfter: parsed.resumeToken ?? null, startAfter: parsed.timestamp };
20
+ }
21
+ seedPosition(_lsn) {
22
+ // The coordinate comes from each event's clusterTime; no state to seed.
23
+ }
24
+ logResume(lsn) {
25
+ const parsed = MongoLSN.fromSerialized(lsn);
26
+ // It is normal for this to be a minute or two old when there is a low volume
27
+ // of ChangeStream events.
28
+ const tokenAgeSeconds = Math.round((Date.now() - timestampToDate(parsed.timestamp).getTime()) / 1000);
29
+ this.context.logger.info(`Resume streaming at ${parsed.timestamp.inspect()} / ${parsed} | Token age: ${tokenAgeSeconds}s`);
30
+ }
31
+ async createStandaloneCheckpoint() {
32
+ return createCheckpoint(this.context.db, STANDALONE_CHECKPOINT_ID);
33
+ }
34
+ async createBatchCheckpoint() {
35
+ return createCheckpoint(this.context.db, this.context.checkpointStreamId);
36
+ }
37
+ async createFirstBarrier() {
38
+ // The barrier marker is a comparable LSN; resume the snapshot stream from it.
39
+ return this.createBatchCheckpoint();
40
+ }
41
+ async keepalive(batch, resumeToken) {
42
+ // Parse the timestamp from the resume token. The ordered LSN prefix
43
+ // advances together with the token, so persisting is always safe.
44
+ const { comparable: lsn, timestamp } = MongoLSN.fromResumeToken(resumeToken);
45
+ await batch.keepalive(lsn);
46
+ // Log the token update. This helps as a general "replication is still active" message in the logs.
47
+ // This token would typically be around 10s behind.
48
+ this.context.logger.info(`Idle change stream. Persisted resumeToken for ${timestampToDate(timestamp).toISOString()}`);
49
+ }
50
+ lsnFromResumeToken(resumeToken) {
51
+ // The timestamp is embedded in the resume token.
52
+ return MongoLSN.fromResumeToken(resumeToken).comparable;
53
+ }
54
+ async createReplicationHead(callback) {
55
+ const session = this.context.client.startSession();
56
+ try {
57
+ await this.context.db.command({ hello: 1 }, { session });
58
+ const head = session.clusterTime?.clusterTime;
59
+ if (head == null) {
60
+ throw new ServiceAssertionError(`clusterTime not available for write checkpoint`);
61
+ }
62
+ const r = await callback(new MongoLSN({ timestamp: head }).comparable);
63
+ // Trigger a change on the changestream, so that the write checkpoint
64
+ // is processed without waiting for other writes.
65
+ await this.context.db.collection(CHECKPOINTS_COLLECTION).findOneAndUpdate({
66
+ _id: STANDALONE_CHECKPOINT_ID
67
+ }, {
68
+ $inc: { i: 1 }
69
+ }, {
70
+ upsert: true,
71
+ returnDocument: 'after',
72
+ session
73
+ });
74
+ const time = session.operationTime;
75
+ if (time == null) {
76
+ throw new ServiceAssertionError(`operationTime not available for write checkpoint`);
77
+ }
78
+ else if (time.lt(head)) {
79
+ throw new ServiceAssertionError(`operationTime must be > clusterTime`);
80
+ }
81
+ return r;
82
+ }
83
+ finally {
84
+ await session.endSession();
85
+ }
86
+ }
87
+ event = {
88
+ observe: (doc) => {
89
+ const checkpointId = getCheckpointId(doc);
90
+ if (checkpointId == null || checkpointId == SENTINEL_CHECKPOINT_ID) {
91
+ return 'foreign';
92
+ }
93
+ // The STANDALONE_CHECKPOINT_ID is only used for the TimestampCheckpointImplementation
94
+ if (checkpointId == STANDALONE_CHECKPOINT_ID) {
95
+ return 'standalone';
96
+ }
97
+ return this.context.checkpointStreamId.equals(checkpointId) ? 'own-barrier' : 'foreign';
98
+ },
99
+ lsn: (doc) => {
100
+ return new MongoLSN({
101
+ timestamp: getEventTimestamp(doc),
102
+ resume_token: doc._id
103
+ }).comparable;
104
+ },
105
+ resolvesBarrier: (marker, doc) => {
106
+ // Barrier markers are comparable LSNs in this implementation.
107
+ return this.event.lsn(doc) >= marker;
108
+ }
109
+ };
110
+ // It's safe to clear the entire _powersync_checkpoints collection in this mode.
111
+ checkpointClearFilter = {};
112
+ }
113
+ //# sourceMappingURL=TimestampCheckpointImplementation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TimestampCheckpointImplementation.js","sourceRoot":"","sources":["../../../src/replication/checkpoints/TimestampCheckpointImplementation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAE1E,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACzG,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EAIL,eAAe,EACf,iBAAiB,EAElB,MAAM,+BAA+B,CAAC;AAEvC;;;;GAIG;AACH,MAAM,OAAO,iCAAiC;IAGxB;IAFX,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC;IAE5C,YAAoB,OAAwC;QAAxC,YAAO,GAAP,OAAO,CAAiC;IAAG,CAAC;IAEhE,mBAAmB,CAAC,GAAW;QAC7B,MAAM,MAAM,GAAG,QAAQ,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,IAAI,EAAE,UAAU,EAAE,MAAM,CAAC,SAAS,EAAE,CAAC;IACnF,CAAC;IAED,YAAY,CAAC,IAAmB;QAC9B,wEAAwE;IAC1E,CAAC;IAED,SAAS,CAAC,GAAW;QACnB,MAAM,MAAM,GAAG,QAAQ,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QAC5C,6EAA6E;QAC7E,0BAA0B;QAC1B,MAAM,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,eAAe,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,CAAC,GAAG,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AY,IAAI,sBAAsB,EAAE,CAAC;gBACnE,OAAO,SAAS,CAAC;YACnB,CAAC;YACD,sFAAsF;YACtF,IAAI,YAAY,IAAI,wBAAwB,EAAE,CAAC;gBAC7C,OAAO,YAAY,CAAC;YACtB,CAAC;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC;QAC1F,CAAC;QAED,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;YACX,OAAO,IAAI,QAAQ,CAAC;gBAClB,SAAS,EAAE,iBAAiB,CAAC,GAAG,CAAC;gBACjC,YAAY,EAAE,GAAG,CAAC,GAAG;aACtB,CAAC,CAAC,UAAU,CAAC;QAChB,CAAC;QAED,eAAe,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE;YAC/B,8DAA8D;YAC9D,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC;QACvC,CAAC;KACF,CAAC;IAEF,gFAAgF;IACvE,qBAAqB,GAAiC,EAAE,CAAC;CACnE"}
@@ -0,0 +1,6 @@
1
+ import { CheckpointImplementation, CheckpointImplementationContext } from './CheckpointImplementation.js';
2
+ /**
3
+ * Select the checkpoint implementation for a source: sentinel-based for DocumentDB
4
+ * DB, clusterTime-based for standard MongoDB.
5
+ */
6
+ export declare function createCheckpointImplementation(isDocumentDb: boolean, context: CheckpointImplementationContext): CheckpointImplementation;
@@ -0,0 +1,10 @@
1
+ import { SentinelCheckpointImplementation } from './SentinelCheckpointImplementation.js';
2
+ import { TimestampCheckpointImplementation } from './TimestampCheckpointImplementation.js';
3
+ /**
4
+ * Select the checkpoint implementation for a source: sentinel-based for DocumentDB
5
+ * DB, clusterTime-based for standard MongoDB.
6
+ */
7
+ export function createCheckpointImplementation(isDocumentDb, context) {
8
+ return isDocumentDb ? new SentinelCheckpointImplementation(context) : new TimestampCheckpointImplementation(context);
9
+ }
10
+ //# sourceMappingURL=create-checkpoint-implementation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-checkpoint-implementation.js","sourceRoot":"","sources":["../../../src/replication/checkpoints/create-checkpoint-implementation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,iCAAiC,EAAE,MAAM,wCAAwC,CAAC;AAE3F;;;GAGG;AACH,MAAM,UAAU,8BAA8B,CAC5C,YAAqB,EACrB,OAAwC;IAExC,OAAO,YAAY,CAAC,CAAC,CAAC,IAAI,gCAAgC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,iCAAiC,CAAC,OAAO,CAAC,CAAC;AACvH,CAAC"}
@@ -1,5 +1,11 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
1
2
  import * as bson from 'bson';
2
3
  import { MongoManager } from './MongoManager.js';
3
4
  export declare const CHECKPOINTS_COLLECTION = "_powersync_checkpoints";
5
+ /**
6
+ * Detect whether the connected server is DocumentDB. DocumentDB lacks usable
7
+ * clusterTime/operationTime and uses the sentinel checkpoint implementation.
8
+ */
9
+ export declare function detectDocumentDb(db: mongo.Db): Promise<boolean>;
4
10
  export declare function checkSourceConfiguration(connectionManager: MongoManager): Promise<void>;
5
11
  export declare function timestampToDate(timestamp: bson.Timestamp): Date;