@powersync/service-module-mongodb 0.22.5 → 0.22.7

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.
@@ -37,6 +37,12 @@ export interface MongoSnapshotterOptions {
37
37
  abortSignal: AbortSignal;
38
38
  maxAwaitTimeMS?: number;
39
39
  snapshotChunkLength?: number;
40
+ /**
41
+ * Minimum time between durable snapshot progress updates, checked between pages.
42
+ * Defaults to 10_000ms; 0 persists every page. Final progress is always persisted.
43
+ * Automatic size-based storage flushes are independent of this interval.
44
+ */
45
+ snapshotProgressIntervalMs?: number;
40
46
  logger?: Logger;
41
47
  checkpointStreamId: mongo.ObjectId;
42
48
  storageHooks?: storage.StorageHooks;
@@ -70,6 +76,7 @@ export class MongoSnapshotter {
70
76
  private readonly queryProvider: MongoReplicationQueryProvider;
71
77
  private readonly maxAwaitTimeMS: number;
72
78
  private readonly snapshotChunkLength: number;
79
+ private readonly snapshotProgressIntervalMs: number;
73
80
  private readonly abortSignal: AbortSignal;
74
81
  private readonly logger: Logger;
75
82
  private readonly checkpointStreamId: mongo.ObjectId;
@@ -94,6 +101,7 @@ export class MongoSnapshotter {
94
101
  this.defaultDb = options.connections.db;
95
102
  this.maxAwaitTimeMS = options.maxAwaitTimeMS ?? 10_000;
96
103
  this.snapshotChunkLength = options.snapshotChunkLength ?? 6_000;
104
+ this.snapshotProgressIntervalMs = options.snapshotProgressIntervalMs ?? 10_000;
97
105
  this.abortSignal = options.abortSignal;
98
106
  this.logger = options.logger ?? options.storage.logger;
99
107
  this.checkpointStreamId = options.checkpointStreamId;
@@ -404,7 +412,8 @@ export class MongoSnapshotter {
404
412
  storeCurrentData: false,
405
413
  skipExistingRows: true,
406
414
  hooks: this.storageHooks,
407
- signal: this.abortSignal,
415
+ // Stop reading pages on cancellation, then persist the last complete page.
416
+ // The replication lease still cancels storage work if ownership is lost.
408
417
  tracer: new PerformanceTracer('MongoDB snapshot table')
409
418
  });
410
419
  // Get fresh table info, in case it was updated while queuing.
@@ -499,56 +508,78 @@ export class MongoSnapshotter {
499
508
  this.logger.info(`Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()}`);
500
509
  }
501
510
 
502
- let lastBatch = performance.now();
503
- let nextChunkPromise = query.nextChunk();
504
- while (true) {
505
- const { docs: docBatch, lastKey, bytes: chunkBytes } = await nextChunkPromise;
506
- if (docBatch.length == 0) {
507
- // No more data - stop iterating
508
- break;
509
- }
510
- bytesReplicatedMetric.add(chunkBytes);
511
- chunksReplicatedMetric.add(1);
512
-
513
- if (this.abortSignal.aborted) {
514
- throw new ReplicationAbortedError(`Aborted initial replication`, this.abortSignal.reason);
515
- }
516
-
517
- // Pre-fetch next batch, so that we can read and write concurrently
518
- nextChunkPromise = query.nextChunk();
519
- for (const buffer of docBatch) {
520
- const { row, replicaId } = this.sourceRowConverter.rawToSqliteRow(buffer);
521
- // This auto-flushes when the batch reaches its size limit
522
- await batch.save({
523
- tag: SaveOperationTag.INSERT,
524
- sourceTable: table,
525
- before: undefined,
526
- beforeReplicaId: undefined,
527
- after: row,
528
- afterReplicaId: replicaId
529
- });
511
+ let lastProgressAt = performance.now();
512
+ let pendingKey: Uint8Array | null = null;
513
+ let pendingProgress = false;
514
+ const persistProgress = async () => {
515
+ if (!pendingProgress) {
516
+ return;
530
517
  }
531
-
532
- // Important: flush before marking progress
518
+ // Important: flush before marking progress. Automatic size-based flushes
519
+ // keep storage work bounded between these less frequent durable barriers.
533
520
  await batch.flush();
534
- at += docBatch.length;
535
- rowsReplicatedMetric.add(docBatch.length);
536
-
537
521
  table = await batch.updateTableProgress(table, {
538
- lastKey,
522
+ lastKey: pendingKey,
539
523
  replicatedCount: at,
540
524
  totalEstimatedCount
541
525
  });
542
-
543
- const duration = performance.now() - lastBatch;
544
- lastBatch = performance.now();
526
+ const now = performance.now();
545
527
  this.logger.info(
546
- `Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()} in ${duration.toFixed(0)}ms`
528
+ `Replicating ${table.qualifiedName} ${table.formatSnapshotProgress()} in ${(now - lastProgressAt).toFixed(0)}ms`
547
529
  );
548
- this.touch();
530
+ lastProgressAt = now;
531
+ pendingProgress = false;
532
+ };
533
+ let nextChunkPromise = query.nextChunk();
534
+ try {
535
+ while (true) {
536
+ const { docs: docBatch, lastKey, bytes: chunkBytes } = await nextChunkPromise;
537
+ if (docBatch.length == 0) {
538
+ // No more data - stop iterating
539
+ break;
540
+ }
541
+ bytesReplicatedMetric.add(chunkBytes);
542
+ chunksReplicatedMetric.add(1);
543
+
544
+ if (this.abortSignal.aborted) {
545
+ // Preserve the last complete page on graceful shutdown, even if the
546
+ // persistence interval has not elapsed. Never advance into this page.
547
+ await persistProgress();
548
+ throw new ReplicationAbortedError(`Aborted initial replication`, this.abortSignal.reason);
549
+ }
550
+
551
+ // Pre-fetch next batch, so that we can read and write concurrently
552
+ nextChunkPromise = query.nextChunk();
553
+ for (const buffer of docBatch) {
554
+ const { row, replicaId } = this.sourceRowConverter.rawToSqliteRow(buffer);
555
+ // This auto-flushes when the batch reaches its size limit
556
+ await batch.save({
557
+ tag: SaveOperationTag.INSERT,
558
+ sourceTable: table,
559
+ before: undefined,
560
+ beforeReplicaId: undefined,
561
+ after: row,
562
+ afterReplicaId: replicaId
563
+ });
564
+ }
565
+
566
+ at += docBatch.length;
567
+ // Activity counters track processed source rows; the table cursor and
568
+ // progress log advance only at a durable persistence boundary.
569
+ rowsReplicatedMetric.add(docBatch.length);
570
+ pendingKey = lastKey;
571
+ pendingProgress = true;
572
+ if (performance.now() - lastProgressAt >= this.snapshotProgressIntervalMs || this.abortSignal.aborted) {
573
+ await persistProgress();
574
+ }
575
+ this.touch();
576
+ }
577
+ // A short snapshot must persist its final page too, before table completion.
578
+ await persistProgress();
579
+ } finally {
580
+ // In case the loop was interrupted, make sure we await the last promise.
581
+ await nextChunkPromise.catch(() => {});
549
582
  }
550
- // In case the loop was interrupted, make sure we await the last promise.
551
- await nextChunkPromise;
552
583
  }
553
584
 
554
585
  private async handleRelation(
@@ -74,7 +74,11 @@ describe.skipIf(DATABASE_TYPE == DatabaseType.DOCUMENTDB)('MongoDB change stream
74
74
  await using context = await openChangeStreamTestContext(factory, {
75
75
  storageVersion,
76
76
  doNotClear: true,
77
- streamOptions: { createReplicationQueryProvider: () => provider }
77
+ streamOptions: {
78
+ // This test isolates partially consumed batches from throttled earlier progress.
79
+ streamingProgressIntervalMs: 0,
80
+ createReplicationQueryProvider: () => provider
81
+ }
78
82
  });
79
83
  readResumeLsn = async () => (await context.storage!.getStatus()).resumeLsn;
80
84
  abort = (cause) => context.abort(cause);