@powersync/service-module-mongodb 0.22.4 → 0.22.6

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.
@@ -0,0 +1,147 @@
1
+ import { MongoSnapshotter } from '@module/replication/MongoSnapshotter.js';
2
+ import { mongo } from '@powersync/lib-service-mongodb';
3
+ import { storage } from '@powersync/service-core';
4
+ import { METRICS_HELPER } from '@powersync/service-core-tests';
5
+ import * as bson from 'bson';
6
+ import { performance } from 'node:perf_hooks';
7
+ import { expect, test, vi } from 'vitest';
8
+ import { openChangeStreamTestContext } from './change_stream_test_setup.js';
9
+ import { env } from './env.js';
10
+ import { INITIALIZED_MONGO_STORAGE_FACTORY } from './util.js';
11
+
12
+ const CONFIG = `
13
+ config:
14
+ edition: 3
15
+ streams:
16
+ items:
17
+ query: SELECT _id AS id, description FROM test_data
18
+ `;
19
+
20
+ async function open(snapshotProgressIntervalMs?: number) {
21
+ const context = await openChangeStreamTestContext(INITIALIZED_MONGO_STORAGE_FACTORY.factory, { storageVersion: 4 });
22
+ await context.updateSyncRules(CONFIG);
23
+ await context.db
24
+ .collection<{ _id: string; description: string }>('test_data')
25
+ .insertMany(['A', 'B', 'C', 'D'].map((id) => ({ _id: id, description: id })));
26
+ const abort = new AbortController();
27
+ const snapshotter = new MongoSnapshotter({
28
+ storage: context.storage!,
29
+ connections: context.connectionManager,
30
+ metrics: METRICS_HELPER.metricsEngine,
31
+ abortSignal: abort.signal,
32
+ checkpointStreamId: new mongo.ObjectId(),
33
+ snapshotChunkLength: 1,
34
+ snapshotProgressIntervalMs
35
+ });
36
+ return { context, abort, snapshotter };
37
+ }
38
+
39
+ test.skipIf(!env.TEST_MONGO_STORAGE).each([
40
+ { interval: undefined, times: [0, 9999, 10000, 10001], counts: [3, 4] },
41
+ { interval: 50, times: [0, 49, 50, 51], counts: [3, 4] },
42
+ { interval: 0, times: [0, 0, 0, 0], counts: [1, 2, 3, 4] },
43
+ { interval: 60000, times: [0, 1, 2, 3], counts: [4] }
44
+ ])('snapshot progress interval $interval', async ({ interval, times, counts }) => {
45
+ const c = await open(interval);
46
+ await using context = c.context;
47
+ let now = 0;
48
+ using _clock = vi.spyOn(performance, 'now').mockImplementation(() => now);
49
+ const observed: number[] = [];
50
+ const order: string[] = [];
51
+ let rows = 0;
52
+ const create = context.storage!.createWriter.bind(context.storage!);
53
+ using _create = vi.spyOn(context.storage!, 'createWriter').mockImplementation(async (...args) => {
54
+ const writer = await create(...args);
55
+ const save = writer.save.bind(writer);
56
+ vi.spyOn(writer, 'save').mockImplementation(async (record) => {
57
+ const result = await save(record);
58
+ now = times[rows++];
59
+ return result;
60
+ });
61
+ const flush = writer.flush.bind(writer);
62
+ vi.spyOn(writer, 'flush').mockImplementation(async (...args) => {
63
+ const result = await flush(...args);
64
+ order.push('flush');
65
+ return result;
66
+ });
67
+ const update = writer.updateTableProgress.bind(writer);
68
+ vi.spyOn(writer, 'updateTableProgress').mockImplementation(async (table, status) => {
69
+ if (status.replicatedCount != null) {
70
+ expect(order.at(-1)).toBe('flush');
71
+ expect(bson.deserialize(status.lastKey!)._id).toBe(['A', 'B', 'C', 'D'][status.replicatedCount - 1]);
72
+ observed.push(status.replicatedCount);
73
+ order.push('progress');
74
+ }
75
+ return update(table, status);
76
+ });
77
+ return writer;
78
+ });
79
+ await c.snapshotter.setupCheckpointsCollection();
80
+ await c.snapshotter.queueSnapshotTables(null);
81
+ const running = c.snapshotter.replicationLoop().catch((error: unknown) => error);
82
+ try {
83
+ await c.snapshotter.waitForInitialSnapshot();
84
+ expect(rows).toBe(4);
85
+ expect(observed).toEqual(counts);
86
+ } finally {
87
+ c.abort.abort();
88
+ await running;
89
+ }
90
+ });
91
+
92
+ test.skipIf(!env.TEST_MONGO_STORAGE)('graceful abort persists the last complete page before the interval', async () => {
93
+ const c = await open(60000);
94
+ await using context = c.context;
95
+ let rows = 0;
96
+ let progressTable: storage.SourceTable | undefined;
97
+ const create = context.storage!.createWriter.bind(context.storage!);
98
+ using _create = vi.spyOn(context.storage!, 'createWriter').mockImplementation(async (...args) => {
99
+ const writer = await create(...args);
100
+ const save = writer.save.bind(writer);
101
+ vi.spyOn(writer, 'save').mockImplementation(async (record) => {
102
+ const result = await save(record);
103
+ if (++rows === 2) {
104
+ c.abort.abort();
105
+ }
106
+ return result;
107
+ });
108
+ const update = writer.updateTableProgress.bind(writer);
109
+ vi.spyOn(writer, 'updateTableProgress').mockImplementation(async (...args) => {
110
+ const result = await update(...args);
111
+ if (args[1].replicatedCount != null) {
112
+ progressTable = result;
113
+ }
114
+ return result;
115
+ });
116
+ return writer;
117
+ });
118
+ await c.snapshotter.setupCheckpointsCollection();
119
+ await c.snapshotter.queueSnapshotTables(null);
120
+ await expect(c.snapshotter.replicationLoop()).rejects.toThrow('Aborted initial replication');
121
+ expect(rows).toBe(2);
122
+ expect(progressTable!.snapshotStatus!.replicatedCount).toBe(2);
123
+ expect(progressTable!.snapshotComplete).toBe(false);
124
+ });
125
+
126
+ test.skipIf(!env.TEST_MONGO_STORAGE)('a failed flush never persists the pending cursor', async () => {
127
+ const c = await open(0);
128
+ await using context = c.context;
129
+ const observed: number[] = [];
130
+ const create = context.storage!.createWriter.bind(context.storage!);
131
+ using _create = vi.spyOn(context.storage!, 'createWriter').mockImplementation(async (...args) => {
132
+ const writer = await create(...args);
133
+ vi.spyOn(writer, 'flush').mockRejectedValueOnce(new Error('failed snapshot flush'));
134
+ const update = writer.updateTableProgress.bind(writer);
135
+ vi.spyOn(writer, 'updateTableProgress').mockImplementation(async (...args) => {
136
+ if (args[1].replicatedCount != null) {
137
+ observed.push(args[1].replicatedCount);
138
+ }
139
+ return update(...args);
140
+ });
141
+ return writer;
142
+ });
143
+ await c.snapshotter.setupCheckpointsCollection();
144
+ await c.snapshotter.queueSnapshotTables(null);
145
+ await expect(c.snapshotter.replicationLoop()).rejects.toThrow('failed snapshot flush');
146
+ expect(observed).toEqual([]);
147
+ });
@@ -84,10 +84,13 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB durable adapt
84
84
  doNotClear: true,
85
85
  streamOptions: {
86
86
  snapshotChunkLength: 5,
87
+ streamingProgressIntervalMs: 0,
87
88
  createReplicationQueryProvider: () => provider,
88
89
  storageHooks: {
89
90
  beforeBatchFlush: async () => {
90
- if (failFlush) throw new Error('injected retained-row flush failure');
91
+ if (failFlush) {
92
+ throw new Error('injected retained-row flush failure');
93
+ }
91
94
  }
92
95
  }
93
96
  }
@@ -111,7 +114,9 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB durable adapt
111
114
  });
112
115
  const result = await context.startStreaming();
113
116
  expect(result).toMatchObject({ status: 'rejected', reason: expect.any(Error) });
114
- if (result.status == 'rejected') expect(String(result.reason)).toContain('retained-row flush failure');
117
+ if (result.status == 'rejected') {
118
+ expect(String(result.reason)).toContain('retained-row flush failure');
119
+ }
115
120
  // Saving the later token despite the failed flush would skip document 1 on restart.
116
121
  expect(save).toHaveBeenCalledOnce();
117
122
  expect(setResumeLsn).not.toHaveBeenCalled();
@@ -156,7 +161,7 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB durable adapt
156
161
  await using context = await openChangeStreamTestContext(factory, {
157
162
  storageVersion,
158
163
  doNotClear: true,
159
- streamOptions: { snapshotChunkLength: 5 }
164
+ streamOptions: { snapshotChunkLength: 5, streamingProgressIntervalMs: 0 }
160
165
  });
161
166
  await context.loadActiveSyncRules();
162
167
  context.storage!.registerListener({
@@ -166,7 +171,9 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB durable adapt
166
171
  await setResumeLsn(lsn);
167
172
  // Abort only after the third position is persisted, so reopening uses an exact token
168
173
  // inside the transaction rather than the position recorded before any of its inserts.
169
- if (++progressCount == 3) context.abort(new Error('stop inside transaction'));
174
+ if (++progressCount == 3) {
175
+ context.abort(new Error('stop inside transaction'));
176
+ }
170
177
  });
171
178
  }
172
179
  });
@@ -225,6 +232,7 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB durable adapt
225
232
  doNotClear: true,
226
233
  streamOptions: {
227
234
  snapshotChunkLength: 5,
235
+ streamingProgressIntervalMs: 0,
228
236
  // Keep the test inside the idle keepalive interval: filtered activity must still save
229
237
  // progress while the checkpoint barrier is pending, rather than being treated as idle.
230
238
  keepaliveIntervalMs: 60_000,
@@ -254,7 +262,9 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB durable adapt
254
262
  }
255
263
  filtered += count;
256
264
  beforeFailure = positionBeforeBatch;
257
- if (scenario == 'adapter failure') throw new Error('injected adapter failure');
265
+ if (scenario == 'adapter failure') {
266
+ throw new Error('injected adapter failure');
267
+ }
258
268
  failFlush = scenario == 'flush failure';
259
269
  forwardedProgress = true;
260
270
  return progress;
@@ -267,7 +277,9 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB durable adapt
267
277
  savedPositions.push((await context.storage!.getStatus()).resumeLsn!);
268
278
  // End the successful case deliberately while the later checkpoint marker is
269
279
  // still pending, so assertions observe progress independently of a commit.
270
- if (savedPositions.length == 3) throw new Error('stopped after three safe boundaries');
280
+ if (savedPositions.length == 3) {
281
+ throw new Error('stopped after three safe boundaries');
282
+ }
271
283
  }
272
284
  }
273
285
  })();
@@ -283,7 +295,9 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB durable adapt
283
295
  // Inject at the public flush boundary to test flush-before-resume ordering on every backend.
284
296
  const originalFlush = batch.flush.bind(batch);
285
297
  vi.spyOn(batch, 'flush').mockImplementation(async (...args) => {
286
- if (failFlush) throw new Error('injected flush failure');
298
+ if (failFlush) {
299
+ throw new Error('injected flush failure');
300
+ }
287
301
  return originalFlush(...args);
288
302
  });
289
303
  const originalSave = batch.save.bind(batch);
@@ -306,7 +320,9 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB durable adapt
306
320
  });
307
321
  const result = await context.startStreaming();
308
322
  expect(result.status).toBe('rejected');
309
- if (result.status != 'rejected') throw new Error('Expected the controlled stop');
323
+ if (result.status != 'rejected') {
324
+ throw new Error('Expected the controlled stop');
325
+ }
310
326
  expect(String(result.reason)).toContain(
311
327
  scenario == 'progress' ? 'three safe boundaries' : `injected ${scenario}`
312
328
  );
@@ -0,0 +1,311 @@
1
+ import { MongoLSN } from '@module/common/MongoLSN.js';
2
+ import { DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER } from '@module/replication/MongoReplicationQueryProvider.js';
3
+ import { createMongoReplicationStreamBatch } from '@module/replication/MongoReplicationStream.js';
4
+ import type { MongoReplicationStreamBatch } from '@module/replication/MongoReplicationStreamTypes.js';
5
+ import { mongo } from '@powersync/lib-service-mongodb';
6
+ import { ReplicationAbortedError } from '@powersync/lib-services-framework';
7
+ import type { TestStorageFactory } from '@powersync/service-core';
8
+ import { performance } from 'node:perf_hooks';
9
+ import { describe, expect, test, vi } from 'vitest';
10
+ import { openChangeStreamTestContext } from './change_stream_test_setup.js';
11
+ import { DATABASE_TYPE, DatabaseType } from './DatabaseType.js';
12
+ import { env } from './env.js';
13
+ import { describeWithStorage, INITIALIZED_MONGO_STORAGE_FACTORY } from './util.js';
14
+
15
+ const CONFIG = `
16
+ config:
17
+ edition: 3
18
+ streams:
19
+ global:
20
+ query: SELECT _id AS id FROM documents
21
+ `;
22
+
23
+ // Queue real source changes after completing a snapshot, so each test can inspect streaming alone.
24
+ async function prepare(factory: TestStorageFactory = INITIALIZED_MONGO_STORAGE_FACTORY.factory, storageVersion = 4) {
25
+ await using context = await openChangeStreamTestContext(factory, { storageVersion });
26
+ await context.updateSyncRules(CONFIG);
27
+ await context.db.createCollection('documents');
28
+ await context.replicateSnapshot();
29
+ await context.getCheckpoint();
30
+ await context.stop();
31
+ await context.db.collection<{ _id: number }>('documents').insertMany([1, 2, 3, 4].map((_id) => ({ _id })));
32
+ }
33
+
34
+ describe.skipIf(!env.TEST_MONGO_STORAGE || DATABASE_TYPE == DatabaseType.DOCUMENTDB)(
35
+ 'streaming progress interval',
36
+ () => {
37
+ test.each([
38
+ { interval: undefined, times: [0, 9999, 10000, 10001], pages: [3, 4] },
39
+ { interval: 50, times: [0, 49, 50, 51], pages: [3, 4] },
40
+ { interval: 0, times: [0, 0, 0, 0], pages: [1, 2, 3, 4] },
41
+ { interval: 60000, times: [0, 1, 2, 3], pages: [4] }
42
+ ])('persists retained and filtered pages at interval $interval', async ({ interval, times, pages }) => {
43
+ await prepare();
44
+ let now = 0;
45
+ using _clock = vi.spyOn(performance, 'now').mockImplementation(() => now);
46
+ const tokens: string[] = [];
47
+ const saved: string[] = [];
48
+ const order: string[] = [];
49
+ const provider = {
50
+ ...DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER,
51
+ openChangeStream: ({ open }: Parameters<typeof DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER.openChangeStream>[0]) =>
52
+ (async function* (): AsyncGenerator<MongoReplicationStreamBatch> {
53
+ for await (const source of open({})) {
54
+ for (const change of source.events) {
55
+ if (!('ns' in change.event) || change.event.ns.coll != 'documents') {
56
+ continue;
57
+ }
58
+ tokens.push(MongoLSN.fromResumeToken(change.event._id).comparable);
59
+ now = times[tokens.length - 1];
60
+ // Alternate retained and excluded events. Keep each real event's exact recovery token
61
+ // while controlling page boundaries independently of MongoDB's adaptive transport size.
62
+ const filtered = tokens.length % 2 == 0;
63
+ yield createMongoReplicationStreamBatch({
64
+ events: filtered ? [] : [change],
65
+ resolveResumeToken: () => change.event._id,
66
+ resolveMetadata: () => ({ filteredCount: filtered ? 1 : 0 })
67
+ });
68
+ if (tokens.length == 4) {
69
+ context.abort();
70
+ return;
71
+ }
72
+ }
73
+ }
74
+ })()
75
+ };
76
+ await using context = await openChangeStreamTestContext(INITIALIZED_MONGO_STORAGE_FACTORY.factory, {
77
+ storageVersion: 4,
78
+ doNotClear: true,
79
+ streamOptions: { streamingProgressIntervalMs: interval, createReplicationQueryProvider: () => provider }
80
+ });
81
+ await context.loadActiveSyncRules();
82
+ const checkpointBefore = await context.storage!.getCheckpoint();
83
+ context.storage!.registerListener({
84
+ batchStarted: (batch) => {
85
+ const flush = batch.flush.bind(batch);
86
+ vi.spyOn(batch, 'flush').mockImplementation(async (...args) => {
87
+ const result = await flush(...args);
88
+ order.push('flush');
89
+ return result;
90
+ });
91
+ const setResumeLsn = batch.setResumeLsn.bind(batch);
92
+ vi.spyOn(batch, 'setResumeLsn').mockImplementation(async (lsn) => {
93
+ expect(order.at(-1)).toBe('flush');
94
+ await setResumeLsn(lsn);
95
+ order.push('resume');
96
+ saved.push(lsn);
97
+ });
98
+ }
99
+ });
100
+ await expect(context.streamer.streamChangesInternal()).rejects.toBeInstanceOf(ReplicationAbortedError);
101
+ expect(saved).toEqual(pages.map((page) => tokens[page - 1]));
102
+ expect((await context.storage!.getStatus()).resumeLsn).toBe(tokens[3]);
103
+ // Restart-only updates must leave client checkpoints behind the unread startup barrier.
104
+ expect((await context.storage!.getCheckpoint()).lsn).toBe(checkpointBefore.lsn);
105
+ });
106
+
107
+ test.each(['partial page', 'unsafe token', 'adapter failure', 'flush failure'] as const)(
108
+ 'shutdown and failure preserve safe recovery after %s',
109
+ async (scenario) => {
110
+ await prepare();
111
+ const tokens: string[] = [];
112
+ const saved: string[] = [];
113
+ let failFlush = false;
114
+ const abortCause = new Error('cancel test reader');
115
+ const provider = {
116
+ ...DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER,
117
+ openChangeStream: ({
118
+ open
119
+ }: Parameters<typeof DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER.openChangeStream>[0]) =>
120
+ (async function* (): AsyncGenerator<MongoReplicationStreamBatch> {
121
+ for await (const source of open({})) {
122
+ for (const change of source.events) {
123
+ if (!('ns' in change.event) || change.event.ns.coll != 'documents') {
124
+ continue;
125
+ }
126
+ tokens.push(MongoLSN.fromResumeToken(change.event._id).comparable);
127
+ yield createMongoReplicationStreamBatch({
128
+ events: (function* () {
129
+ yield change;
130
+ if (tokens.length == 2 && scenario == 'partial page') {
131
+ context.abort(abortCause);
132
+ }
133
+ })(),
134
+ resolveResumeToken: () => {
135
+ if (tokens.length == 2 && scenario == 'adapter failure') {
136
+ throw new Error('injected adapter failure');
137
+ }
138
+ return tokens.length == 2 && scenario == 'unsafe token' ? undefined : change.event._id;
139
+ }
140
+ });
141
+ if (tokens.length == 2) {
142
+ failFlush = scenario == 'flush failure';
143
+ context.abort(abortCause);
144
+ // Model the reader throwing its cancellation reason while fetching another page.
145
+ throw abortCause;
146
+ }
147
+ }
148
+ }
149
+ })()
150
+ };
151
+ await using context = await openChangeStreamTestContext(INITIALIZED_MONGO_STORAGE_FACTORY.factory, {
152
+ storageVersion: 4,
153
+ doNotClear: true,
154
+ streamOptions: { streamingProgressIntervalMs: 60000, createReplicationQueryProvider: () => provider }
155
+ });
156
+ await context.loadActiveSyncRules();
157
+ const originalLsn = (await context.storage!.getStatus()).resumeLsn;
158
+ context.storage!.registerListener({
159
+ batchStarted: (batch) => {
160
+ const flush = batch.flush.bind(batch);
161
+ vi.spyOn(batch, 'flush').mockImplementation(async (...args) => {
162
+ if (failFlush) {
163
+ throw new Error('injected flush failure');
164
+ }
165
+ return flush(...args);
166
+ });
167
+ const setResumeLsn = batch.setResumeLsn.bind(batch);
168
+ vi.spyOn(batch, 'setResumeLsn').mockImplementation(async (lsn) => {
169
+ await setResumeLsn(lsn);
170
+ saved.push(lsn);
171
+ });
172
+ }
173
+ });
174
+ await expect(context.streamer.streamChangesInternal()).rejects.toThrow(
175
+ scenario.includes('failure') ? `injected ${scenario}` : 'Replication stream aborted'
176
+ );
177
+ if (scenario.includes('failure')) {
178
+ expect(saved).toEqual([]);
179
+ expect((await context.storage!.getStatus()).resumeLsn).toBe(originalLsn);
180
+ } else {
181
+ expect(saved).toEqual([tokens[0]]);
182
+ expect((await context.storage!.getStatus()).resumeLsn).toBe(tokens[0]);
183
+ }
184
+ }
185
+ );
186
+
187
+ test.each([0, 60000])('checkpoint commits stay immediate at interval %i', async (interval) => {
188
+ await prepare();
189
+ const saved: string[] = [];
190
+ const committed: string[] = [];
191
+ let expectedCommit: string | undefined;
192
+ const provider = {
193
+ ...DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER,
194
+ openChangeStream: ({ open }: Parameters<typeof DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER.openChangeStream>[0]) =>
195
+ (async function* (): AsyncGenerator<MongoReplicationStreamBatch> {
196
+ for await (const source of open({})) {
197
+ for (const change of source.events) {
198
+ yield createMongoReplicationStreamBatch({
199
+ events: [change],
200
+ resolveResumeToken: () => change.event._id
201
+ });
202
+ if (committed.length > 0) {
203
+ expectedCommit = MongoLSN.fromResumeToken(change.event._id).comparable;
204
+ context.abort();
205
+ return;
206
+ }
207
+ }
208
+ }
209
+ })()
210
+ };
211
+ await using context = await openChangeStreamTestContext(INITIALIZED_MONGO_STORAGE_FACTORY.factory, {
212
+ storageVersion: 4,
213
+ doNotClear: true,
214
+ streamOptions: { streamingProgressIntervalMs: interval, createReplicationQueryProvider: () => provider }
215
+ });
216
+ await context.loadActiveSyncRules();
217
+ context.storage!.registerListener({
218
+ batchStarted: (batch) => {
219
+ const commit = batch.commit.bind(batch);
220
+ vi.spyOn(batch, 'commit').mockImplementation(async (lsn, ...args) => {
221
+ const result = await commit(lsn, ...args);
222
+ committed.push(lsn);
223
+ return result;
224
+ });
225
+ const setResumeLsn = batch.setResumeLsn.bind(batch);
226
+ vi.spyOn(batch, 'setResumeLsn').mockImplementation(async (lsn) => {
227
+ await setResumeLsn(lsn);
228
+ saved.push(lsn);
229
+ });
230
+ }
231
+ });
232
+ await expect(context.streamer.streamChangesInternal()).rejects.toBeInstanceOf(ReplicationAbortedError);
233
+ expect(committed).toEqual([expectedCommit]);
234
+ expect(saved).not.toContain(expectedCommit);
235
+ if (interval > 0) {
236
+ // The commit supersedes pending pages, so shutdown needs no restart-only update either.
237
+ expect(saved).toEqual([]);
238
+ }
239
+ expect((await context.storage!.getStatus()).resumeLsn).toBe(expectedCommit);
240
+ });
241
+
242
+ describeWithStorage({ timeout: 30_000 }, ({ factory, storageVersion }) => {
243
+ test('blocked checkpoints retain a restart-only update for shutdown', async () => {
244
+ await prepare(factory, storageVersion);
245
+ let blockedLsn: string | undefined;
246
+ const saved: string[] = [];
247
+ const provider = {
248
+ ...DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER,
249
+ openChangeStream: ({
250
+ open
251
+ }: Parameters<typeof DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER.openChangeStream>[0]) =>
252
+ (async function* (): AsyncGenerator<MongoReplicationStreamBatch> {
253
+ for await (const source of open({})) {
254
+ for (const change of source.events) {
255
+ yield createMongoReplicationStreamBatch({
256
+ events: [change],
257
+ resolveResumeToken: () => change.event._id
258
+ });
259
+ if (blockedLsn != null) {
260
+ context.abort();
261
+ return;
262
+ }
263
+ }
264
+ }
265
+ })()
266
+ };
267
+ await using context = await openChangeStreamTestContext(factory, {
268
+ storageVersion,
269
+ doNotClear: true,
270
+ streamOptions: { streamingProgressIntervalMs: 60000, createReplicationQueryProvider: () => provider }
271
+ });
272
+ await context.loadActiveSyncRules();
273
+ // Keep checkpoint publication blocked beyond every event in this test, using real storage metadata.
274
+ {
275
+ await using writer = await context.storage!.createWriter({
276
+ zeroLSN: MongoLSN.ZERO.comparable,
277
+ defaultSchema: context.db.databaseName,
278
+ storeCurrentData: false
279
+ });
280
+ const future = new MongoLSN({
281
+ timestamp: new mongo.Timestamp({ t: Math.floor(Date.now() / 1000) + 3600, i: 0 })
282
+ }).comparable;
283
+ await writer.markSnapshotDone(future);
284
+ }
285
+ const checkpointBefore = await context.storage!.getCheckpoint();
286
+ context.storage!.registerListener({
287
+ batchStarted: (batch) => {
288
+ const commit = batch.commit.bind(batch);
289
+ vi.spyOn(batch, 'commit').mockImplementation(async (lsn, ...args) => {
290
+ const result = await commit(lsn, ...args);
291
+ expect(result.checkpointBlocked).toBe(true);
292
+ expect(result.checkpointCreated).toBe(false);
293
+ blockedLsn = lsn;
294
+ return result;
295
+ });
296
+ const setResumeLsn = batch.setResumeLsn.bind(batch);
297
+ vi.spyOn(batch, 'setResumeLsn').mockImplementation(async (lsn) => {
298
+ await setResumeLsn(lsn);
299
+ saved.push(lsn);
300
+ });
301
+ }
302
+ });
303
+ await expect(context.streamer.streamChangesInternal()).rejects.toBeInstanceOf(ReplicationAbortedError);
304
+ expect(blockedLsn).toBeDefined();
305
+ expect(saved).toEqual([blockedLsn]);
306
+ expect((await context.storage!.getStatus()).resumeLsn).toBe(blockedLsn);
307
+ expect((await context.storage!.getCheckpoint()).lsn).toBe(checkpointBefore.lsn);
308
+ });
309
+ });
310
+ }
311
+ );