@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.
- package/CHANGELOG.md +21 -0
- package/dist/replication/ChangeStream.d.ts +14 -0
- package/dist/replication/ChangeStream.js +241 -195
- package/dist/replication/ChangeStream.js.map +1 -1
- package/dist/replication/MongoSnapshotter.d.ts +7 -0
- package/dist/replication/MongoSnapshotter.js +65 -37
- package/dist/replication/MongoSnapshotter.js.map +1 -1
- package/package.json +9 -9
- package/src/replication/ChangeStream.ts +278 -211
- package/src/replication/MongoSnapshotter.ts +73 -42
- package/test/src/change_stream_abort.test.ts +5 -1
- package/test/src/offloaded_replication.test.ts +558 -0
- package/test/src/snapshot_progress_interval.test.ts +147 -0
- package/test/src/stream_progress.test.ts +24 -8
- package/test/src/stream_progress_interval.test.ts +311 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,558 @@
|
|
|
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 { MongoSnapshotter } from '@module/replication/MongoSnapshotter.js';
|
|
6
|
+
import { mongo } from '@powersync/lib-service-mongodb';
|
|
7
|
+
import { ReplicationAbortedError } from '@powersync/lib-services-framework';
|
|
8
|
+
import { storage } from '@powersync/service-core';
|
|
9
|
+
import { METRICS_HELPER } from '@powersync/service-core-tests';
|
|
10
|
+
import {
|
|
11
|
+
MongoBucketStorageOptions,
|
|
12
|
+
MongoSyncBucketStorage,
|
|
13
|
+
OperationBatch,
|
|
14
|
+
test_utils
|
|
15
|
+
} from '@powersync/service-module-mongodb-storage';
|
|
16
|
+
import { BSON } from 'bson';
|
|
17
|
+
import { performance } from 'node:perf_hooks';
|
|
18
|
+
import { describe, expect, test, vi } from 'vitest';
|
|
19
|
+
import { openChangeStreamTestContext } from './change_stream_test_setup.js';
|
|
20
|
+
import { DATABASE_TYPE, DatabaseType } from './DatabaseType.js';
|
|
21
|
+
import { env } from './env.js';
|
|
22
|
+
|
|
23
|
+
type ObjectStorage = NonNullable<MongoBucketStorageOptions['objectStorage']>;
|
|
24
|
+
type StoredObject = Awaited<ReturnType<ObjectStorage['get']>>;
|
|
25
|
+
|
|
26
|
+
// Keep the real storage packing, upload-marker, publication and read paths. Only remote object I/O
|
|
27
|
+
// is in memory, so tests can block or fail it deterministically and retain it across restarts.
|
|
28
|
+
class MemoryObjects implements ObjectStorage {
|
|
29
|
+
readonly data = new Map<string, StoredObject>();
|
|
30
|
+
|
|
31
|
+
async put(...[path, data, metadata, options]: Parameters<ObjectStorage['put']>) {
|
|
32
|
+
options?.signal?.throwIfAborted();
|
|
33
|
+
this.data.set(path, { data, metadata });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async get(...[path, options]: Parameters<ObjectStorage['get']>) {
|
|
37
|
+
options?.signal?.throwIfAborted();
|
|
38
|
+
const object = this.data.get(path);
|
|
39
|
+
if (object == null) {
|
|
40
|
+
throw new Error(`Object not found: ${path}`);
|
|
41
|
+
}
|
|
42
|
+
return object;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async *list(...[prefix, options]: Parameters<ObjectStorage['list']>) {
|
|
46
|
+
for (const path of this.data.keys()) {
|
|
47
|
+
options?.signal?.throwIfAborted();
|
|
48
|
+
if (path.startsWith(prefix)) {
|
|
49
|
+
yield path;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async delete(...[paths, options]: Parameters<ObjectStorage['delete']>) {
|
|
55
|
+
options?.signal?.throwIfAborted();
|
|
56
|
+
for (const path of paths) {
|
|
57
|
+
this.data.delete(path);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async deletePrefix(...[prefix, options]: Parameters<ObjectStorage['deletePrefix']>) {
|
|
62
|
+
const paths = [];
|
|
63
|
+
for await (const path of this.list(prefix, options)) {
|
|
64
|
+
paths.push(path);
|
|
65
|
+
}
|
|
66
|
+
await this.delete(paths, options);
|
|
67
|
+
return { objectCount: paths.length };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Deadlines diagnose a missing synchronization event; ordering assertions use the gates themselves.
|
|
72
|
+
async function waitFor<T>(promise: Promise<T>, description: string): Promise<T> {
|
|
73
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
74
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
75
|
+
timer = setTimeout(() => reject(new Error(`Timed out waiting for ${description}`)), 10000);
|
|
76
|
+
timer.unref();
|
|
77
|
+
});
|
|
78
|
+
try {
|
|
79
|
+
return await Promise.race([promise, timeout]);
|
|
80
|
+
} finally {
|
|
81
|
+
clearTimeout(timer!);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const CONFIG = `
|
|
86
|
+
config:
|
|
87
|
+
edition: 3
|
|
88
|
+
streams:
|
|
89
|
+
global:
|
|
90
|
+
query: SELECT _id AS id, description FROM documents
|
|
91
|
+
`;
|
|
92
|
+
|
|
93
|
+
function fixture() {
|
|
94
|
+
const objects = new MemoryObjects();
|
|
95
|
+
const { factory } = test_utils.mongoTestStorageFactoryGenerator({
|
|
96
|
+
url: env.MONGO_TEST_URL,
|
|
97
|
+
isCI: env.CI,
|
|
98
|
+
supportsMultipleSyncConfigs: true,
|
|
99
|
+
inlineThresholdBytes: 0,
|
|
100
|
+
objectStorage: objects
|
|
101
|
+
});
|
|
102
|
+
return { objects, factory };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function lease(context: Awaited<ReturnType<typeof openChangeStreamTestContext>>) {
|
|
106
|
+
return (context.storage! as MongoSyncBucketStorage).replicationStream.current_lock!;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function insertRows(context: Awaited<ReturnType<typeof openChangeStreamTestContext>>) {
|
|
110
|
+
await context.db
|
|
111
|
+
.collection<{ _id: number; description: string }>('documents')
|
|
112
|
+
.insertMany([1, 2, 3, 4].map((_id) => ({ _id, description: `row ${_id}` })));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function expectRecoveredRows(context: Awaited<ReturnType<typeof openChangeStreamTestContext>>) {
|
|
116
|
+
context.startStreaming();
|
|
117
|
+
const ops = await context.getBucketData('global|0[]');
|
|
118
|
+
const latest = new Map<string, string>();
|
|
119
|
+
for (const op of ops) {
|
|
120
|
+
if (op.op == 'PUT') {
|
|
121
|
+
latest.set(op.object_id!, JSON.parse(op.data!).description);
|
|
122
|
+
} else if (op.op == 'REMOVE') {
|
|
123
|
+
latest.delete(op.object_id!);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
expect([...latest.entries()].sort()).toEqual([1, 2, 3, 4].map((id) => [String(id), `row ${id}`]));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
describe.skipIf(!env.TEST_MONGO_STORAGE || DATABASE_TYPE == DatabaseType.DOCUMENTDB)(
|
|
130
|
+
'v4 offloaded replication progress',
|
|
131
|
+
{ timeout: 30_000 },
|
|
132
|
+
() => {
|
|
133
|
+
test.each(['shutdown', 'upload failure', 'publication failure'] as const)(
|
|
134
|
+
'streaming %s drains or replays the pending prefix',
|
|
135
|
+
async (scenario) => {
|
|
136
|
+
const { objects, factory } = fixture();
|
|
137
|
+
{
|
|
138
|
+
await using context = await openChangeStreamTestContext(factory, { storageVersion: 4 });
|
|
139
|
+
await context.updateSyncRules(CONFIG);
|
|
140
|
+
await context.db.createCollection('documents');
|
|
141
|
+
await context.replicateSnapshot();
|
|
142
|
+
await context.getCheckpoint();
|
|
143
|
+
await context.stop();
|
|
144
|
+
await insertRows(context);
|
|
145
|
+
}
|
|
146
|
+
{
|
|
147
|
+
const entered = Promise.withResolvers<void>();
|
|
148
|
+
const release = Promise.withResolvers<void>();
|
|
149
|
+
const handled = Promise.withResolvers<void>();
|
|
150
|
+
const failure = new Error(`injected ${scenario}`);
|
|
151
|
+
let page = 0;
|
|
152
|
+
let finalLsn: string | undefined;
|
|
153
|
+
const provider = {
|
|
154
|
+
...DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER,
|
|
155
|
+
openChangeStream: ({
|
|
156
|
+
open
|
|
157
|
+
}: Parameters<typeof DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER.openChangeStream>[0]) =>
|
|
158
|
+
(async function* (): AsyncGenerator<MongoReplicationStreamBatch> {
|
|
159
|
+
for await (const source of open({})) {
|
|
160
|
+
for (const change of source.events) {
|
|
161
|
+
if (!('ns' in change.event) || change.event.ns.coll != 'documents') {
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
yield createMongoReplicationStreamBatch({
|
|
165
|
+
events: [change],
|
|
166
|
+
resolveResumeToken: () => change.event._id
|
|
167
|
+
});
|
|
168
|
+
if (++page == 2) {
|
|
169
|
+
finalLsn = MongoLSN.fromResumeToken(change.event._id).comparable;
|
|
170
|
+
handled.resolve();
|
|
171
|
+
context.abort();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
})()
|
|
177
|
+
};
|
|
178
|
+
await using context = await openChangeStreamTestContext(factory, {
|
|
179
|
+
storageVersion: 4,
|
|
180
|
+
doNotClear: true,
|
|
181
|
+
streamOptions: { streamingProgressIntervalMs: 60000, createReplicationQueryProvider: () => provider }
|
|
182
|
+
});
|
|
183
|
+
await context.loadActiveSyncRules();
|
|
184
|
+
const before = await context.storage!.getStatus();
|
|
185
|
+
const checkpointBefore = await context.storage!.getCheckpoint();
|
|
186
|
+
// Exercise the automatic pipeline with small real source pages.
|
|
187
|
+
using _limit = vi.spyOn(OperationBatch.prototype, 'shouldFlush').mockReturnValue(true);
|
|
188
|
+
using _clock = vi.spyOn(performance, 'now').mockReturnValue(0);
|
|
189
|
+
const put = objects.put.bind(objects);
|
|
190
|
+
using uploads = vi.spyOn(objects, 'put').mockImplementation(async (...args) => {
|
|
191
|
+
entered.resolve();
|
|
192
|
+
await release.promise;
|
|
193
|
+
if (scenario == 'upload failure') {
|
|
194
|
+
throw failure;
|
|
195
|
+
}
|
|
196
|
+
return put(...args);
|
|
197
|
+
});
|
|
198
|
+
const saved: string[] = [];
|
|
199
|
+
context.storage!.registerListener({
|
|
200
|
+
batchStarted: (writer) => {
|
|
201
|
+
const setResumeLsn = writer.setResumeLsn.bind(writer);
|
|
202
|
+
vi.spyOn(writer, 'setResumeLsn').mockImplementation(async (lsn) => {
|
|
203
|
+
await setResumeLsn(lsn);
|
|
204
|
+
saved.push(lsn);
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
const running = context.streamer.streamChangesInternal().catch((error: unknown) => error);
|
|
209
|
+
let settled = false;
|
|
210
|
+
void running.then(() => {
|
|
211
|
+
settled = true;
|
|
212
|
+
});
|
|
213
|
+
try {
|
|
214
|
+
await waitFor(entered.promise, 'entered');
|
|
215
|
+
await waitFor(handled.promise, 'handled');
|
|
216
|
+
const pipeline = lease(context).replicationPipeline!;
|
|
217
|
+
expect(pipeline.pendingCount).toBe(2);
|
|
218
|
+
expect(saved).toEqual([]);
|
|
219
|
+
expect((await context.storage!.getStatus()).resumeLsn).toBe(before.resumeLsn);
|
|
220
|
+
expect(settled).toBe(false);
|
|
221
|
+
if (scenario == 'publication failure') {
|
|
222
|
+
const session = pipeline.publicationSession;
|
|
223
|
+
const transaction = session.withTransaction.bind(session);
|
|
224
|
+
vi.spyOn(session, 'withTransaction').mockImplementationOnce(async (callback, options) => {
|
|
225
|
+
return transaction(async (activeSession) => {
|
|
226
|
+
await callback(activeSession);
|
|
227
|
+
// Fail after real writes, so the test also proves the publication is rolled back.
|
|
228
|
+
throw failure;
|
|
229
|
+
}, options);
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
} finally {
|
|
233
|
+
release.resolve();
|
|
234
|
+
context.abort();
|
|
235
|
+
await running;
|
|
236
|
+
}
|
|
237
|
+
const error = await running;
|
|
238
|
+
expect(uploads).toHaveBeenCalled();
|
|
239
|
+
const pipeline = lease(context).replicationPipeline!;
|
|
240
|
+
expect(pipeline.pendingCount).toBe(0);
|
|
241
|
+
expect(pipeline.accountedBytes).toBe(0);
|
|
242
|
+
expect(pipeline.overlayEntryCount).toBe(0);
|
|
243
|
+
expect((await context.storage!.getCheckpoint()).lsn).toBe(checkpointBefore.lsn);
|
|
244
|
+
if (scenario == 'shutdown') {
|
|
245
|
+
expect(error).toBeInstanceOf(ReplicationAbortedError);
|
|
246
|
+
expect(saved).toEqual([finalLsn]);
|
|
247
|
+
expect((await context.storage!.getStatus()).resumeLsn).toBe(finalLsn);
|
|
248
|
+
expect(objects.data.size).toBe(2);
|
|
249
|
+
} else {
|
|
250
|
+
expect(error).toBeInstanceOf(ReplicationAbortedError);
|
|
251
|
+
expect(saved).toEqual([]);
|
|
252
|
+
expect((await context.storage!.getStatus()).resumeLsn).toBe(before.resumeLsn);
|
|
253
|
+
expect(lease(context).signal.aborted).toBe(true);
|
|
254
|
+
expect(lease(context).signal.reason).toMatchObject({ cause: failure });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
// Reopen both source and storage. Reads hydrate the actual offloaded payloads, including
|
|
258
|
+
// rows flushed before a shutdown and rows replayed after a failed publication.
|
|
259
|
+
await using resumed = await openChangeStreamTestContext(factory, { storageVersion: 4, doNotClear: true });
|
|
260
|
+
await resumed.loadActiveSyncRules();
|
|
261
|
+
using reads = vi.spyOn(objects, 'get');
|
|
262
|
+
await expectRecoveredRows(resumed);
|
|
263
|
+
expect(reads).toHaveBeenCalled();
|
|
264
|
+
}
|
|
265
|
+
);
|
|
266
|
+
|
|
267
|
+
test.each(['shutdown', 'upload failure', 'publication failure'] as const)(
|
|
268
|
+
'snapshot %s preserves a durable cursor and recovers all offloaded rows',
|
|
269
|
+
async (scenario) => {
|
|
270
|
+
const { objects, factory } = fixture();
|
|
271
|
+
let durableCount = 0;
|
|
272
|
+
{
|
|
273
|
+
await using context = await openChangeStreamTestContext(factory, { storageVersion: 4 });
|
|
274
|
+
await context.updateSyncRules(CONFIG);
|
|
275
|
+
await insertRows(context);
|
|
276
|
+
const abort = new AbortController();
|
|
277
|
+
const snapshotter = new MongoSnapshotter({
|
|
278
|
+
storage: context.storage!,
|
|
279
|
+
connections: context.connectionManager,
|
|
280
|
+
metrics: METRICS_HELPER.metricsEngine,
|
|
281
|
+
abortSignal: abort.signal,
|
|
282
|
+
checkpointStreamId: new mongo.ObjectId(),
|
|
283
|
+
snapshotChunkLength: 1,
|
|
284
|
+
snapshotProgressIntervalMs: 60000
|
|
285
|
+
});
|
|
286
|
+
let now = 0;
|
|
287
|
+
using _clock = vi.spyOn(performance, 'now').mockImplementation(() => now);
|
|
288
|
+
await snapshotter.setupCheckpointsCollection();
|
|
289
|
+
await snapshotter.queueSnapshotTables(null);
|
|
290
|
+
let rows = 0;
|
|
291
|
+
let failPublication = false;
|
|
292
|
+
let progressTable: storage.SourceTable | undefined;
|
|
293
|
+
const failure = new Error(`injected ${scenario}`);
|
|
294
|
+
const create = context.storage!.createWriter.bind(context.storage!);
|
|
295
|
+
using _create = vi.spyOn(context.storage!, 'createWriter').mockImplementation(async (...args) => {
|
|
296
|
+
const writer = await create(...args);
|
|
297
|
+
const save = writer.save.bind(writer);
|
|
298
|
+
vi.spyOn(writer, 'save').mockImplementation(async (record) => {
|
|
299
|
+
const result = await save(record);
|
|
300
|
+
rows++;
|
|
301
|
+
if (scenario == 'shutdown') {
|
|
302
|
+
if (rows == 2) {
|
|
303
|
+
abort.abort();
|
|
304
|
+
}
|
|
305
|
+
} else {
|
|
306
|
+
// Persist one page, then fail the next durable boundary using a controlled clock.
|
|
307
|
+
now += 60000;
|
|
308
|
+
}
|
|
309
|
+
return result;
|
|
310
|
+
});
|
|
311
|
+
const update = writer.updateTableProgress.bind(writer);
|
|
312
|
+
vi.spyOn(writer, 'updateTableProgress').mockImplementation(async (...args) => {
|
|
313
|
+
const result = await update(...args);
|
|
314
|
+
if (args[1].replicatedCount != null) {
|
|
315
|
+
durableCount = args[1].replicatedCount;
|
|
316
|
+
progressTable = result;
|
|
317
|
+
}
|
|
318
|
+
return result;
|
|
319
|
+
});
|
|
320
|
+
return writer;
|
|
321
|
+
});
|
|
322
|
+
const put = objects.put.bind(objects);
|
|
323
|
+
let uploads = 0;
|
|
324
|
+
using _uploads = vi.spyOn(objects, 'put').mockImplementation(async (...args) => {
|
|
325
|
+
if (++uploads == 2) {
|
|
326
|
+
if (scenario == 'upload failure') {
|
|
327
|
+
throw failure;
|
|
328
|
+
}
|
|
329
|
+
failPublication = scenario == 'publication failure';
|
|
330
|
+
}
|
|
331
|
+
return put(...args);
|
|
332
|
+
});
|
|
333
|
+
const session = lease(context).session;
|
|
334
|
+
const transaction = session.withTransaction.bind(session);
|
|
335
|
+
using _transaction = vi.spyOn(session, 'withTransaction').mockImplementation(async (callback, options) => {
|
|
336
|
+
return transaction(async (activeSession) => {
|
|
337
|
+
const result = await callback(activeSession);
|
|
338
|
+
if (failPublication) {
|
|
339
|
+
throw failure;
|
|
340
|
+
}
|
|
341
|
+
return result;
|
|
342
|
+
}, options);
|
|
343
|
+
});
|
|
344
|
+
await expect(snapshotter.replicationLoop()).rejects.toThrow(
|
|
345
|
+
scenario == 'shutdown' ? 'Aborted initial replication' : `injected ${scenario}`
|
|
346
|
+
);
|
|
347
|
+
expect(rows).toBe(2);
|
|
348
|
+
expect(durableCount).toBe(scenario == 'shutdown' ? 2 : 1);
|
|
349
|
+
expect(BSON.deserialize(progressTable!.snapshotStatus!.lastKey!)._id).toBe(durableCount);
|
|
350
|
+
expect(progressTable!.snapshotComplete).toBe(false);
|
|
351
|
+
expect((await context.storage!.getStatus()).snapshotDone).toBe(false);
|
|
352
|
+
expect((await context.storage!.getCheckpoint()).lsn).toBeNull();
|
|
353
|
+
expect(uploads).toBeGreaterThan(0);
|
|
354
|
+
}
|
|
355
|
+
await using resumed = await openChangeStreamTestContext(factory, { storageVersion: 4, doNotClear: true });
|
|
356
|
+
await resumed.loadNextSyncRules();
|
|
357
|
+
const snapshotRows: string[] = [];
|
|
358
|
+
resumed.storage!.registerListener({
|
|
359
|
+
batchStarted: (writer) => {
|
|
360
|
+
if (!writer.skipExistingRows) {
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const save = writer.save.bind(writer);
|
|
364
|
+
vi.spyOn(writer, 'save').mockImplementation(async (record) => {
|
|
365
|
+
snapshotRows.push(String(record.after!._id));
|
|
366
|
+
return save(record);
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
await resumed.replicateSnapshot();
|
|
371
|
+
await expectRecoveredRows(resumed);
|
|
372
|
+
expect(snapshotRows).toEqual([1, 2, 3, 4].slice(durableCount).map(String));
|
|
373
|
+
}
|
|
374
|
+
);
|
|
375
|
+
|
|
376
|
+
test('concurrent snapshot and streaming writers share backpressure and publish a consistent checkpoint', async () => {
|
|
377
|
+
const { objects, factory } = fixture();
|
|
378
|
+
const sourceReady = Promise.withResolvers<void>();
|
|
379
|
+
const continueStreaming = Promise.withResolvers<void>();
|
|
380
|
+
const snapshotQueued = Promise.withResolvers<void>();
|
|
381
|
+
const startSnapshot = Promise.withResolvers<void>();
|
|
382
|
+
const snapshotFirstSaved = Promise.withResolvers<void>();
|
|
383
|
+
const continueSnapshot = Promise.withResolvers<void>();
|
|
384
|
+
const snapshotSecondAttempt = Promise.withResolvers<void>();
|
|
385
|
+
const streamStarted = Promise.withResolvers<void>();
|
|
386
|
+
const streamWarm = Promise.withResolvers<void>();
|
|
387
|
+
const streamSecondSaved = Promise.withResolvers<void>();
|
|
388
|
+
const streamThirdAttempt = Promise.withResolvers<void>();
|
|
389
|
+
const uploadEntered = Promise.withResolvers<void>();
|
|
390
|
+
const releaseUpload = Promise.withResolvers<void>();
|
|
391
|
+
let pausedSnapshot = false;
|
|
392
|
+
let holdUpload = false;
|
|
393
|
+
let heldUpload = false;
|
|
394
|
+
let snapshotSaves = 0;
|
|
395
|
+
let streamSaves = 0;
|
|
396
|
+
let secondSnapshotSaved = false;
|
|
397
|
+
let thirdStreamSaved = false;
|
|
398
|
+
await using context = await openChangeStreamTestContext(factory, {
|
|
399
|
+
storageVersion: 4,
|
|
400
|
+
streamOptions: {
|
|
401
|
+
snapshotChunkLength: 1,
|
|
402
|
+
snapshotProgressIntervalMs: 60000,
|
|
403
|
+
streamingProgressIntervalMs: 60000,
|
|
404
|
+
createReplicationQueryProvider: () => ({
|
|
405
|
+
...DEFAULT_MONGO_REPLICATION_QUERY_PROVIDER,
|
|
406
|
+
openChangeStream: ({ open }) =>
|
|
407
|
+
(async function* (): AsyncGenerator<MongoReplicationStreamBatch> {
|
|
408
|
+
let documents = 0;
|
|
409
|
+
for await (const source of open({})) {
|
|
410
|
+
for (const change of source.events) {
|
|
411
|
+
const document = 'ns' in change.event && change.event.ns.coll == 'documents';
|
|
412
|
+
if (document && documents == 0) {
|
|
413
|
+
// Queue all three writes before processing the first, so the source barrier
|
|
414
|
+
// requested by that first write follows the updates under test.
|
|
415
|
+
await sourceReady.promise;
|
|
416
|
+
}
|
|
417
|
+
yield createMongoReplicationStreamBatch({
|
|
418
|
+
events: [change],
|
|
419
|
+
resolveResumeToken: () => change.event._id
|
|
420
|
+
});
|
|
421
|
+
if (document && ++documents == 1) {
|
|
422
|
+
await continueStreaming.promise;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
})()
|
|
427
|
+
}),
|
|
428
|
+
snapshotHooks: {
|
|
429
|
+
beforeSnapshotStarted: async () => {
|
|
430
|
+
if (!pausedSnapshot) {
|
|
431
|
+
pausedSnapshot = true;
|
|
432
|
+
snapshotQueued.resolve();
|
|
433
|
+
await startSnapshot.promise;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
},
|
|
437
|
+
storageHooks: {
|
|
438
|
+
afterBatchFlush: async (writer) => {
|
|
439
|
+
if (!writer.skipExistingRows && streamSaves > 0) {
|
|
440
|
+
streamWarm.resolve();
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
await context.updateSyncRules(CONFIG);
|
|
447
|
+
await insertRows(context);
|
|
448
|
+
using _limit = vi.spyOn(OperationBatch.prototype, 'shouldFlush').mockReturnValue(true);
|
|
449
|
+
context.storage!.registerListener({
|
|
450
|
+
batchStarted: (writer) => {
|
|
451
|
+
if (!writer.skipExistingRows) {
|
|
452
|
+
const commit = writer.commit.bind(writer);
|
|
453
|
+
vi.spyOn(writer, 'commit').mockImplementation(async (...args) => {
|
|
454
|
+
const result = await commit(...args);
|
|
455
|
+
if (streamSaves == 0) {
|
|
456
|
+
streamStarted.resolve();
|
|
457
|
+
}
|
|
458
|
+
return result;
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
const save = writer.save.bind(writer);
|
|
462
|
+
vi.spyOn(writer, 'save').mockImplementation(async (record) => {
|
|
463
|
+
if (writer.skipExistingRows) {
|
|
464
|
+
if (++snapshotSaves == 2) {
|
|
465
|
+
snapshotSecondAttempt.resolve();
|
|
466
|
+
}
|
|
467
|
+
const result = await save(record);
|
|
468
|
+
if (snapshotSaves == 1) {
|
|
469
|
+
snapshotFirstSaved.resolve();
|
|
470
|
+
await continueSnapshot.promise;
|
|
471
|
+
} else if (snapshotSaves == 2) {
|
|
472
|
+
secondSnapshotSaved = true;
|
|
473
|
+
}
|
|
474
|
+
return result;
|
|
475
|
+
}
|
|
476
|
+
if (++streamSaves == 3) {
|
|
477
|
+
streamThirdAttempt.resolve();
|
|
478
|
+
}
|
|
479
|
+
const result = await save(record);
|
|
480
|
+
if (streamSaves == 2) {
|
|
481
|
+
streamSecondSaved.resolve();
|
|
482
|
+
} else if (streamSaves == 3) {
|
|
483
|
+
thirdStreamSaved = true;
|
|
484
|
+
}
|
|
485
|
+
return result;
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
const put = objects.put.bind(objects);
|
|
490
|
+
using _uploads = vi.spyOn(objects, 'put').mockImplementation(async (...args) => {
|
|
491
|
+
if (holdUpload && !heldUpload) {
|
|
492
|
+
heldUpload = true;
|
|
493
|
+
uploadEntered.resolve();
|
|
494
|
+
await releaseUpload.promise;
|
|
495
|
+
}
|
|
496
|
+
return put(...args);
|
|
497
|
+
});
|
|
498
|
+
const snapshot = context.replicateSnapshot().then(
|
|
499
|
+
() => null,
|
|
500
|
+
(error: unknown) => error
|
|
501
|
+
);
|
|
502
|
+
try {
|
|
503
|
+
await waitFor(snapshotQueued.promise, 'snapshotQueued');
|
|
504
|
+
await waitFor(streamStarted.promise, 'streamStarted');
|
|
505
|
+
const collection = context.db.collection<{ _id: string; description: string }>('documents');
|
|
506
|
+
await collection.insertOne({ _id: 'S', description: 'warm' });
|
|
507
|
+
await collection.updateOne({ _id: 'S' }, { $set: { description: 'latest' } });
|
|
508
|
+
await collection.insertOne({ _id: 'T', description: 'tail' });
|
|
509
|
+
sourceReady.resolve();
|
|
510
|
+
await waitFor(streamWarm.promise, 'streamWarm');
|
|
511
|
+
holdUpload = true;
|
|
512
|
+
startSnapshot.resolve();
|
|
513
|
+
await waitFor(uploadEntered.promise, 'uploadEntered');
|
|
514
|
+
await waitFor(snapshotFirstSaved.promise, 'snapshotFirstSaved');
|
|
515
|
+
continueStreaming.resolve();
|
|
516
|
+
await waitFor(streamSecondSaved.promise, 'streamSecondSaved');
|
|
517
|
+
continueSnapshot.resolve();
|
|
518
|
+
await waitFor(snapshotSecondAttempt.promise, 'snapshotSecondAttempt');
|
|
519
|
+
await waitFor(streamThirdAttempt.promise, 'streamThirdAttempt');
|
|
520
|
+
const pipeline = lease(context).replicationPipeline!;
|
|
521
|
+
expect(pipeline.pendingCount).toBe(2);
|
|
522
|
+
expect(pipeline.accountedBytes).toBeGreaterThan(0);
|
|
523
|
+
expect(pipeline.accountedBytes).toBeLessThan(64 * 1024 * 1024);
|
|
524
|
+
expect(secondSnapshotSaved).toBe(false);
|
|
525
|
+
expect(thirdStreamSaved).toBe(false);
|
|
526
|
+
expect((await context.storage!.getStatus()).snapshotDone).toBe(false);
|
|
527
|
+
expect((await context.storage!.getCheckpoint()).lsn).toBeNull();
|
|
528
|
+
} finally {
|
|
529
|
+
releaseUpload.resolve();
|
|
530
|
+
sourceReady.resolve();
|
|
531
|
+
continueStreaming.resolve();
|
|
532
|
+
startSnapshot.resolve();
|
|
533
|
+
continueSnapshot.resolve();
|
|
534
|
+
}
|
|
535
|
+
const snapshotError = await snapshot;
|
|
536
|
+
if (snapshotError != null) {
|
|
537
|
+
throw snapshotError;
|
|
538
|
+
}
|
|
539
|
+
const ops = await context.getBucketData('global|0[]');
|
|
540
|
+
const latest = new Map<string, string>();
|
|
541
|
+
for (const op of ops) {
|
|
542
|
+
if (op.op == 'PUT') {
|
|
543
|
+
latest.set(op.object_id!, JSON.parse(op.data!).description);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
expect([...latest.entries()].sort()).toEqual([
|
|
547
|
+
...[1, 2, 3, 4].map((id) => [String(id), `row ${id}`]),
|
|
548
|
+
['S', 'latest'],
|
|
549
|
+
['T', 'tail']
|
|
550
|
+
]);
|
|
551
|
+
await context.stop();
|
|
552
|
+
const pipeline = lease(context).replicationPipeline!;
|
|
553
|
+
expect(pipeline.pendingCount).toBe(0);
|
|
554
|
+
expect(pipeline.accountedBytes).toBe(0);
|
|
555
|
+
expect(pipeline.overlayEntryCount).toBe(0);
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
);
|