@powersync/service-module-mongodb-storage 0.25.0 → 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 (84) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/storage/MongoBucketStorage.d.ts +6 -0
  3. package/dist/storage/MongoBucketStorage.js +8 -29
  4. package/dist/storage/MongoBucketStorage.js.map +1 -1
  5. package/dist/storage/implementation/MongoBucketBatch.d.ts +21 -16
  6. package/dist/storage/implementation/MongoBucketBatch.js +22 -125
  7. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  8. package/dist/storage/implementation/MongoStorageProvider.js +1 -0
  9. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
  10. package/dist/storage/implementation/MongoSyncBucketStorage.js +1 -0
  11. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
  12. package/dist/storage/implementation/MongoSyncRulesLock.d.ts +9 -2
  13. package/dist/storage/implementation/MongoSyncRulesLock.js +12 -3
  14. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
  15. package/dist/storage/implementation/OperationBatch.d.ts +10 -3
  16. package/dist/storage/implementation/OperationBatch.js +22 -13
  17. package/dist/storage/implementation/OperationBatch.js.map +1 -1
  18. package/dist/storage/implementation/ReplicationBatchLimits.d.ts +24 -0
  19. package/dist/storage/implementation/ReplicationBatchLimits.js +25 -0
  20. package/dist/storage/implementation/ReplicationBatchLimits.js.map +1 -0
  21. package/dist/storage/implementation/common/BatchOperationBuffer.d.ts +17 -1
  22. package/dist/storage/implementation/common/BatchOperationBuffer.js +22 -24
  23. package/dist/storage/implementation/common/BatchOperationBuffer.js.map +1 -1
  24. package/dist/storage/implementation/common/PersistedBatch.d.ts +2 -0
  25. package/dist/storage/implementation/common/PreparedPublication.d.ts +13 -9
  26. package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +18 -1
  27. package/dist/storage/implementation/v1/MongoBucketBatchV1.js +99 -14
  28. package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
  29. package/dist/storage/implementation/v1/PersistedBatchV1.js +1 -1
  30. package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
  31. package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +39 -3
  32. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +356 -90
  33. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  34. package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -5
  35. package/dist/storage/implementation/v3/PersistedBatchV3.js +26 -13
  36. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  37. package/dist/storage/implementation/v3/ReplicationPipelineV3.d.ts +84 -0
  38. package/dist/storage/implementation/v3/ReplicationPipelineV3.js +187 -0
  39. package/dist/storage/implementation/v3/ReplicationPipelineV3.js.map +1 -0
  40. package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +4 -4
  41. package/dist/storage/implementation/v3/SourceRecordStoreV3.js +4 -4
  42. package/dist/storage/implementation/v3/chunking.js +7 -3
  43. package/dist/storage/implementation/v3/chunking.js.map +1 -1
  44. package/dist/types/types.d.ts +5 -0
  45. package/dist/types/types.js +4 -0
  46. package/dist/types/types.js.map +1 -1
  47. package/dist/utils/collection-sizes.d.ts +9 -0
  48. package/dist/utils/collection-sizes.js +95 -0
  49. package/dist/utils/collection-sizes.js.map +1 -0
  50. package/dist/utils/test-utils.js +1 -0
  51. package/dist/utils/test-utils.js.map +1 -1
  52. package/package.json +7 -7
  53. package/src/storage/MongoBucketStorage.ts +19 -30
  54. package/src/storage/implementation/MongoBucketBatch.ts +47 -137
  55. package/src/storage/implementation/MongoStorageProvider.ts +1 -0
  56. package/src/storage/implementation/MongoSyncBucketStorage.ts +1 -0
  57. package/src/storage/implementation/MongoSyncRulesLock.ts +13 -3
  58. package/src/storage/implementation/OperationBatch.ts +23 -15
  59. package/src/storage/implementation/ReplicationBatchLimits.ts +45 -0
  60. package/src/storage/implementation/common/BatchOperationBuffer.ts +21 -26
  61. package/src/storage/implementation/common/PersistedBatch.ts +2 -0
  62. package/src/storage/implementation/common/PreparedPublication.ts +13 -9
  63. package/src/storage/implementation/v1/MongoBucketBatchV1.ts +135 -17
  64. package/src/storage/implementation/v1/PersistedBatchV1.ts +2 -1
  65. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +433 -101
  66. package/src/storage/implementation/v3/PersistedBatchV3.ts +26 -13
  67. package/src/storage/implementation/v3/ReplicationPipelineV3.ts +220 -0
  68. package/src/storage/implementation/v3/SourceRecordStoreV3.ts +4 -4
  69. package/src/storage/implementation/v3/chunking.ts +8 -3
  70. package/src/types/types.ts +7 -0
  71. package/src/utils/collection-sizes.ts +114 -0
  72. package/src/utils/test-utils.ts +1 -0
  73. package/test/src/concurrent_writers.test.ts +9 -15
  74. package/test/src/operation_batch.test.ts +207 -0
  75. package/test/src/prepared_publication.test.ts +187 -6
  76. package/test/src/replication_batch_config.test.ts +117 -0
  77. package/test/src/replication_pipeline.test.ts +738 -0
  78. package/test/src/replication_pipeline_benchmark.test.ts +133 -0
  79. package/test/src/replication_preparation.test.ts +4 -2
  80. package/test/src/replication_uploads.test.ts +28 -3
  81. package/test/src/storage.test.ts +24 -5
  82. package/test/src/storage_compacting.test.ts +16 -0
  83. package/test/src/storage_metrics.test.ts +88 -0
  84. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,187 @@
1
+ import { ReplicationAbortedError, ReplicationAssertionError } from '@powersync/lib-services-framework';
2
+ import { PerformanceTracer } from '@powersync/service-core';
3
+ import { MAX_PIPELINE_BATCHES } from '../ReplicationBatchLimits.js';
4
+ /**
5
+ * Two stages, with at most two in-flight batches per lease:
6
+ * 1. Preparation reads stored source records, evaluates changes and seals writes
7
+ * on lock.session under writerMutex. After admission, background preparation
8
+ * packs bucket operations and uploads offloaded chunks to object storage (e.g. S3).
9
+ * 2. Publishing commits the prepared MongoDB writes and object references, in FIFO
10
+ * order on a separate session. The successor can read/evaluate, pack and upload
11
+ * while its predecessor uploads or publishes. Both batches share the existing
12
+ * object-storage request limiter; there is no additional upload queue.
13
+ * Reads/evaluation and MongoDB publishing each remain serialized. Both slots can
14
+ * be uploading at once. No background task acquires writerMutex or uses lock.session.
15
+ *
16
+ * Each source writer separately buffers one bounded input block. Only full
17
+ * blocks (or explicit boundaries) enter preparation: alternating snapshot and
18
+ * streaming saves must not turn those blocks into single-row publications.
19
+ */
20
+ export class ReplicationPipelineV3 {
21
+ lock;
22
+ allocator;
23
+ limits;
24
+ publicationSession;
25
+ tracer = new PerformanceTracer('MongoDB publication');
26
+ /**
27
+ * Live writers can buffer raw rows/checkpoints that are not yet in `pending`.
28
+ * Metadata barriers must include all of those buffers before changing table state.
29
+ * Writers register at construction and unregister on disposal, not on each save.
30
+ */
31
+ writers = new Set();
32
+ pending = [];
33
+ reading;
34
+ /**
35
+ * MongoDB operationTime from the last successful queued publication. The
36
+ * publisher records it here so preparation can copy its causal history from
37
+ * publicationSession into lock.session before reading stored source records.
38
+ */
39
+ publishedTime;
40
+ constructor(lock, allocator, limits) {
41
+ this.lock = lock;
42
+ this.allocator = allocator;
43
+ this.limits = limits;
44
+ this.publicationSession = lock.db.client.startSession({ causalConsistency: true });
45
+ }
46
+ registerWriter(writer) {
47
+ this.writers.add(writer);
48
+ }
49
+ unregisterWriter(writer) {
50
+ this.writers.delete(writer);
51
+ }
52
+ /**
53
+ * Synchronously capture and queue every writer's current input. The caller
54
+ * then queues its metadata operation on writerMutex and drains publication
55
+ * there. Do not await between writers: rows appended after this boundary must
56
+ * stay behind the metadata change, even while earlier inputs are being prepared.
57
+ */
58
+ enqueueBufferedInputs() {
59
+ for (const writer of this.writers) {
60
+ void writer.flushBufferedInputToPipeline().catch((error) => this.fail(error));
61
+ }
62
+ }
63
+ get pendingCount() {
64
+ return this.pending.length;
65
+ }
66
+ get accountedBytes() {
67
+ return (this.pending.reduce((sum, batch) => sum + batch.bytes, 0) +
68
+ (this.reading != null && !this.pending.includes(this.reading) ? this.reading.bytes : 0));
69
+ }
70
+ /** Caller holds writerMutex. Reserve the preparation slot before reading another block. */
71
+ async capacity(bytes = 0) {
72
+ this.lock.throwIfAborted();
73
+ while (this.pending.length >= MAX_PIPELINE_BATCHES ||
74
+ (this.pending.length > 0 && this.accountedBytes + bytes > this.limits.maxPipelineBytes)) {
75
+ const signal = this.lock.signal;
76
+ const aborted = Promise.withResolvers();
77
+ const onAbort = () => aborted.reject(signal.reason);
78
+ signal.addEventListener('abort', onAbort, { once: true });
79
+ try {
80
+ signal.throwIfAborted();
81
+ await Promise.race([this.pending[0].done, aborted.promise]);
82
+ }
83
+ finally {
84
+ signal.removeEventListener('abort', onAbort);
85
+ }
86
+ this.lock.throwIfAborted();
87
+ }
88
+ }
89
+ get overlayEntryCount() {
90
+ const batches = new Set(this.pending);
91
+ if (this.reading != null) {
92
+ batches.add(this.reading);
93
+ }
94
+ return [...batches].reduce((sum, batch) => sum + batch.records.size, 0);
95
+ }
96
+ /**
97
+ * Caller holds writerMutex. Advance the preparation session's MongoDB logical
98
+ * time so subsequent majority reads include completed publications from the
99
+ * separate publication session. Later batches can read that persisted state
100
+ * without retaining every earlier batch's delta. A predecessor whose publication
101
+ * overlaps the current preparation still needs the pinned overlay from beginRead().
102
+ *
103
+ * Only preparation code advances the read session. The background publisher
104
+ * records publishedTime instead of mutating lock.session during an active read
105
+ * or transaction. Advancing the clock neither waits for nor flushes queued work.
106
+ */
107
+ advanceReadTime() {
108
+ if (this.publishedTime != null) {
109
+ this.lock.session.advanceOperationTime(this.publishedTime);
110
+ }
111
+ }
112
+ /**
113
+ * Capacity guarantees at most one predecessor. Keep its immutable delta alive
114
+ * until preparation finishes, even when a read straddles its commit. Earlier
115
+ * batches are already durable and covered by the read session's causal clock.
116
+ */
117
+ beginRead() {
118
+ this.lock.throwIfAborted();
119
+ if (this.pending.length > 1) {
120
+ throw new ReplicationAssertionError('Preparation requires an available pipeline slot');
121
+ }
122
+ this.advanceReadTime();
123
+ this.reading = this.pending.at(-1);
124
+ return this.reading?.records ?? new Map();
125
+ }
126
+ endRead() {
127
+ this.reading = undefined;
128
+ }
129
+ /** Own the sealed batch before starting uploads; only MongoDB publication waits for its turn. */
130
+ enqueue(records, bytes, preparePayloads, publish) {
131
+ const previous = this.pending.at(-1)?.done;
132
+ const preparationTime = this.lock.session.operationTime;
133
+ const batch = { records, bytes, done: Promise.resolve() };
134
+ this.pending.push(batch);
135
+ // Start payload work as soon as this batch is accounted for. Observe failure
136
+ // immediately, even while the predecessor is blocked in MongoDB. Keep this
137
+ // promise fulfilled: the lease carries the error, and FIFO teardown must join
138
+ // both the predecessor and all started uploads before removing this batch.
139
+ const payloads = Promise.resolve()
140
+ .then(() => {
141
+ this.lock.throwIfAborted();
142
+ return preparePayloads();
143
+ })
144
+ .catch((error) => this.fail(error));
145
+ const task = (async () => {
146
+ try {
147
+ await previous;
148
+ await payloads;
149
+ this.lock.throwIfAborted();
150
+ if (preparationTime != null) {
151
+ this.publicationSession.advanceOperationTime(preparationTime);
152
+ }
153
+ await publish(this.publicationSession);
154
+ // Hand off the confirmed publication time before removing the batch from pending.
155
+ this.publishedTime = this.publicationSession.operationTime;
156
+ }
157
+ catch (error) {
158
+ this.fail(error);
159
+ throw error;
160
+ }
161
+ finally {
162
+ this.pending.shift();
163
+ }
164
+ })();
165
+ // Failure aborts the lease before the successor can publish. Keep teardown and
166
+ // capacity waits rejection-free; public operations surface the lease error.
167
+ batch.done = task.catch(() => { });
168
+ return task;
169
+ }
170
+ fail(error) {
171
+ this.lock.invalidate(new ReplicationAbortedError('Replication pipeline failed; restart from persisted progress', error));
172
+ }
173
+ async join() {
174
+ await this.pending.at(-1)?.done;
175
+ }
176
+ async drain() {
177
+ await this.join();
178
+ this.lock.throwIfAborted();
179
+ this.advanceReadTime();
180
+ }
181
+ async dispose() {
182
+ await this.join();
183
+ this.writers.clear();
184
+ await this.publicationSession.endSession();
185
+ }
186
+ }
187
+ //# sourceMappingURL=ReplicationPipelineV3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ReplicationPipelineV3.js","sourceRoot":"","sources":["../../../../src/storage/implementation/v3/ReplicationPipelineV3.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AACvG,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAI5D,OAAO,EAAE,oBAAoB,EAA0B,MAAM,8BAA8B,CAAC;AAS5F;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,qBAAqB;IAmBb;IACR;IACQ;IApBV,kBAAkB,CAAsB;IACxC,MAAM,GAAG,IAAI,iBAAiB,CAAyB,qBAAqB,CAAC,CAAC;IACvF;;;;OAIG;IACc,OAAO,GAAG,IAAI,GAAG,EAAsB,CAAC;IACxC,OAAO,GAAkB,EAAE,CAAC;IACrC,OAAO,CAAe;IAC9B;;;;OAIG;IACK,aAAa,CAAmB;IAExC,YACmB,IAAwB,EAChC,SAA6B,EACrB,MAA8B;QAF9B,SAAI,GAAJ,IAAI,CAAoB;QAChC,cAAS,GAAT,SAAS,CAAoB;QACrB,WAAM,GAAN,MAAM,CAAwB;QAE/C,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC;IACrF,CAAC;IAED,cAAc,CAAC,MAA0B;QACvC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC3B,CAAC;IAED,gBAAgB,CAAC,MAA0B;QACzC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;IAED;;;;;OAKG;IACH,qBAAqB;QACnB,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YAClC,KAAK,MAAM,CAAC,4BAA4B,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,E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BACvC,kFAAkF;gBAClF,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,kBAAkB,CAAC,aAAa,CAAC;YAC7D,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBACjB,MAAM,KAAK,CAAC;YACd,CAAC;oBAAS,CAAC;gBACT,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;YACvB,CAAC;QACH,CAAC,CAAC,EAAE,CAAC;QACL,+EAA+E;QAC/E,4EAA4E;QAC5E,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CAAC,KAAc;QACjB,IAAI,CAAC,IAAI,CAAC,UAAU,CAClB,IAAI,uBAAuB,CAAC,8DAA8D,EAAE,KAAK,CAAC,CACnG,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,IAAI;QACR,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC;IAClC,CAAC;IAED,KAAK,CAAC,KAAK;QACT,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC;QAClB,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;QAC3B,IAAI,CAAC,eAAe,EAAE,CAAC;IACzB,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC;QAClB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,MAAM,IAAI,CAAC,kBAAkB,CAAC,UAAU,EAAE,CAAC;IAC7C,CAAC;CACF"}
@@ -11,10 +11,10 @@ import { VersionedPowerSyncMongoV3 } from './VersionedPowerSyncMongoV3.js';
11
11
  * The loadSizes(), loadDocuments() and loadTruncateBatch() methods are preparation
12
12
  * reads: callers must hold the lease's writer mutex and use its shared causal
13
13
  * session outside any transaction. These reads always request primary/majority
14
- * consistency, so they observe earlier writes in that session. Keep the mutex
15
- * held through publication to prevent another local writer from changing the
16
- * source records between preparation and commit. Publication transactions write
17
- * the prepared result without calling these read methods again.
14
+ * consistency. The lease pipeline advances the session clock from confirmed
15
+ * publications before reads, and overlays pending source-record versions while
16
+ * publication proceeds on a separate session. Pin those versions through reads
17
+ * that overlap commit. Publication never repeats these reads on transaction retry.
18
18
  */
19
19
  export declare class SourceRecordStoreV3 implements SourceRecordStore {
20
20
  private readonly db;
@@ -9,10 +9,10 @@ import { serializeParameterLookup } from './models.js';
9
9
  * The loadSizes(), loadDocuments() and loadTruncateBatch() methods are preparation
10
10
  * reads: callers must hold the lease's writer mutex and use its shared causal
11
11
  * session outside any transaction. These reads always request primary/majority
12
- * consistency, so they observe earlier writes in that session. Keep the mutex
13
- * held through publication to prevent another local writer from changing the
14
- * source records between preparation and commit. Publication transactions write
15
- * the prepared result without calling these read methods again.
12
+ * consistency. The lease pipeline advances the session clock from confirmed
13
+ * publications before reads, and overlays pending source-record versions while
14
+ * publication proceeds on a separate session. Pin those versions through reads
15
+ * that overlap commit. Publication never repeats these reads on transaction retry.
16
16
  */
17
17
  export class SourceRecordStoreV3 {
18
18
  db;
@@ -1,4 +1,3 @@
1
- import { bson } from '@powersync/service-core';
2
1
  export const DEFAULT_MAX_DOC_SIZE_BYTES = 1024 * 1024; // 1MB
3
2
  /**
4
3
  * Split an array of bucket data operations into chunks where each chunk's
@@ -12,8 +11,13 @@ export function chunkBucketData(operations, maxDocSizeBytes = DEFAULT_MAX_DOC_SI
12
11
  let currentChunk = [];
13
12
  let currentSize = 0;
14
13
  for (const op of operations) {
15
- // Add 5 to account for array index up to 4 digits (9999) plus null byte.
16
- const opSize = bson.calculateObjectSize(op) + 5;
14
+ // Chunk boundaries only need an estimate, but should be close to actual values.
15
+ // This estimate is more CPU-efficient than calculating the actual BSON size.
16
+ const opSize = 192 +
17
+ Buffer.byteLength(op.data ?? '') +
18
+ 2 * Buffer.byteLength(op.subkey ?? '') +
19
+ Buffer.byteLength(op.table ?? '') +
20
+ Buffer.byteLength(op.row_id ?? '');
17
21
  if (currentSize + opSize > maxDocSizeBytes && currentChunk.length > 0) {
18
22
  chunks.push(currentChunk);
19
23
  currentChunk = [];
@@ -1 +1 @@
1
- {"version":3,"file":"chunking.js","sourceRoot":"","sources":["../../../../src/storage/implementation/v3/chunking.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAG/C,MAAM,CAAC,MAAM,0BAA0B,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC,MAAM;AAE7D;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,UAA2B,EAC3B,eAAe,GAAG,0BAA0B;IAE5C,MAAM,MAAM,GAAsB,EAAE,CAAC;IACrC,IAAI,YAAY,GAAoB,EAAE,CAAC;IACvC,IAAI,WAAW,GAAG,CAAC,CAAC;IAEpB,KAAK,MAAM,EAAE,IAAI,UAAU,EAAE,CAAC;QAC5B,yEAAyE;QACzE,MAAM,MAAM,GAAG,IAAI,CAAC,mBAAmB,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;QAEhD,IAAI,WAAW,GAAG,MAAM,GAAG,eAAe,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtE,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;YAC1B,YAAY,GAAG,EAAE,CAAC;YAClB,WAAW,GAAG,CAAC,CAAC;QAClB,CAAC;QAED,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACtB,WAAW,IAAI,MAAM,CAAC;IACxB,CAAC;IAED,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC5B,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC5B,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"chunking.js","sourceRoot":"","sources":["../../../../src/storage/implementation/v3/chunking.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,0BAA0B,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC,MAAM;AAE7D;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,UAA2B,EAC3B,eAAe,GAAG,0BAA0B;IAE5C,MAAM,MAAM,GAAsB,EAAE,CAAC;IACrC,IAAI,YAAY,GAAoB,EAAE,CAAC;IACvC,IAAI,WAAW,GAAG,CAAC,CAAC;IAEpB,KAAK,MAAM,EAAE,IAAI,UAAU,EAAE,CAAC;QAC5B,gFAAgF;QAChF,6EAA6E;QAC7E,MAAM,MAAM,GACV,GAAG;YACH,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC;YAChC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,MAAM,IAAI,EAAE,CAAC;YACtC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC;YACjC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;QAErC,IAAI,WAAW,GAAG,MAAM,GAAG,eAAe,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtE,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;YAC1B,YAAY,GAAG,EAAE,CAAC;YAClB,WAAW,GAAG,CAAC,CAAC;QAClB,CAAC;QAED,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACtB,WAAW,IAAI,MAAM,CAAC;IACxB,CAAC;IAED,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC5B,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC5B,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -14,6 +14,9 @@ export declare const S3DefaultsMode: t.Codec<"standard" | "in-region" | "cross-r
14
14
  export type S3DefaultsMode = t.Encoded<typeof S3DefaultsMode>;
15
15
  export declare const MongoStorageReadPreference: t.Codec<"primary" | "primaryPreferred" | "secondary" | "secondaryPreferred" | "nearest", "primary" | "primaryPreferred" | "secondary" | "secondaryPreferred" | "nearest">;
16
16
  export type MongoStorageReadPreference = t.Encoded<typeof MongoStorageReadPreference>;
17
+ /** Coordinated replication batch/transaction targets; default: medium. */
18
+ export declare const MongoReplicationBatchSize: t.Codec<"small" | "medium" | "large", "small" | "medium" | "large">;
19
+ export type MongoReplicationBatchSize = t.Encoded<typeof MongoReplicationBatchSize>;
17
20
  export declare const MongoStorageConfig: t.Intersection<t.Codec<{
18
21
  type: string;
19
22
  max_pool_size?: number | undefined;
@@ -63,6 +66,8 @@ export declare const MongoStorageConfig: t.Intersection<t.Codec<{
63
66
  clear_batch_throttle_rate: t.OptionalCodec<t.Codec<number, number, string, t.CodecProps>>;
64
67
  /** Maximum concurrent buckets across V3 chunk-compaction jobs. Range: 1–64. Default: 4 with object storage, otherwise 2. */
65
68
  chunk_compaction_concurrency: t.OptionalCodec<t.Codec<number, number, string, t.CodecProps>>;
69
+ /** Larger batches improve throughput at the cost of retained memory. Default: medium. */
70
+ replication_batch_size: t.OptionalCodec<t.Codec<"small" | "medium" | "large", "small" | "medium" | "large", string, t.CodecProps>>;
66
71
  object_storage: t.OptionalCodec<t.Codec<{
67
72
  type: "s3";
68
73
  bucket: string;
@@ -30,6 +30,8 @@ const S3ObjectStorageConfig = t.object({
30
30
  inline_threshold_bytes: t.number.optional()
31
31
  });
32
32
  export const MongoStorageReadPreference = service_types.enumLiteral('primary', 'primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest');
33
+ /** Coordinated replication batch/transaction targets; default: medium. */
34
+ export const MongoReplicationBatchSize = service_types.enumLiteral('small', 'medium', 'large');
33
35
  export const MongoStorageConfig = service_types.configFile.BaseStorageConfig.and(lib_mongo.BaseMongoConfig).and(t.object({
34
36
  /**
35
37
  * Read preference for bulk checksum and bucket data reads.
@@ -57,6 +59,8 @@ export const MongoStorageConfig = service_types.configFile.BaseStorageConfig.and
57
59
  clear_batch_throttle_rate: t.number.optional(),
58
60
  /** Maximum concurrent buckets across V3 chunk-compaction jobs. Range: 1–64. Default: 4 with object storage, otherwise 2. */
59
61
  chunk_compaction_concurrency: t.number.optional(),
62
+ /** Larger batches improve throughput at the cost of retained memory. Default: medium. */
63
+ replication_batch_size: MongoReplicationBatchSize.optional(),
60
64
  object_storage: S3ObjectStorageConfig.optional()
61
65
  }));
62
66
  export const DEFAULT_CLEAR_BATCH_THROTTLE_RATE = 0.2;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAC5E,OAAO,KAAK,aAAa,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,CAAC,MAAM,UAAU,CAAC;AAE9B;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,aAAa,CAAC,WAAW,CAAC,UAAU,EAAE,WAAW,EAAE,cAAc,EAAE,QAAQ,CAAC,CAAC;AAI3G,MAAM,qBAAqB,GAAG,CAAC,CAAC,MAAM,CAAC;IACrC,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;IACrB,MAAM,EAAE,CAAC,CAAC,MAAM;IAChB,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC3B,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC3B,QAAQ,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC7B,gBAAgB,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE;IACtC,aAAa,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClC,iBAAiB,EAAE,CAAC,CAA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
5
+ /**
6
+ * Creates a size reader with command support cached for the owning storage factory's lifetime.
7
+ */
8
+ export declare function createCollectionSizeReader(db: mongo.Db, readPreference?: mongo.ReadPreference): (collections: CollectionNames) => Promise<Map<string, number>>;
9
+ export {};
@@ -0,0 +1,95 @@
1
+ import { isMongoServerError } from '@powersync/lib-service-mongodb';
2
+ /**
3
+ * Creates a size reader with command support cached for the owning storage factory's lifetime.
4
+ */
5
+ export function createCollectionSizeReader(db, readPreference) {
6
+ let dataSizeSupported = true;
7
+ return async (collections) => {
8
+ if (dataSizeSupported) {
9
+ try {
10
+ return await getDataSizes(db, collections, readPreference);
11
+ }
12
+ catch (error) {
13
+ if (isDataSizeUnsupported(error)) {
14
+ // Remember unsupported commands for this factory's lifetime, including subsequent scrapes.
15
+ dataSizeSupported = false;
16
+ }
17
+ else {
18
+ throw error;
19
+ }
20
+ }
21
+ }
22
+ return getCollStatsSizes(db, collections, readPreference);
23
+ };
24
+ }
25
+ function isDataSizeUnsupported(error) {
26
+ // Observed on M0 cluster:
27
+ // errmsg: 'CMD_NOT_ALLOWED: dataSize',
28
+ // code: 8000,
29
+ // codeName: 'AtlasError'
30
+ // We support other permutations in case it other error codes are used in other scenarios.
31
+ return (isMongoServerError(error) &&
32
+ (error.code === 59 || // CommandNotFound
33
+ error.code === 115 || // CommandNotSupported
34
+ (error.code === 8000 && // AtlasError: the command is unavailable on this Atlas tier.
35
+ /dataSize/i.test(error.message) &&
36
+ /not allowed|not supported|unsupported|CMD_NOT_ALLOWED/i.test(error.message))));
37
+ }
38
+ /**
39
+ * Get collection sizes via the `dataSize` command. This does not require opening storage statistics cursors,
40
+ * resulting in less work and lower memory usage on the server.
41
+ *
42
+ * Two disadvantages:
43
+ * 1. No batch support - each collection is queried sequentially, which can be slower for large numbers of collections.
44
+ * 2. The `dataSize` command is not supported on all MongoDB deployments, so we fall back to `collStats` if it fails.
45
+ *
46
+ * We avoid concurrent queries to avoid filling connection pools, which can cause delays in other queriers, and can
47
+ * also increase overhead on the server.
48
+ */
49
+ async function getDataSizes(db, collections, readPreference) {
50
+ const sizesByCollection = new Map();
51
+ // With estimate enabled and no bounds, dataSize reads the cached logical size without
52
+ // opening storage statistics cursors that keep idle collections' WiredTiger handles warm.
53
+ // Query sequentially so metrics collection does not fill the connection pool on standby pods.
54
+ for (const collection of collections) {
55
+ const stats = await db.command({ dataSize: `${db.databaseName}.${collection.name}`, estimate: true }, { readPreference });
56
+ sizesByCollection.set(collection.name, Number(stats.size));
57
+ }
58
+ return sizesByCollection;
59
+ }
60
+ /**
61
+ * Query collection sizes using $collStats, batched using $unionWith.
62
+ */
63
+ async function getCollStatsSizes(db, collections, readPreference) {
64
+ const sizesByCollection = new Map();
65
+ const statsPipeline = [
66
+ { $collStats: { storageStats: {} } },
67
+ { $project: { ns: 1, size: '$storageStats.size' } }
68
+ ];
69
+ // MongoDB has a limit of 1000 stages per aggregation pipeline. Additionally, we want
70
+ // to avoid too much work per aggregation, so we limit the number of collections per batch.
71
+ const COLLECTIONS_PER_BATCH = 100;
72
+ // Query batches sequentially so metrics collection does not fill the connection pool on standby pods.
73
+ // If a collection disappears during aggregation, let the next metrics collection retry.
74
+ for (let offset = 0; offset < collections.length; offset += COLLECTIONS_PER_BATCH) {
75
+ const batch = collections.slice(offset, offset + COLLECTIONS_PER_BATCH);
76
+ const pipeline = [
77
+ ...statsPipeline,
78
+ ...batch.slice(1).map((collection) => ({
79
+ $unionWith: { coll: collection.name, pipeline: statsPipeline }
80
+ }))
81
+ ];
82
+ const stats = await db
83
+ .collection(batch[0].name)
84
+ .aggregate(pipeline, {
85
+ readPreference
86
+ })
87
+ .toArray();
88
+ for (const stat of stats) {
89
+ const name = stat.ns.slice(db.databaseName.length + 1);
90
+ sizesByCollection.set(name, (sizesByCollection.get(name) ?? 0) + Number(stat.size));
91
+ }
92
+ }
93
+ return sizesByCollection;
94
+ }
95
+ //# sourceMappingURL=collection-sizes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collection-sizes.js","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,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;gBACrC,UAAU,EAAE,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,QAAQ,EAAE,aAAa,EAAE;aAC/D,CAAC,CAAC;SACJ,CAAC;QACF,MAAM,KAAK,GAAG,MAAM,EAAE;aACnB,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;aACzB,SAAS,CAAwC,QAAQ,EAAE;YAC1D,cAAc;SACf,CAAC;aACD,OAAO,EAAE,CAAC;QACb,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,MAAM,IAAI,GAAG,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACvD,iBAAiB,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACtF,CAAC;IACH,CAAC;IAED,OAAO,iBAAiB,CAAC;AAC3B,CAAC"}
@@ -17,6 +17,7 @@ export function mongoTestStorageFactoryGenerator(factoryOptions) {
17
17
  supportsMultipleSyncConfigs: factoryOptions.supportsMultipleSyncConfigs,
18
18
  objectStorage: factoryOptions.objectStorage,
19
19
  chunkCompactionConcurrency: factoryOptions.chunkCompactionConcurrency,
20
+ replicationBatchSize: factoryOptions.replicationBatchSize,
20
21
  inlineThresholdBytes: factoryOptions.inlineThresholdBytes
21
22
  });
22
23
  },
@@ -1 +1 @@
1
- {"version":3,"file":"test-utils.js","sourceRoot":"","sources":["../../src/utils/test-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,gCAAgC,CAAC;AAEvD,OAAO,EAAE,kBAAkB,EAA6B,MAAM,kCAAkC,CAAC;AACjG,OAAO,EAAE,kBAAkB,EAAE,MAA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I,cAAc,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@powersync/service-module-mongodb-storage",
3
3
  "repository": "https://github.com/powersync-ja/powersync-service",
4
- "version": "0.25.0",
4
+ "version": "0.26.0",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "publishConfig": {
@@ -20,15 +20,15 @@
20
20
  "lru-cache": "^10.2.2",
21
21
  "ts-codec": "^1.3.0",
22
22
  "uuid": "^14.0.0",
23
- "@powersync/lib-service-mongodb": "0.6.36",
24
- "@powersync/lib-services-framework": "0.10.5",
25
- "@powersync/service-core": "1.28.3",
26
- "@powersync/service-jsonbig": "0.17.14",
27
- "@powersync/service-sync-rules": "0.45.0",
23
+ "@powersync/lib-service-mongodb": "0.6.37",
24
+ "@powersync/lib-services-framework": "0.10.6",
25
+ "@powersync/service-core": "1.29.0",
26
+ "@powersync/service-jsonbig": "0.18.0",
27
+ "@powersync/service-sync-rules": "0.45.1",
28
28
  "@powersync/service-types": "0.21.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@powersync/service-core-tests": "0.18.5"
31
+ "@powersync/service-core-tests": "0.18.6"
32
32
  },
33
33
  "scripts": {
34
34
  "build": "tsc -b",
@@ -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
 
@@ -907,35 +924,7 @@ export class MongoBucketStorage extends storage.BucketStorageFactory {
907
924
  { nameOnly: true, readPreference: this.options.statsReadPreference }
908
925
  )
909
926
  .toArray();
910
- const sizesByCollection = new Map<string, number>();
911
- const statsPipeline: mongo.Document[] = [
912
- { $collStats: { storageStats: {} } },
913
- { $project: { ns: 1, size: '$storageStats.size' } }
914
- ];
915
- // MongoDB has a limit of 1000 stages per aggregation pipeline. Additionally, we want
916
- // to avoid too much work per aggregation, so we limit the number of collections per batch.
917
- const COLLECTIONS_PER_BATCH = 100;
918
- // Query batches sequentially so metrics collection does not fill the connection pool on standby pods.
919
- // If a collection disappears during aggregation, let the next metrics collection retry.
920
- for (let offset = 0; offset < collections.length; offset += COLLECTIONS_PER_BATCH) {
921
- const batch = collections.slice(offset, offset + COLLECTIONS_PER_BATCH);
922
- const pipeline = [
923
- ...statsPipeline,
924
- ...batch.slice(1).map((collection) => ({
925
- $unionWith: { coll: collection.name, pipeline: statsPipeline }
926
- }))
927
- ];
928
- const stats = await this.db.db
929
- .collection(batch[0].name)
930
- .aggregate<{ ns: string; size: number | bigint }>(pipeline, {
931
- readPreference: this.options.statsReadPreference
932
- })
933
- .toArray();
934
- for (const stat of stats) {
935
- const name = stat.ns.slice(this.db.db.databaseName.length + 1);
936
- sizesByCollection.set(name, (sizesByCollection.get(name) ?? 0) + Number(stat.size));
937
- }
938
- }
927
+ const sizesByCollection = await this.getCollectionSizes(collections);
939
928
 
940
929
  const v3StorageConfig = getMongoStorageConfig(storage.STORAGE_VERSION_3) as StorageConfig & {
941
930
  incrementalReprocessing: true;