@powersync/service-module-mongodb-storage 0.25.0 → 0.26.1
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 +27 -0
- package/dist/storage/MongoBucketStorage.d.ts +6 -0
- package/dist/storage/MongoBucketStorage.js +8 -29
- package/dist/storage/MongoBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoBucketBatch.d.ts +24 -18
- package/dist/storage/implementation/MongoBucketBatch.js +25 -127
- package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
- package/dist/storage/implementation/MongoStorageProvider.js +1 -0
- package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
- package/dist/storage/implementation/MongoSyncBucketStorage.js +1 -0
- package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoSyncRulesLock.d.ts +9 -2
- package/dist/storage/implementation/MongoSyncRulesLock.js +17 -4
- package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
- package/dist/storage/implementation/OperationBatch.d.ts +10 -3
- package/dist/storage/implementation/OperationBatch.js +22 -13
- package/dist/storage/implementation/OperationBatch.js.map +1 -1
- package/dist/storage/implementation/ReplicationBatchLimits.d.ts +24 -0
- package/dist/storage/implementation/ReplicationBatchLimits.js +25 -0
- package/dist/storage/implementation/ReplicationBatchLimits.js.map +1 -0
- package/dist/storage/implementation/common/BatchOperationBuffer.d.ts +17 -1
- package/dist/storage/implementation/common/BatchOperationBuffer.js +22 -24
- package/dist/storage/implementation/common/BatchOperationBuffer.js.map +1 -1
- package/dist/storage/implementation/common/PersistedBatch.d.ts +2 -0
- package/dist/storage/implementation/common/PreparedPublication.d.ts +17 -9
- package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +18 -1
- package/dist/storage/implementation/v1/MongoBucketBatchV1.js +99 -14
- package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
- package/dist/storage/implementation/v1/PersistedBatchV1.js +1 -1
- package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
- package/dist/storage/implementation/v3/CompactionLease.d.ts +17 -4
- package/dist/storage/implementation/v3/CompactionLease.js +76 -13
- package/dist/storage/implementation/v3/CompactionLease.js.map +1 -1
- package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +39 -3
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js +374 -95
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +5 -3
- package/dist/storage/implementation/v3/MongoCompactorV3.js +169 -82
- package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
- package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +15 -6
- package/dist/storage/implementation/v3/PersistedBatchV3.js +29 -16
- package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/ReplicationPipelineV3.d.ts +84 -0
- package/dist/storage/implementation/v3/ReplicationPipelineV3.js +187 -0
- package/dist/storage/implementation/v3/ReplicationPipelineV3.js.map +1 -0
- package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +4 -4
- package/dist/storage/implementation/v3/SourceRecordStoreV3.js +4 -4
- package/dist/storage/implementation/v3/chunking.js +7 -3
- package/dist/storage/implementation/v3/chunking.js.map +1 -1
- package/dist/types/types.d.ts +5 -0
- package/dist/types/types.js +4 -0
- package/dist/types/types.js.map +1 -1
- package/dist/utils/collection-sizes.d.ts +9 -0
- package/dist/utils/collection-sizes.js +95 -0
- package/dist/utils/collection-sizes.js.map +1 -0
- package/dist/utils/test-utils.js +1 -0
- package/dist/utils/test-utils.js.map +1 -1
- package/package.json +7 -7
- package/src/storage/MongoBucketStorage.ts +19 -30
- package/src/storage/implementation/MongoBucketBatch.ts +50 -139
- package/src/storage/implementation/MongoStorageProvider.ts +1 -0
- package/src/storage/implementation/MongoSyncBucketStorage.ts +1 -0
- package/src/storage/implementation/MongoSyncRulesLock.ts +18 -4
- package/src/storage/implementation/OperationBatch.ts +23 -15
- package/src/storage/implementation/ReplicationBatchLimits.ts +45 -0
- package/src/storage/implementation/common/BatchOperationBuffer.ts +21 -26
- package/src/storage/implementation/common/PersistedBatch.ts +2 -0
- package/src/storage/implementation/common/PreparedPublication.ts +17 -9
- package/src/storage/implementation/v1/MongoBucketBatchV1.ts +135 -17
- package/src/storage/implementation/v1/PersistedBatchV1.ts +2 -1
- package/src/storage/implementation/v3/CompactionLease.ts +91 -15
- package/src/storage/implementation/v3/MongoBucketBatchV3.ts +455 -107
- package/src/storage/implementation/v3/MongoCompactorV3.ts +217 -127
- package/src/storage/implementation/v3/PersistedBatchV3.ts +30 -17
- package/src/storage/implementation/v3/ReplicationPipelineV3.ts +220 -0
- package/src/storage/implementation/v3/SourceRecordStoreV3.ts +4 -4
- package/src/storage/implementation/v3/chunking.ts +8 -3
- package/src/types/types.ts +7 -0
- package/src/utils/collection-sizes.ts +114 -0
- package/src/utils/test-utils.ts +1 -0
- package/test/src/concurrent_writers.test.ts +22 -15
- package/test/src/helpers/PublicationCommandMonitor.ts +18 -3
- package/test/src/operation_batch.test.ts +207 -0
- package/test/src/prepared_publication.test.ts +210 -7
- package/test/src/replication_batch_config.test.ts +117 -0
- package/test/src/replication_pipeline.test.ts +738 -0
- package/test/src/replication_pipeline_benchmark.test.ts +133 -0
- package/test/src/replication_preparation.test.ts +4 -2
- package/test/src/replication_publication_baseline.test.ts +26 -16
- package/test/src/replication_publication_batching.test.ts +6 -2
- package/test/src/replication_uploads.test.ts +28 -3
- package/test/src/storage.test.ts +24 -5
- package/test/src/storage_compacting.test.ts +269 -47
- package/test/src/storage_metrics.test.ts +88 -0
- package/tsconfig.json +1 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
|
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
|
|
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,35 +542,36 @@ export abstract class MongoBucketBatch
|
|
|
578
542
|
);
|
|
579
543
|
}
|
|
580
544
|
|
|
581
|
-
protected
|
|
582
|
-
|
|
583
|
-
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
|
|
590
|
-
*
|
|
591
|
-
*
|
|
592
|
-
*
|
|
551
|
+
* Internal transaction helper: the caller serializes use of its session, via
|
|
552
|
+
* the writer mutex or the v3/v4 publication FIFO. Before invoking cb(),
|
|
553
|
+
* acquireFence() must modify the stream document conditional on lease
|
|
554
|
+
* ownership. Any writes before the fence must use the same transaction so
|
|
555
|
+
* they roll back if another process has taken over the lease. This database
|
|
556
|
+
* fence is required on every retry even though local writers are serialized.
|
|
593
557
|
*/
|
|
594
558
|
protected async withFencedTransaction<S, T>(
|
|
595
559
|
acquireFence: () => Promise<S>,
|
|
596
560
|
cb: (stream: S) => Promise<T>,
|
|
597
561
|
session = this.session,
|
|
598
|
-
description?: string
|
|
562
|
+
description?: string,
|
|
563
|
+
tracer = this.tracer
|
|
599
564
|
): Promise<T> {
|
|
600
565
|
this.options.replicationLock.throwIfAborted();
|
|
601
566
|
let attempts = 0;
|
|
602
567
|
// Includes driver commit retries and the delays between transaction attempts.
|
|
603
|
-
using _transactionSpan =
|
|
568
|
+
using _transactionSpan = tracer.span('storage', 'transaction');
|
|
604
569
|
const result = await session.withTransaction(
|
|
605
570
|
async () => {
|
|
606
571
|
attempts++;
|
|
607
572
|
// One callback invocation per transaction attempt. Commit happens after
|
|
608
573
|
// this span; command monitoring is needed to measure the full wire lifetime.
|
|
609
|
-
using attemptSpan =
|
|
574
|
+
using attemptSpan = tracer.span('storage', 'transaction_body');
|
|
610
575
|
try {
|
|
611
576
|
const stream = await acquireFence();
|
|
612
577
|
const result = await cb(stream);
|
|
@@ -632,7 +597,7 @@ export abstract class MongoBucketBatch
|
|
|
632
597
|
this.logger.warn('Transaction error', e as Error);
|
|
633
598
|
}
|
|
634
599
|
const delay = Math.random() * 50;
|
|
635
|
-
using _ =
|
|
600
|
+
using _ = tracer.span('storage', 'retry_delay');
|
|
636
601
|
await timers.setTimeout(delay);
|
|
637
602
|
throw e;
|
|
638
603
|
}
|
|
@@ -648,16 +613,10 @@ export abstract class MongoBucketBatch
|
|
|
648
613
|
* database operation or reacquire this mutex. All session use, including reads,
|
|
649
614
|
* belongs inside this boundary so it cannot join another writer's transaction.
|
|
650
615
|
* Transaction helpers still fence database ownership on every attempt.
|
|
616
|
+
* V3/v4 also flush all writers before metadata operations; flush/commit pass
|
|
617
|
+
* false so their callbacks handle their own input without flushing other writers.
|
|
651
618
|
*/
|
|
652
|
-
|
|
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
|
-
}
|
|
619
|
+
protected abstract withWriterLock<T>(callback: () => Promise<T>, flushAllWriters?: boolean): Promise<T>;
|
|
661
620
|
|
|
662
621
|
/** Internal single-document update; the public operation already holds the mutex. */
|
|
663
622
|
protected async updateStreamMetadata(
|
|
@@ -694,28 +653,22 @@ export abstract class MongoBucketBatch
|
|
|
694
653
|
/** Advance the persisted head in the same transaction as the operations. */
|
|
695
654
|
protected abstract onReplicationTransactionFlush(writes: MongoWriteBatch, lastOp: InternalOpId): void;
|
|
696
655
|
|
|
697
|
-
|
|
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
|
-
}
|
|
656
|
+
abstract [Symbol.asyncDispose](): Promise<void>;
|
|
707
657
|
|
|
708
658
|
async dispose() {
|
|
709
659
|
await this[Symbol.asyncDispose]();
|
|
710
660
|
}
|
|
711
661
|
|
|
712
|
-
|
|
662
|
+
abstract save(record: storage.SaveOptions): Promise<storage.FlushedResult | null>;
|
|
663
|
+
|
|
664
|
+
/** Buffer one complete input event synchronously, including its custom checkpoints. */
|
|
665
|
+
protected bufferRecord(record: storage.SaveOptions): boolean {
|
|
713
666
|
const { after, before, sourceTable, tag } = record;
|
|
714
667
|
const storeCurrentData = this.storeCurrentData && sourceTable.storeCurrentData;
|
|
715
668
|
// V3 source tables own disjoint event-definition ids for each physical table. Multiple
|
|
716
669
|
// SourceTables may evaluate different events, but each definition is evaluated through
|
|
717
670
|
// at most one record for this row change.
|
|
718
|
-
//
|
|
671
|
+
// V1/v2 storage leaves eventDefinitionIds undefined and selects by table ref.
|
|
719
672
|
if (sourceTable.syncEvent) {
|
|
720
673
|
for (const { event, eventId } of this.getTableEvents(sourceTable)) {
|
|
721
674
|
this.iterateListeners((cb) =>
|
|
@@ -734,27 +687,20 @@ export abstract class MongoBucketBatch
|
|
|
734
687
|
}
|
|
735
688
|
}
|
|
736
689
|
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
return null;
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
this.logger.debug(`Saving ${record.tag}:${record.before?.id}/${record.after?.id}`);
|
|
690
|
+
// Event-only tables can still buffer custom checkpoints. Only data/parameter
|
|
691
|
+
// rows need source-record lookup and evaluation, but both kinds of input can flush.
|
|
692
|
+
if (sourceTable.syncData || sourceTable.syncParameters) {
|
|
693
|
+
this.logger.debug(`Saving ${record.tag}:${record.before?.id}/${record.after?.id}`);
|
|
745
694
|
|
|
746
|
-
|
|
747
|
-
|
|
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;
|
|
695
|
+
this.batch ??= new OperationBatch(this.options.batchLimits);
|
|
696
|
+
this.batch.push(new RecordOperation(record));
|
|
754
697
|
}
|
|
755
|
-
|
|
698
|
+
|
|
699
|
+
return this.batch?.shouldFlush() ?? false;
|
|
756
700
|
}
|
|
757
701
|
|
|
702
|
+
protected abstract automaticFlush(): Promise<storage.FlushedResult | null>;
|
|
703
|
+
|
|
758
704
|
/**
|
|
759
705
|
* Drop is equivalent to TRUNCATE, plus removing our record of the table.
|
|
760
706
|
*/
|
|
@@ -781,22 +727,7 @@ export abstract class MongoBucketBatch
|
|
|
781
727
|
return this.withWriterLock(() => this.truncateInternal(sourceTables));
|
|
782
728
|
}
|
|
783
729
|
|
|
784
|
-
protected
|
|
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
|
-
}
|
|
730
|
+
protected abstract truncateInternal(sourceTables: storage.SourceTable[]): Promise<storage.FlushedResult | null>;
|
|
800
731
|
|
|
801
732
|
async truncateSingle(sourceTable: storage.SourceTable): Promise<InternalOpId> {
|
|
802
733
|
return this.withWriterLock(() => this.truncateSingleInternal(sourceTable));
|
|
@@ -845,27 +776,7 @@ export abstract class MongoBucketBatch
|
|
|
845
776
|
/**
|
|
846
777
|
* Gets relevant {@link HydratedEventDescriptor}s for the given {@link SourceTable}
|
|
847
778
|
*/
|
|
848
|
-
protected getTableEvents(
|
|
779
|
+
protected abstract getTableEvents(
|
|
849
780
|
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
|
-
}
|
|
781
|
+
): { event: HydratedEventDescriptor; eventId?: EventDefinitionId }[];
|
|
871
782
|
}
|
|
@@ -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,
|
|
@@ -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
|
-
/**
|
|
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
|
|
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
|
*/
|
|
@@ -88,6 +95,10 @@ export class MongoSyncRulesLock implements storage.ReplicationLock {
|
|
|
88
95
|
try {
|
|
89
96
|
await this.refresh();
|
|
90
97
|
} catch (e) {
|
|
98
|
+
// An in-flight refresh can finish after publication failed or teardown released the lock.
|
|
99
|
+
if (this.signal.aborted) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
91
102
|
this.invalidate(e);
|
|
92
103
|
this.logger.error('Failed to refresh lock', e);
|
|
93
104
|
}
|
|
@@ -108,12 +119,15 @@ export class MongoSyncRulesLock implements storage.ReplicationLock {
|
|
|
108
119
|
);
|
|
109
120
|
if (result.modifiedCount == 0) {
|
|
110
121
|
// Log and ignore
|
|
111
|
-
this.logger.warn(`
|
|
122
|
+
this.logger.warn(`Replication lock ${this.sync_rules_id}/${this.lock_id} was no longer owned during cleanup`);
|
|
112
123
|
}
|
|
113
124
|
} finally {
|
|
114
125
|
// Let an active operation finish/abort before ending its session. Queued
|
|
115
126
|
// writers check the aborted lease after acquiring the mutex and do no I/O.
|
|
116
|
-
await this.writerMutex.exclusiveLock(() =>
|
|
127
|
+
await this.writerMutex.exclusiveLock(async () => {
|
|
128
|
+
await this.replicationPipeline?.dispose();
|
|
129
|
+
await this.session.endSession();
|
|
130
|
+
});
|
|
117
131
|
}
|
|
118
132
|
}
|
|
119
133
|
|
|
@@ -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
|
|
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
|
|
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;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { MongoReplicationBatchSize } from '../../types/types.js';
|
|
2
|
+
|
|
3
|
+
/** Headroom for JS objects, memberships, packed chunks and upload buffers. */
|
|
4
|
+
export const RETAINED_BYTES_FACTOR = 4;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One predecessor plus its successor. Preparation's overlay assumes at most one
|
|
8
|
+
* predecessor, so increasing this requires more than changing a capacity limit.
|
|
9
|
+
*/
|
|
10
|
+
export const MAX_PIPELINE_BATCHES = 2;
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_REPLICATION_BATCH_SIZE: MongoReplicationBatchSize = 'medium';
|
|
13
|
+
|
|
14
|
+
/** Flush/backpressure targets, not hard memory ceilings or single-row limits. */
|
|
15
|
+
export interface ReplicationBatchLimits {
|
|
16
|
+
/** Row operations or custom checkpoints in a writer's input buffer. */
|
|
17
|
+
readonly maxInputBatchCount: number;
|
|
18
|
+
/** Estimated input bytes before row evaluation. */
|
|
19
|
+
readonly maxInputBatchBytes: number;
|
|
20
|
+
/** Per write category, preserving the existing transaction splitting rules. */
|
|
21
|
+
readonly maxTransactionBatchCount: number;
|
|
22
|
+
readonly maxTransactionBatchBytes: number;
|
|
23
|
+
/** Accounted work including packing headroom; excludes source/raw input buffers. */
|
|
24
|
+
readonly maxPipelineBytes: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function profile(count: number, inputBytes: number, transactionBytes: number): ReplicationBatchLimits {
|
|
28
|
+
return Object.freeze({
|
|
29
|
+
maxInputBatchCount: count,
|
|
30
|
+
maxInputBatchBytes: inputBytes,
|
|
31
|
+
maxTransactionBatchCount: count,
|
|
32
|
+
maxTransactionBatchBytes: transactionBytes,
|
|
33
|
+
maxPipelineBytes: MAX_PIPELINE_BATCHES * RETAINED_BYTES_FACTOR * transactionBytes
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Larger profiles trade higher retained memory for fewer flushes and round trips. */
|
|
38
|
+
export const REPLICATION_BATCH_LIMITS: Readonly<Record<MongoReplicationBatchSize, ReplicationBatchLimits>> =
|
|
39
|
+
Object.freeze({
|
|
40
|
+
small: profile(4_000, 2 * 1024 * 1024, 4 * 1024 * 1024),
|
|
41
|
+
medium: profile(8_000, 4 * 1024 * 1024, 8 * 1024 * 1024),
|
|
42
|
+
large: profile(16_000, 8 * 1024 * 1024, 16 * 1024 * 1024)
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_REPLICATION_BATCH_LIMITS = REPLICATION_BATCH_LIMITS[DEFAULT_REPLICATION_BATCH_SIZE];
|
|
@@ -4,33 +4,13 @@ import { JSONBig } from '@powersync/service-jsonbig';
|
|
|
4
4
|
import { BucketDataSource, BucketDefinitionId } from '@powersync/service-sync-rules';
|
|
5
5
|
import { mongoTableId, replicaIdToSubkey } from '../../../utils/util.js';
|
|
6
6
|
import { currentBucketKey, MAX_ROW_SIZE } from '../MongoBucketBatchShared.js';
|
|
7
|
+
import { DEFAULT_REPLICATION_BATCH_LIMITS, ReplicationBatchLimits } from '../ReplicationBatchLimits.js';
|
|
7
8
|
import { TaggedBucketParameterDocument } from '../models.js';
|
|
8
9
|
import { BucketDataDoc, BucketKey } from './BucketDataDoc.js';
|
|
9
10
|
import { BucketStateUpdate, SaveBucketDataOptions } from './PersistedBatch.js';
|
|
10
11
|
import { PublicationStats } from './PreparedPublication.js';
|
|
11
12
|
import { SourceRecordBucketState } from './SourceRecordStore.js';
|
|
12
13
|
|
|
13
|
-
/**
|
|
14
|
-
* Maximum size of operations we write in a single transaction.
|
|
15
|
-
*
|
|
16
|
-
* It's tricky to find the exact limit, but from experience, over 100MB
|
|
17
|
-
* can cause an error:
|
|
18
|
-
* > transaction is too large and will not fit in the storage engine cache
|
|
19
|
-
*
|
|
20
|
-
* Additionally, unbounded size here can balloon our memory usage in some edge
|
|
21
|
-
* cases.
|
|
22
|
-
*
|
|
23
|
-
* When we reach this threshold, we commit the transaction and start a new one.
|
|
24
|
-
*/
|
|
25
|
-
const MAX_TRANSACTION_BATCH_SIZE = 30_000_000;
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Limit number of documents to write in a single transaction.
|
|
29
|
-
*
|
|
30
|
-
* This has an effect on error message size in some cases.
|
|
31
|
-
*/
|
|
32
|
-
const MAX_TRANSACTION_DOC_COUNT = 2_000;
|
|
33
|
-
|
|
34
14
|
/**
|
|
35
15
|
* Shared operation generation, size accounting and diagnostics. Each storage
|
|
36
16
|
* version owns this buffer and decides when to write, retain or clear its data.
|
|
@@ -58,7 +38,8 @@ export class BatchOperationBuffer {
|
|
|
58
38
|
checkDefinitionId(id: BucketDefinitionId | null): BucketDefinitionId;
|
|
59
39
|
getBucketDefinitionId(source: BucketDataSource): BucketDefinitionId;
|
|
60
40
|
},
|
|
61
|
-
private readonly logger: Logger = defaultLogger
|
|
41
|
+
private readonly logger: Logger = defaultLogger,
|
|
42
|
+
private readonly limits: ReplicationBatchLimits = DEFAULT_REPLICATION_BATCH_LIMITS
|
|
62
43
|
) {
|
|
63
44
|
this.currentSize = writtenSize;
|
|
64
45
|
}
|
|
@@ -257,12 +238,26 @@ export class BatchOperationBuffer {
|
|
|
257
238
|
});
|
|
258
239
|
}
|
|
259
240
|
|
|
241
|
+
/**
|
|
242
|
+
* Maximum size of operations we write in a single transaction.
|
|
243
|
+
*
|
|
244
|
+
* It's tricky to find the exact limit, but from experience, over 100MB
|
|
245
|
+
* can cause an error:
|
|
246
|
+
* > transaction is too large and will not fit in the storage engine cache
|
|
247
|
+
*
|
|
248
|
+
* Additionally, unbounded size here can balloon our memory usage in some edge
|
|
249
|
+
* cases.
|
|
250
|
+
*
|
|
251
|
+
* When we reach this threshold, we commit the transaction and start a new one.
|
|
252
|
+
* We also limit the number of documents per write category; this has an effect
|
|
253
|
+
* on error message size in some cases.
|
|
254
|
+
*/
|
|
260
255
|
shouldFlushTransaction(currentDataCount: number) {
|
|
261
256
|
return (
|
|
262
|
-
this.currentSize >=
|
|
263
|
-
this.bucketDataCount >=
|
|
264
|
-
currentDataCount >=
|
|
265
|
-
this.bucketParameters.length >=
|
|
257
|
+
this.currentSize >= this.limits.maxTransactionBatchBytes ||
|
|
258
|
+
this.bucketDataCount >= this.limits.maxTransactionBatchCount ||
|
|
259
|
+
currentDataCount >= this.limits.maxTransactionBatchCount ||
|
|
260
|
+
this.bucketParameters.length >= this.limits.maxTransactionBatchCount
|
|
266
261
|
);
|
|
267
262
|
}
|
|
268
263
|
|
|
@@ -3,6 +3,7 @@ import { InternalOpId, storage } from '@powersync/service-core';
|
|
|
3
3
|
import { BucketDefinitionId, EvaluatedParameters, EvaluatedRow } from '@powersync/service-sync-rules';
|
|
4
4
|
import * as bson from 'bson';
|
|
5
5
|
import { MongoIdSequence } from '../MongoIdSequence.js';
|
|
6
|
+
import { ReplicationBatchLimits } from '../ReplicationBatchLimits.js';
|
|
6
7
|
import { SourceRecordBucketState, SourceRecordLookupState } from './SourceRecordStore.js';
|
|
7
8
|
|
|
8
9
|
export interface SaveBucketDataOptions {
|
|
@@ -30,6 +31,7 @@ export interface UpsertCurrentDataOptions {
|
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
export interface PersistedBatchOptions {
|
|
34
|
+
batchLimits?: ReplicationBatchLimits;
|
|
33
35
|
logger?: Logger;
|
|
34
36
|
}
|
|
35
37
|
|
|
@@ -10,8 +10,9 @@ export interface PublicationStats {
|
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
* Sealed
|
|
14
|
-
*
|
|
13
|
+
* Sealed writes from v3/v4 row preparation. Payload packing and uploads finish
|
|
14
|
+
* preparation once, including on failure; MongoDB transaction retries create
|
|
15
|
+
* fresh writes on every attempt without clearing the sealed batch.
|
|
15
16
|
*
|
|
16
17
|
* Scheduling metadata belongs to the caller: lease, selected config/mappings,
|
|
17
18
|
* input suffix, checkpoint intent and durable progress. Replay is valid only
|
|
@@ -20,7 +21,7 @@ export interface PublicationStats {
|
|
|
20
21
|
* fit a different context or overwrite its object paths. Publication also
|
|
21
22
|
* asserts that assigned IDs advance the freshly fenced persisted head.
|
|
22
23
|
*
|
|
23
|
-
* No
|
|
24
|
+
* No connector repair callbacks run here. The coordinator collects
|
|
24
25
|
* markRecordUnavailable records during evaluation and delivers them only after
|
|
25
26
|
* confirmed commit. Diagnostics run during evaluation.
|
|
26
27
|
* Before/after-flush hooks, source events and custom checkpoint consumption also
|
|
@@ -29,14 +30,21 @@ export interface PublicationStats {
|
|
|
29
30
|
*/
|
|
30
31
|
export interface PreparedPublication {
|
|
31
32
|
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
33
|
+
* Finish preparation by packing payloads and uploading offloaded chunks.
|
|
34
|
+
* This can overlap a predecessor's uploads or MongoDB publication.
|
|
35
|
+
* Preparation has already consumed assigned IDs. Sealing itself starts no I/O,
|
|
36
|
+
* so the coordinator can establish ownership before yielding.
|
|
37
|
+
* A packing/upload failure is terminal for this generation; all started uploads
|
|
38
|
+
* must settle before this promise rejects.
|
|
36
39
|
*/
|
|
37
|
-
|
|
40
|
+
packAndUploadPayloads(): Promise<void>;
|
|
38
41
|
/**
|
|
39
|
-
*
|
|
42
|
+
* Queue this group's bucket-state updates after packing. Execute them for all
|
|
43
|
+
* groups in preparation order before publishing any group's remaining writes.
|
|
44
|
+
*/
|
|
45
|
+
queueBucketStates(writes: MongoWriteBatch): void;
|
|
46
|
+
/**
|
|
47
|
+
* Publish the remaining MongoDB writes in the same transaction as bucket state.
|
|
40
48
|
* An optional batch supplies independent head/checkpoint writes to execute
|
|
41
49
|
* together with this group's data. This method owns execution of that batch;
|
|
42
50
|
* callers must not execute it again or include another group's dependent writes.
|