@powersync/service-module-mongodb-storage 0.24.2 → 0.26.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 (105) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/migrations/db/migrations/1684951997326-init.js +3 -29
  3. package/dist/migrations/db/migrations/1684951997326-init.js.map +1 -1
  4. package/dist/migrations/db/migrations/1741697235857-bucket-state-index.js +3 -24
  5. package/dist/migrations/db/migrations/1741697235857-bucket-state-index.js.map +1 -1
  6. package/dist/migrations/db/migrations/1760433882550-bucket-state-index2.js +3 -24
  7. package/dist/migrations/db/migrations/1760433882550-bucket-state-index2.js.map +1 -1
  8. package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.d.ts +3 -0
  9. package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.js +21 -0
  10. package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.js.map +1 -0
  11. package/dist/storage/MongoBucketStorage.d.ts +9 -0
  12. package/dist/storage/MongoBucketStorage.js +60 -30
  13. package/dist/storage/MongoBucketStorage.js.map +1 -1
  14. package/dist/storage/implementation/MongoBucketBatch.d.ts +21 -16
  15. package/dist/storage/implementation/MongoBucketBatch.js +22 -125
  16. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  17. package/dist/storage/implementation/MongoStorageProvider.js +1 -0
  18. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
  19. package/dist/storage/implementation/MongoSyncBucketStorage.js +12 -5
  20. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
  21. package/dist/storage/implementation/MongoSyncRulesLock.d.ts +9 -2
  22. package/dist/storage/implementation/MongoSyncRulesLock.js +12 -3
  23. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
  24. package/dist/storage/implementation/OperationBatch.d.ts +10 -3
  25. package/dist/storage/implementation/OperationBatch.js +22 -13
  26. package/dist/storage/implementation/OperationBatch.js.map +1 -1
  27. package/dist/storage/implementation/ReplicationBatchLimits.d.ts +24 -0
  28. package/dist/storage/implementation/ReplicationBatchLimits.js +25 -0
  29. package/dist/storage/implementation/ReplicationBatchLimits.js.map +1 -0
  30. package/dist/storage/implementation/common/BatchOperationBuffer.d.ts +17 -1
  31. package/dist/storage/implementation/common/BatchOperationBuffer.js +22 -24
  32. package/dist/storage/implementation/common/BatchOperationBuffer.js.map +1 -1
  33. package/dist/storage/implementation/common/PersistedBatch.d.ts +2 -0
  34. package/dist/storage/implementation/common/PreparedPublication.d.ts +13 -9
  35. package/dist/storage/implementation/db.d.ts +2 -0
  36. package/dist/storage/implementation/db.js +14 -0
  37. package/dist/storage/implementation/db.js.map +1 -1
  38. package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +18 -1
  39. package/dist/storage/implementation/v1/MongoBucketBatchV1.js +99 -14
  40. package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
  41. package/dist/storage/implementation/v1/PersistedBatchV1.js +1 -1
  42. package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
  43. package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js +3 -1
  44. package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js.map +1 -1
  45. package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +39 -3
  46. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +356 -90
  47. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  48. package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -5
  49. package/dist/storage/implementation/v3/PersistedBatchV3.js +26 -13
  50. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  51. package/dist/storage/implementation/v3/ReplicationPipelineV3.d.ts +84 -0
  52. package/dist/storage/implementation/v3/ReplicationPipelineV3.js +187 -0
  53. package/dist/storage/implementation/v3/ReplicationPipelineV3.js.map +1 -0
  54. package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +4 -4
  55. package/dist/storage/implementation/v3/SourceRecordStoreV3.js +4 -4
  56. package/dist/storage/implementation/v3/chunking.js +7 -3
  57. package/dist/storage/implementation/v3/chunking.js.map +1 -1
  58. package/dist/types/types.d.ts +5 -0
  59. package/dist/types/types.js +4 -0
  60. package/dist/types/types.js.map +1 -1
  61. package/dist/utils/collection-sizes.d.ts +9 -0
  62. package/dist/utils/collection-sizes.js +95 -0
  63. package/dist/utils/collection-sizes.js.map +1 -0
  64. package/dist/utils/test-utils.js +1 -4
  65. package/dist/utils/test-utils.js.map +1 -1
  66. package/package.json +7 -7
  67. package/src/migrations/db/migrations/1684951997326-init.ts +3 -36
  68. package/src/migrations/db/migrations/1741697235857-bucket-state-index.ts +3 -31
  69. package/src/migrations/db/migrations/1760433882550-bucket-state-index2.ts +3 -31
  70. package/src/migrations/db/migrations/1794268800000-v1-storage-collections.ts +22 -0
  71. package/src/storage/MongoBucketStorage.ts +80 -31
  72. package/src/storage/implementation/MongoBucketBatch.ts +47 -137
  73. package/src/storage/implementation/MongoStorageProvider.ts +1 -0
  74. package/src/storage/implementation/MongoSyncBucketStorage.ts +13 -5
  75. package/src/storage/implementation/MongoSyncRulesLock.ts +13 -3
  76. package/src/storage/implementation/OperationBatch.ts +23 -15
  77. package/src/storage/implementation/ReplicationBatchLimits.ts +45 -0
  78. package/src/storage/implementation/common/BatchOperationBuffer.ts +21 -26
  79. package/src/storage/implementation/common/PersistedBatch.ts +2 -0
  80. package/src/storage/implementation/common/PreparedPublication.ts +13 -9
  81. package/src/storage/implementation/db.ts +15 -0
  82. package/src/storage/implementation/v1/MongoBucketBatchV1.ts +135 -17
  83. package/src/storage/implementation/v1/PersistedBatchV1.ts +2 -1
  84. package/src/storage/implementation/v1/VersionedPowerSyncMongoV1.ts +3 -1
  85. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +433 -101
  86. package/src/storage/implementation/v3/PersistedBatchV3.ts +26 -13
  87. package/src/storage/implementation/v3/ReplicationPipelineV3.ts +220 -0
  88. package/src/storage/implementation/v3/SourceRecordStoreV3.ts +4 -4
  89. package/src/storage/implementation/v3/chunking.ts +8 -3
  90. package/src/types/types.ts +7 -0
  91. package/src/utils/collection-sizes.ts +114 -0
  92. package/src/utils/test-utils.ts +1 -5
  93. package/test/src/concurrent_writers.test.ts +9 -15
  94. package/test/src/operation_batch.test.ts +207 -0
  95. package/test/src/prepared_publication.test.ts +187 -6
  96. package/test/src/replication_batch_config.test.ts +117 -0
  97. package/test/src/replication_pipeline.test.ts +738 -0
  98. package/test/src/replication_pipeline_benchmark.test.ts +133 -0
  99. package/test/src/replication_preparation.test.ts +4 -2
  100. package/test/src/replication_uploads.test.ts +28 -3
  101. package/test/src/storage.test.ts +24 -5
  102. package/test/src/storage_compacting.test.ts +16 -0
  103. package/test/src/storage_metrics.test.ts +88 -0
  104. package/test/src/v1_collections.test.ts +233 -0
  105. package/tsconfig.tsbuildinfo +1 -1
@@ -24,7 +24,12 @@ import {
24
24
  } from '@powersync/service-core';
25
25
  import { Semaphore } from 'async-mutex';
26
26
  import { ObjectId } from 'bson';
27
- import { DEFAULT_CLEAR_BATCH_THROTTLE_RATE, normalizeChunkCompactionConcurrency } from '../types/types.js';
27
+ import {
28
+ DEFAULT_CLEAR_BATCH_THROTTLE_RATE,
29
+ MongoReplicationBatchSize,
30
+ normalizeChunkCompactionConcurrency
31
+ } from '../types/types.js';
32
+ import { createCollectionSizeReader } from '../utils/collection-sizes.js';
28
33
  import { generateReplicationStreamName } from '../utils/util.js';
29
34
  import type { MongoSyncBucketStorage } from './implementation/createMongoSyncBucketStorage.js';
30
35
  import { createMongoSyncBucketStorage } from './implementation/createMongoSyncBucketStorage.js';
@@ -34,6 +39,11 @@ import { MongoChecksumOptions } from './implementation/MongoChecksums.js';
34
39
  import { MongoOpIdAllocator } from './implementation/MongoOpIdAllocator.js';
35
40
  import { MongoPersistedReplicationStream } from './implementation/MongoPersistedReplicationStream.js';
36
41
  import { MongoSyncRulesLock } from './implementation/MongoSyncRulesLock.js';
42
+ import {
43
+ DEFAULT_REPLICATION_BATCH_SIZE,
44
+ REPLICATION_BATCH_LIMITS,
45
+ ReplicationBatchLimits
46
+ } from './implementation/ReplicationBatchLimits.js';
37
47
  import { stopReplicationStreamPipeline } from './implementation/SyncRuleStateUpdate.js';
38
48
  import { SyncRuleDocumentV1 } from './implementation/v1/models.js';
39
49
  import { ObjectStorage } from './implementation/v3/object-storage/ObjectStorage.js';
@@ -42,6 +52,8 @@ import { VersionedPowerSyncMongoV3 } from './implementation/v3/VersionedPowerSyn
42
52
  import { ReplicationStreamDocumentV3, SyncConfigDefinition, SyncRuleConfigStateV3 } from './storage-index.js';
43
53
 
44
54
  export interface MongoBucketStorageOptions {
55
+ /** Coordinated replication limits. Default: medium. */
56
+ replicationBatchSize?: MongoReplicationBatchSize;
45
57
  checksumOptions?: Omit<MongoChecksumOptions, 'storageConfig'>;
46
58
  objectStorage?: ObjectStorage;
47
59
  inlineThresholdBytes?: number;
@@ -93,8 +105,10 @@ export class MongoBucketStorage extends storage.BucketStorageFactory {
93
105
  }
94
106
 
95
107
  private activeStorageCache: MongoSyncBucketStorage | undefined;
108
+ private readonly getCollectionSizes: ReturnType<typeof createCollectionSizeReader>;
96
109
 
97
110
  public readonly db: PowerSyncMongo;
111
+ public readonly replicationBatchLimits: ReplicationBatchLimits;
98
112
  public readonly chunkCompactionConcurrency: number;
99
113
  public readonly chunkCompactionSlots: Semaphore;
100
114
 
@@ -103,6 +117,8 @@ export class MongoBucketStorage extends storage.BucketStorageFactory {
103
117
  private options: MongoBucketStorageOptions
104
118
  ) {
105
119
  super();
120
+ this.replicationBatchLimits =
121
+ REPLICATION_BATCH_LIMITS[options.replicationBatchSize ?? DEFAULT_REPLICATION_BATCH_SIZE];
106
122
  this.chunkCompactionConcurrency = normalizeChunkCompactionConcurrency(
107
123
  options.chunkCompactionConcurrency,
108
124
  options.objectStorage != null
@@ -111,6 +127,7 @@ export class MongoBucketStorage extends storage.BucketStorageFactory {
111
127
  this.chunkCompactionSlots = new Semaphore(this.chunkCompactionConcurrency);
112
128
  this.client = db.client;
113
129
  this.db = db;
130
+ this.getCollectionSizes = createCollectionSizeReader(db.db, options.statsReadPreference);
114
131
  this.replicationStreamNamePrefix = options.replicationStreamNamePrefix;
115
132
  }
116
133
 
@@ -576,7 +593,67 @@ export class MongoBucketStorage extends storage.BucketStorageFactory {
576
593
  }
577
594
 
578
595
  private async withTransaction<T>(callback: (session: mongo.ClientSession) => Promise<T>): Promise<T> {
579
- return this.client.withSession((session) => session.withTransaction(callback));
596
+ // Serialize deployment with collection drops so newly deployed streams retain their storage.
597
+ return this.withStorageSchemaLock((refresh) =>
598
+ this.client.withSession((session) =>
599
+ session.withTransaction(async () => {
600
+ await refresh();
601
+ return callback(session);
602
+ })
603
+ )
604
+ );
605
+ }
606
+
607
+ private async withStorageSchemaLock<T>(callback: (refresh: () => Promise<void>) => Promise<T>): Promise<T> {
608
+ const name = 'v1-storage-collections';
609
+ // Seed by unique _id so concurrent first acquisitions share one lock document.
610
+ await this.db.db
611
+ .collection<{ _id: string; name: string }>('locks')
612
+ .updateOne({ _id: name }, { $setOnInsert: { name } }, { upsert: true });
613
+ const manager = new lib_mongo.locks.MongoLockManager({ collection: this.db.locks, name, timeout: 300_000 });
614
+ let result!: T;
615
+ await manager.lock(
616
+ async (refresh) => {
617
+ let lastRefresh = Date.now();
618
+ result = await callback(async () => {
619
+ // Rate-limit refresh writes; identical timestamps are not a modified document.
620
+ if (Date.now() - lastRefresh >= 30_000) {
621
+ await refresh();
622
+ lastRefresh = Date.now();
623
+ }
624
+ });
625
+ },
626
+ { max_wait_ms: 60_000 }
627
+ );
628
+ return result;
629
+ }
630
+
631
+ /** Returns true when no v1/v2 stream needs the shared data collections. */
632
+ async dropUnusedV1StorageCollections(signal?: AbortSignal): Promise<boolean> {
633
+ return this.withStorageSchemaLock(async (refresh) => {
634
+ signal?.throwIfAborted();
635
+ const live = await this.db.sync_rules.findOne(
636
+ {
637
+ $or: [{ storage_version: { $lt: storage.STORAGE_VERSION_3 } }, { storage_version: { $exists: false } }],
638
+ // Processing streams write data; errored streams still serve clients.
639
+ state: { $nin: [storage.SyncRuleState.STOP, storage.SyncRuleState.TERMINATED] }
640
+ },
641
+ { projection: { _id: 1 } }
642
+ );
643
+ if (live != null) return false;
644
+ for (const collection of this.db.v1DataCollections) {
645
+ signal?.throwIfAborted();
646
+ await refresh();
647
+ const dropped = await collection
648
+ .drop({ maxTimeMS: lib_mongo.db.MONGO_CLEAR_OPERATION_TIMEOUT_MS })
649
+ .catch((error) => {
650
+ if (!lib_mongo.isMongoNamespaceNotFoundError(error)) throw error;
651
+ return false;
652
+ });
653
+ if (dropped) logger.info(`Dropped unused v1/v2 storage collection: ${collection.collectionName}`);
654
+ }
655
+ return true;
656
+ });
580
657
  }
581
658
 
582
659
  /**
@@ -847,35 +924,7 @@ export class MongoBucketStorage extends storage.BucketStorageFactory {
847
924
  { nameOnly: true, readPreference: this.options.statsReadPreference }
848
925
  )
849
926
  .toArray();
850
- const sizesByCollection = new Map<string, number>();
851
- const statsPipeline: mongo.Document[] = [
852
- { $collStats: { storageStats: {} } },
853
- { $project: { ns: 1, size: '$storageStats.size' } }
854
- ];
855
- // MongoDB has a limit of 1000 stages per aggregation pipeline. Additionally, we want
856
- // to avoid too much work per aggregation, so we limit the number of collections per batch.
857
- const COLLECTIONS_PER_BATCH = 100;
858
- // Query batches sequentially so metrics collection does not fill the connection pool on standby pods.
859
- // If a collection disappears during aggregation, let the next metrics collection retry.
860
- for (let offset = 0; offset < collections.length; offset += COLLECTIONS_PER_BATCH) {
861
- const batch = collections.slice(offset, offset + COLLECTIONS_PER_BATCH);
862
- const pipeline = [
863
- ...statsPipeline,
864
- ...batch.slice(1).map((collection) => ({
865
- $unionWith: { coll: collection.name, pipeline: statsPipeline }
866
- }))
867
- ];
868
- const stats = await this.db.db
869
- .collection(batch[0].name)
870
- .aggregate<{ ns: string; size: number | bigint }>(pipeline, {
871
- readPreference: this.options.statsReadPreference
872
- })
873
- .toArray();
874
- for (const stat of stats) {
875
- const name = stat.ns.slice(this.db.db.databaseName.length + 1);
876
- sizesByCollection.set(name, (sizesByCollection.get(name) ?? 0) + Number(stat.size));
877
- }
878
- }
927
+ const sizesByCollection = await this.getCollectionSizes(collections);
879
928
 
880
929
  const v3StorageConfig = getMongoStorageConfig(storage.STORAGE_VERSION_3) as StorageConfig & {
881
930
  incrementalReprocessing: true;
@@ -43,10 +43,12 @@ import { REPLICATION_WRITE_OPTIONS } from './MongoReplicationOptions.js';
43
43
  import { MongoSyncRulesLock } from './MongoSyncRulesLock.js';
44
44
  import { MongoWriteBatch } from './MongoWriteBatch.js';
45
45
  import { OperationBatch, RecordOperation } from './OperationBatch.js';
46
+ import { ReplicationBatchLimits } from './ReplicationBatchLimits.js';
46
47
  import { ObjectStorage } from './v3/object-storage/ObjectStorage.js';
47
48
  import { createObjectStorageUsageWriterId } from './v3/object-storage/ObjectStorageUsage.js';
48
49
 
49
50
  export interface MongoBucketBatchOptions {
51
+ batchLimits: ReplicationBatchLimits;
50
52
  replicationLock: MongoSyncRulesLock;
51
53
  opIdAllocator: MongoOpIdAllocator;
52
54
  /**
@@ -116,8 +118,9 @@ export abstract class MongoBucketBatch
116
118
  protected readonly mapping: BucketDefinitionMapping;
117
119
  protected readonly objectStorageUsageWriterId = createObjectStorageUsageWriterId();
118
120
 
121
+ /** Mutable input for new saves; v3/v4 detach it when an operation is queued. */
119
122
  protected batch: OperationBatch | null = null;
120
- protected write_checkpoint_batch: storage.CustomWriteCheckpointOptions[] = [];
123
+
121
124
  protected readonly markRecordUnavailable: BucketStorageMarkRecordUnavailable | undefined;
122
125
  protected hooks: storage.StorageHooks | undefined;
123
126
  protected clearedError = false;
@@ -164,13 +167,14 @@ export abstract class MongoBucketBatch
164
167
  this.skipExistingRows = options.skipExistingRows;
165
168
  this.markRecordUnavailable = options.markRecordUnavailable;
166
169
  this.hooks = options.hooks;
167
- this.batch = new OperationBatch();
170
+ this.batch = new OperationBatch(this.options.batchLimits);
168
171
 
169
172
  this.tracer = options.tracer ?? new PerformanceTracer('MongoDB storage');
170
173
  }
171
174
 
172
175
  addCustomWriteCheckpoint(checkpoint: storage.BatchedCustomWriteCheckpointOptions): void {
173
- this.write_checkpoint_batch.push({
176
+ this.batch ??= new OperationBatch(this.options.batchLimits);
177
+ this.batch.addCustomWriteCheckpoint({
174
178
  ...checkpoint,
175
179
  sync_rules_id: this.replicationStreamId
176
180
  });
@@ -188,9 +192,7 @@ export abstract class MongoBucketBatch
188
192
 
189
193
  protected abstract cleanupDroppedSourceTables(sourceTables: storage.SourceTable[]): Promise<void>;
190
194
 
191
- async commit(lsn: string, options?: storage.BucketBatchCommitOptions): Promise<storage.CheckpointResult> {
192
- return this.withWriterLock(() => this.commitInternal(lsn, options));
193
- }
195
+ abstract commit(lsn: string, options?: storage.BucketBatchCommitOptions): Promise<storage.CheckpointResult>;
194
196
 
195
197
  protected abstract commitInternal(
196
198
  lsn: string,
@@ -247,54 +249,16 @@ export abstract class MongoBucketBatch
247
249
  ): Promise<storage.SourceTable[]>;
248
250
 
249
251
  /** Perform any version-specific setup required before writing custom checkpoints. */
250
- protected async prepareCustomWriteCheckpoints(): Promise<void> {}
252
+ protected abstract prepareCustomWriteCheckpoints(
253
+ checkpoints: readonly storage.CustomWriteCheckpointOptions[]
254
+ ): Promise<void>;
251
255
 
252
256
  async flush(options?: storage.BatchBucketFlushOptions): Promise<storage.FlushedResult | null> {
253
- return this.withWriterLock(() => this.flushInternal(options));
257
+ return this.withWriterLock(() => this.flushInternal(options), false);
254
258
  }
255
259
 
256
260
  /** Internal helpers require the public operation to hold the writer mutex. */
257
- protected async flushInternal(options?: storage.BatchBucketFlushOptions): Promise<storage.FlushedResult | null> {
258
- let result: storage.FlushedResult | null = null;
259
- // One flush may be split over multiple transactions.
260
- // Each flushInner() is one transaction.
261
- while (this.batch != null || this.write_checkpoint_batch.length > 0) {
262
- let r = await this.flushInner(options);
263
- if (r) {
264
- result = r;
265
- }
266
- }
267
- return result;
268
- }
269
-
270
- /** Publish the checkpoint in the final flush transaction, or use the empty-commit path. */
271
- protected async flushAndCommit<T>(
272
- checkpoint: (stream: SyncRuleDocumentBase, lastOp: InternalOpId, writes?: MongoWriteBatch) => Promise<T>,
273
- commitWithoutFlush: () => Promise<T>,
274
- options?: storage.BatchBucketFlushOptions,
275
- projection?: mongo.Document
276
- ): Promise<T> {
277
- if (this.batch == null && this.write_checkpoint_batch.length === 0) {
278
- return commitWithoutFlush();
279
- }
280
- let result!: T;
281
- while (this.batch != null || this.write_checkpoint_batch.length > 0) {
282
- await this.flushInner(
283
- options,
284
- async (stream, lastOp, writes) => {
285
- result = await checkpoint(stream, lastOp, writes);
286
- },
287
- projection
288
- );
289
- }
290
- return result;
291
- }
292
-
293
- protected abstract flushInner(
294
- options?: storage.BatchBucketFlushOptions,
295
- checkpoint?: (stream: SyncRuleDocumentBase, lastOp: InternalOpId, writes?: MongoWriteBatch) => Promise<void>,
296
- projection?: mongo.Document
297
- ): Promise<storage.FlushedResult | null>;
261
+ protected abstract flushInternal(options?: storage.BatchBucketFlushOptions): Promise<storage.FlushedResult | null>;
298
262
 
299
263
  /**
300
264
  * Evaluate one source operation and append its storage writes to batch.
@@ -578,16 +542,15 @@ export abstract class MongoBucketBatch
578
542
  );
579
543
  }
580
544
 
581
- protected async withTransaction<T>(
582
- cb: (stream: SyncRuleDocumentBase) => Promise<T>,
583
- session = this.session
584
- ): Promise<T> {
585
- return this.withFencedTransaction(() => this.fence(session), cb, session);
586
- }
545
+ protected abstract withTransaction<T>(
546
+ callback: (stream: SyncRuleDocumentBase) => Promise<T>,
547
+ session?: mongo.ClientSession
548
+ ): Promise<T>;
587
549
 
588
550
  /**
589
- * Internal transaction helper: the public writer operation already holds the
590
- * mutex. The first operation must modify the stream document conditional on
551
+ * Internal transaction helper: the caller serializes use of its session, via
552
+ * the writer mutex or the v3/v4 publication FIFO. The first operation must
553
+ * modify the stream document conditional on
591
554
  * lease ownership. This database fence is required on every retry even though
592
555
  * local writers are serialized; another process may have taken over the lease.
593
556
  */
@@ -595,18 +558,19 @@ export abstract class MongoBucketBatch
595
558
  acquireFence: () => Promise<S>,
596
559
  cb: (stream: S) => Promise<T>,
597
560
  session = this.session,
598
- description?: string
561
+ description?: string,
562
+ tracer = this.tracer
599
563
  ): Promise<T> {
600
564
  this.options.replicationLock.throwIfAborted();
601
565
  let attempts = 0;
602
566
  // Includes driver commit retries and the delays between transaction attempts.
603
- using _transactionSpan = this.tracer.span('storage', 'transaction');
567
+ using _transactionSpan = tracer.span('storage', 'transaction');
604
568
  const result = await session.withTransaction(
605
569
  async () => {
606
570
  attempts++;
607
571
  // One callback invocation per transaction attempt. Commit happens after
608
572
  // this span; command monitoring is needed to measure the full wire lifetime.
609
- using attemptSpan = this.tracer.span('storage', 'transaction_body');
573
+ using attemptSpan = tracer.span('storage', 'transaction_body');
610
574
  try {
611
575
  const stream = await acquireFence();
612
576
  const result = await cb(stream);
@@ -632,7 +596,7 @@ export abstract class MongoBucketBatch
632
596
  this.logger.warn('Transaction error', e as Error);
633
597
  }
634
598
  const delay = Math.random() * 50;
635
- using _ = this.tracer.span('storage', 'retry_delay');
599
+ using _ = tracer.span('storage', 'retry_delay');
636
600
  await timers.setTimeout(delay);
637
601
  throw e;
638
602
  }
@@ -648,16 +612,10 @@ export abstract class MongoBucketBatch
648
612
  * database operation or reacquire this mutex. All session use, including reads,
649
613
  * belongs inside this boundary so it cannot join another writer's transaction.
650
614
  * Transaction helpers still fence database ownership on every attempt.
615
+ * V3/v4 also flush all writers before metadata operations; flush/commit pass
616
+ * false so their callbacks handle their own input without flushing other writers.
651
617
  */
652
- private async withWriterLock<T>(callback: () => Promise<T>): Promise<T> {
653
- using lockSpan = this.tracer.span('storage', 'internal_lock');
654
- this.options.replicationLock.throwIfAborted();
655
- return this.options.replicationLock.writerMutex.exclusiveLock(async () => {
656
- lockSpan.end();
657
- this.options.replicationLock.throwIfAborted();
658
- return callback();
659
- });
660
- }
618
+ protected abstract withWriterLock<T>(callback: () => Promise<T>, flushAllWriters?: boolean): Promise<T>;
661
619
 
662
620
  /** Internal single-document update; the public operation already holds the mutex. */
663
621
  protected async updateStreamMetadata(
@@ -694,28 +652,22 @@ export abstract class MongoBucketBatch
694
652
  /** Advance the persisted head in the same transaction as the operations. */
695
653
  protected abstract onReplicationTransactionFlush(writes: MongoWriteBatch, lastOp: InternalOpId): void;
696
654
 
697
- async [Symbol.asyncDispose]() {
698
- if (this.batch?.hasData() || this.write_checkpoint_batch.length > 0) {
699
- // We don't error here, since:
700
- // 1. In error states, this is expected (we can't distinguish between disposing after success or error).
701
- // 2. SuppressedError is messy to deal with.
702
- this.logger.warn('Disposing writer with unflushed changes');
703
- }
704
- // The lease owns the shared session and ends it after all writers stop.
705
- super.clearListeners();
706
- }
655
+ abstract [Symbol.asyncDispose](): Promise<void>;
707
656
 
708
657
  async dispose() {
709
658
  await this[Symbol.asyncDispose]();
710
659
  }
711
660
 
712
- async save(record: storage.SaveOptions): Promise<storage.FlushedResult | null> {
661
+ abstract save(record: storage.SaveOptions): Promise<storage.FlushedResult | null>;
662
+
663
+ /** Buffer one complete input event synchronously, including its custom checkpoints. */
664
+ protected bufferRecord(record: storage.SaveOptions): boolean {
713
665
  const { after, before, sourceTable, tag } = record;
714
666
  const storeCurrentData = this.storeCurrentData && sourceTable.storeCurrentData;
715
667
  // V3 source tables own disjoint event-definition ids for each physical table. Multiple
716
668
  // SourceTables may evaluate different events, but each definition is evaluated through
717
669
  // at most one record for this row change.
718
- // Legacy storage leaves eventDefinitionIds undefined and selects by table ref.
670
+ // V1/v2 storage leaves eventDefinitionIds undefined and selects by table ref.
719
671
  if (sourceTable.syncEvent) {
720
672
  for (const { event, eventId } of this.getTableEvents(sourceTable)) {
721
673
  this.iterateListeners((cb) =>
@@ -734,27 +686,20 @@ export abstract class MongoBucketBatch
734
686
  }
735
687
  }
736
688
 
737
- /**
738
- * Return if the table is just an event table
739
- */
740
- if (!sourceTable.syncData && !sourceTable.syncParameters) {
741
- return null;
742
- }
743
-
744
- this.logger.debug(`Saving ${record.tag}:${record.before?.id}/${record.after?.id}`);
689
+ // Event-only tables can still buffer custom checkpoints. Only data/parameter
690
+ // rows need source-record lookup and evaluation, but both kinds of input can flush.
691
+ if (sourceTable.syncData || sourceTable.syncParameters) {
692
+ this.logger.debug(`Saving ${record.tag}:${record.before?.id}/${record.after?.id}`);
745
693
 
746
- this.batch ??= new OperationBatch();
747
- this.batch.push(new RecordOperation(record));
748
-
749
- if (this.batch.shouldFlush()) {
750
- const r = await this.flush();
751
- // HACK: Give other streams a chance to also flush
752
- await timers.setTimeout(5);
753
- return r;
694
+ this.batch ??= new OperationBatch(this.options.batchLimits);
695
+ this.batch.push(new RecordOperation(record));
754
696
  }
755
- return null;
697
+
698
+ return this.batch?.shouldFlush() ?? false;
756
699
  }
757
700
 
701
+ protected abstract automaticFlush(): Promise<storage.FlushedResult | null>;
702
+
758
703
  /**
759
704
  * Drop is equivalent to TRUNCATE, plus removing our record of the table.
760
705
  */
@@ -781,22 +726,7 @@ export abstract class MongoBucketBatch
781
726
  return this.withWriterLock(() => this.truncateInternal(sourceTables));
782
727
  }
783
728
 
784
- protected async truncateInternal(sourceTables: storage.SourceTable[]): Promise<storage.FlushedResult | null> {
785
- await this.flushInternal();
786
-
787
- let last_op: InternalOpId | null = null;
788
- for (let table of sourceTables) {
789
- last_op = await this.truncateSingleInternal(table);
790
- }
791
-
792
- if (last_op) {
793
- return {
794
- flushed_op: last_op
795
- };
796
- } else {
797
- return null;
798
- }
799
- }
729
+ protected abstract truncateInternal(sourceTables: storage.SourceTable[]): Promise<storage.FlushedResult | null>;
800
730
 
801
731
  async truncateSingle(sourceTable: storage.SourceTable): Promise<InternalOpId> {
802
732
  return this.withWriterLock(() => this.truncateSingleInternal(sourceTable));
@@ -845,27 +775,7 @@ export abstract class MongoBucketBatch
845
775
  /**
846
776
  * Gets relevant {@link HydratedEventDescriptor}s for the given {@link SourceTable}
847
777
  */
848
- protected getTableEvents(
778
+ protected abstract getTableEvents(
849
779
  table: storage.SourceTable
850
- ): { event: HydratedEventDescriptor; eventId?: EventDefinitionId }[] {
851
- // V3 storage assigns event-definition ids to each source table, so membership is authoritative.
852
- // Iterate the table's distinct ids and resolve each through the stream's deduped event map, so a
853
- // definition reused across configs has one evaluator for that id. The evaluator may still return
854
- // multiple payloads from matching queries. Legacy storage leaves this undefined and selects by table ref.
855
- if (table.eventDefinitionIds != null) {
856
- const eventById = this.options.parsedSyncConfig.eventById;
857
- const events: { event: HydratedEventDescriptor; eventId: EventDefinitionId }[] = [];
858
- for (const id of table.eventDefinitionIds) {
859
- const event = eventById.get(id);
860
- if (event != null && event.tableTriggersEvent(table.ref)) {
861
- events.push({ event, eventId: id });
862
- }
863
- }
864
- return events;
865
- }
866
-
867
- return this.sync_rules.eventDescriptors
868
- .filter((event) => event.tableTriggersEvent(table.ref))
869
- .map((event) => ({ event }));
870
- }
780
+ ): { event: HydratedEventDescriptor; eventId?: EventDefinitionId }[];
871
781
  }
@@ -76,6 +76,7 @@ export class MongoStorageProvider implements storage.StorageProvider {
76
76
  });
77
77
  const syncStorageFactory = new MongoBucketStorage(database, {
78
78
  chunkCompactionConcurrency,
79
+ replicationBatchSize: decodedConfig.replication_batch_size,
79
80
  replicationStreamNamePrefix: resolvedConfig.slot_name_prefix,
80
81
  readPreference,
81
82
  statsReadPreference:
@@ -283,6 +283,7 @@ export abstract class MongoSyncBucketStorage
283
283
  replicationStreamName: this.replicationStreamName,
284
284
  replicationLock,
285
285
  opIdAllocator: this.factory.getOpIdAllocator(this.replicationStream, replicationLock),
286
+ batchLimits: this.factory.replicationBatchLimits,
286
287
  storeCurrentData: options.storeCurrentData,
287
288
  skipExistingRows: options.skipExistingRows ?? false,
288
289
  markRecordUnavailable: options.markRecordUnavailable,
@@ -405,11 +406,18 @@ export abstract class MongoSyncBucketStorage
405
406
  this.factory.discardOpIdAllocator(this.replicationStreamId);
406
407
  await this.clearSyncRuleState();
407
408
 
408
- await this.clearBucketData(signal);
409
- await this.clearParameterIndexes(signal);
410
- await this.clearSourceRecords(signal);
411
- await this.clearBucketState(signal);
412
- await this.clearSourceTables(signal);
409
+ // Only stopped-stream cleanup may remove shared collections. Clearing an
410
+ // active or processing stream for a snapshot must not change shared storage.
411
+ const droppedV1Collections =
412
+ this.replicationStream.state == storage.SyncRuleState.STOP &&
413
+ (await this.factory.dropUnusedV1StorageCollections(signal));
414
+ if (this.storageConfig.version >= storage.STORAGE_VERSION_3 || !droppedV1Collections) {
415
+ await this.clearBucketData(signal);
416
+ await this.clearParameterIndexes(signal);
417
+ await this.clearSourceRecords(signal);
418
+ await this.clearBucketState(signal);
419
+ await this.clearSourceTables(signal);
420
+ }
413
421
  await this.clearCustomCheckpointRequests(signal);
414
422
 
415
423
  this.#storageInitialized = false;
@@ -4,6 +4,7 @@ import { mongo } from '@powersync/lib-service-mongodb';
4
4
  import { ErrorCode, Logger, ReplicationAbortedError, ServiceError } from '@powersync/lib-services-framework';
5
5
  import { storage, utils } from '@powersync/service-core';
6
6
  import { VersionedPowerSyncMongo } from './db.js';
7
+ import type { ReplicationPipelineV3 } from './v3/ReplicationPipelineV3.js';
7
8
 
8
9
  const LOCK_DURATION_MS = 60 * 1000;
9
10
 
@@ -12,11 +13,17 @@ const LOCK_DURATION_MS = 60 * 1000;
12
13
  * processes that replication stream at a time.
13
14
  */
14
15
  export class MongoSyncRulesLock implements storage.ReplicationLock {
15
- /** Public writer operations hold this mutex through preparation, publication and cleanup. */
16
+ /**
17
+ * Serializes public operations and preparation reads. V1/v2 also hold it
18
+ * through publication; v3/v4 may publish on the lease pipeline's own session.
19
+ */
16
20
  readonly writerMutex = new utils.Mutex();
21
+ /** Initialized only for v3/v4; owned and joined by the lease. */
22
+ replicationPipeline?: ReplicationPipelineV3;
17
23
  /**
18
24
  * All writers use this causal session sequentially under writerMutex. Reusing
19
- * it carries earlier writes into later majority reads without copying clocks.
25
+ * it carries earlier writes into later majority reads. The v3/v4 pipeline
26
+ * also carries confirmed publication clocks from its separate session.
20
27
  * Only lease teardown ends it; disposing one writer must not affect the rest.
21
28
  * Lease acquisition and renewal use independent operations and never wait here.
22
29
  */
@@ -113,7 +120,10 @@ export class MongoSyncRulesLock implements storage.ReplicationLock {
113
120
  } finally {
114
121
  // Let an active operation finish/abort before ending its session. Queued
115
122
  // writers check the aborted lease after acquiring the mutex and do no I/O.
116
- await this.writerMutex.exclusiveLock(() => this.session.endSession());
123
+ await this.writerMutex.exclusiveLock(async () => {
124
+ await this.replicationPipeline?.dispose();
125
+ await this.session.endSession();
126
+ });
117
127
  }
118
128
  }
119
129
 
@@ -3,16 +3,7 @@ import * as bson from 'bson';
3
3
 
4
4
  import { storage } from '@powersync/service-core';
5
5
  import { mongoTableId } from '../../utils/util.js';
6
-
7
- /**
8
- * Maximum number of operations in a batch.
9
- */
10
- const MAX_BATCH_COUNT = 2000;
11
-
12
- /**
13
- * Maximum size of operations in the batch (estimated).
14
- */
15
- const MAX_RECORD_BATCH_SIZE = 5_000_000;
6
+ import { DEFAULT_REPLICATION_BATCH_LIMITS, ReplicationBatchLimits } from './ReplicationBatchLimits.js';
16
7
 
17
8
  /**
18
9
  * Maximum size of size of current_data documents we lookup at a time.
@@ -20,15 +11,20 @@ const MAX_RECORD_BATCH_SIZE = 5_000_000;
20
11
  const MAX_CURRENT_DATA_BATCH_SIZE = 16_000_000;
21
12
 
22
13
  /**
23
- * Batch of input operations.
14
+ * Batch of input row operations and custom checkpoints.
24
15
  *
25
- * We accumulate operations up to MAX_RECORD_BATCH_SIZE,
26
- * then further split into sub-batches if MAX_CURRENT_DATA_BATCH_SIZE is exceeded.
16
+ * We accumulate operations up to the configured input count/byte targets,
17
+ * then further split rows into sub-batches if MAX_CURRENT_DATA_BATCH_SIZE is exceeded.
18
+ * Custom checkpoints bypass row evaluation and are persisted with the input's publication.
27
19
  */
28
20
  export class OperationBatch {
29
21
  batch: RecordOperation[] = [];
22
+ readonly customWriteCheckpoints: storage.CustomWriteCheckpointOptions[] = [];
30
23
  currentSize: number = 0;
31
24
 
25
+ constructor(private readonly limits: ReplicationBatchLimits = DEFAULT_REPLICATION_BATCH_LIMITS) {}
26
+
27
+ /** Row count only: custom checkpoints bypass source-record lookup and repair. */
32
28
  get length() {
33
29
  return this.batch.length;
34
30
  }
@@ -38,12 +34,21 @@ export class OperationBatch {
38
34
  this.currentSize += op.estimatedSize;
39
35
  }
40
36
 
37
+ addCustomWriteCheckpoint(checkpoint: storage.CustomWriteCheckpointOptions) {
38
+ this.customWriteCheckpoints.push(checkpoint);
39
+ this.currentSize += bson.calculateObjectSize(checkpoint);
40
+ }
41
+
41
42
  shouldFlush() {
42
- return this.batch.length >= MAX_BATCH_COUNT || this.currentSize > MAX_RECORD_BATCH_SIZE;
43
+ return (
44
+ this.batch.length >= this.limits.maxInputBatchCount ||
45
+ this.customWriteCheckpoints.length >= this.limits.maxInputBatchCount ||
46
+ this.currentSize > this.limits.maxInputBatchBytes
47
+ );
43
48
  }
44
49
 
45
50
  hasData() {
46
- return this.length > 0;
51
+ return this.length > 0 || this.customWriteCheckpoints.length > 0;
47
52
  }
48
53
 
49
54
  /**
@@ -52,6 +57,9 @@ export class OperationBatch {
52
57
  *
53
58
  */
54
59
  *batched(sizes: Map<string, number> | undefined): Generator<RecordOperation[]> {
60
+ if (this.length === 0) {
61
+ return;
62
+ }
55
63
  if (sizes == null) {
56
64
  yield this.batch;
57
65
  return;