@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.
- package/CHANGELOG.md +30 -0
- package/dist/migrations/db/migrations/1684951997326-init.js +3 -29
- package/dist/migrations/db/migrations/1684951997326-init.js.map +1 -1
- package/dist/migrations/db/migrations/1741697235857-bucket-state-index.js +3 -24
- package/dist/migrations/db/migrations/1741697235857-bucket-state-index.js.map +1 -1
- package/dist/migrations/db/migrations/1760433882550-bucket-state-index2.js +3 -24
- package/dist/migrations/db/migrations/1760433882550-bucket-state-index2.js.map +1 -1
- package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.d.ts +3 -0
- package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.js +21 -0
- package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.js.map +1 -0
- package/dist/storage/MongoBucketStorage.d.ts +9 -0
- package/dist/storage/MongoBucketStorage.js +60 -30
- package/dist/storage/MongoBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoBucketBatch.d.ts +21 -16
- package/dist/storage/implementation/MongoBucketBatch.js +22 -125
- 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 +12 -5
- package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoSyncRulesLock.d.ts +9 -2
- package/dist/storage/implementation/MongoSyncRulesLock.js +12 -3
- 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 +13 -9
- package/dist/storage/implementation/db.d.ts +2 -0
- package/dist/storage/implementation/db.js +14 -0
- package/dist/storage/implementation/db.js.map +1 -1
- 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/v1/VersionedPowerSyncMongoV1.js +3 -1
- package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js.map +1 -1
- package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +39 -3
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js +356 -90
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -5
- package/dist/storage/implementation/v3/PersistedBatchV3.js +26 -13
- 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 -4
- package/dist/utils/test-utils.js.map +1 -1
- package/package.json +7 -7
- package/src/migrations/db/migrations/1684951997326-init.ts +3 -36
- package/src/migrations/db/migrations/1741697235857-bucket-state-index.ts +3 -31
- package/src/migrations/db/migrations/1760433882550-bucket-state-index2.ts +3 -31
- package/src/migrations/db/migrations/1794268800000-v1-storage-collections.ts +22 -0
- package/src/storage/MongoBucketStorage.ts +80 -31
- package/src/storage/implementation/MongoBucketBatch.ts +47 -137
- package/src/storage/implementation/MongoStorageProvider.ts +1 -0
- package/src/storage/implementation/MongoSyncBucketStorage.ts +13 -5
- package/src/storage/implementation/MongoSyncRulesLock.ts +13 -3
- 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 +13 -9
- package/src/storage/implementation/db.ts +15 -0
- package/src/storage/implementation/v1/MongoBucketBatchV1.ts +135 -17
- package/src/storage/implementation/v1/PersistedBatchV1.ts +2 -1
- package/src/storage/implementation/v1/VersionedPowerSyncMongoV1.ts +3 -1
- package/src/storage/implementation/v3/MongoBucketBatchV3.ts +433 -101
- package/src/storage/implementation/v3/PersistedBatchV3.ts +26 -13
- 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 -5
- package/test/src/concurrent_writers.test.ts +9 -15
- package/test/src/operation_batch.test.ts +207 -0
- package/test/src/prepared_publication.test.ts +187 -6
- 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_uploads.test.ts +28 -3
- package/test/src/storage.test.ts +24 -5
- package/test/src/storage_compacting.test.ts +16 -0
- package/test/src/storage_metrics.test.ts +88 -0
- package/test/src/v1_collections.test.ts +233 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
import { PreparedPublication } from '../common/PreparedPublication.js';
|
|
18
18
|
import { SourceRecordLookupState } from '../common/SourceRecordStore.js';
|
|
19
19
|
import { MongoWriteBatch } from '../MongoWriteBatch.js';
|
|
20
|
+
import { RETAINED_BYTES_FACTOR } from '../ReplicationBatchLimits.js';
|
|
20
21
|
import { serializeBucketData } from './bucket-format.js';
|
|
21
22
|
import { chunkBucketData } from './chunking.js';
|
|
22
23
|
import { DEFAULT_MIN_COMPACT_CHUNK_INTERVAL_MS } from './compaction-constants.js';
|
|
@@ -62,19 +63,19 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
|
|
|
62
63
|
private readonly inlineThresholdBytes: number;
|
|
63
64
|
private readonly signal?: AbortSignal;
|
|
64
65
|
private sealed = false;
|
|
65
|
-
private
|
|
66
|
+
private payloadsTask?: Promise<void>;
|
|
66
67
|
private payloadsReady = false;
|
|
67
68
|
|
|
68
69
|
constructor(
|
|
69
70
|
private readonly db: VersionedPowerSyncMongoV3,
|
|
70
71
|
private readonly group_id: number,
|
|
71
72
|
private readonly mapping: BucketDefinitionMapping,
|
|
72
|
-
|
|
73
|
+
private readonly initialWrittenSize: number,
|
|
73
74
|
options?: PersistedBatchV3Options
|
|
74
75
|
) {
|
|
75
76
|
this.operations = new BatchOperationBuffer(
|
|
76
77
|
group_id,
|
|
77
|
-
|
|
78
|
+
initialWrittenSize,
|
|
78
79
|
{
|
|
79
80
|
// V3-specific definition validation; v1 does not persist definition ids.
|
|
80
81
|
checkDefinitionId: (definitionId) => {
|
|
@@ -85,7 +86,8 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
|
|
|
85
86
|
},
|
|
86
87
|
getBucketDefinitionId: (source) => mapping.bucketSourceId(source)
|
|
87
88
|
},
|
|
88
|
-
options?.logger
|
|
89
|
+
options?.logger,
|
|
90
|
+
options?.batchLimits
|
|
89
91
|
);
|
|
90
92
|
this.inlineThresholdBytes = options?.inlineThresholdBytes ?? DEFAULT_INLINE_THRESHOLD_BYTES;
|
|
91
93
|
this.signal = options?.signal;
|
|
@@ -99,6 +101,17 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
|
|
|
99
101
|
return this.operations.currentSize;
|
|
100
102
|
}
|
|
101
103
|
|
|
104
|
+
/**
|
|
105
|
+
* Reuse the running size estimate with headroom for JS objects, membership
|
|
106
|
+
* maps, packed chunks and upload buffers, without traversing the batch again.
|
|
107
|
+
* Separate from transaction-size targets; this is not a measured heap size.
|
|
108
|
+
* This estimate intentionally charges superseded representations until commit.
|
|
109
|
+
* Exclude the carried transaction size: earlier groups account for themselves.
|
|
110
|
+
*/
|
|
111
|
+
get estimatedRetainedBytes(): number {
|
|
112
|
+
return (this.currentSize - this.initialWrittenSize) * RETAINED_BYTES_FACTOR;
|
|
113
|
+
}
|
|
114
|
+
|
|
102
115
|
saveBucketData(options: SaveBucketDataOptions): void {
|
|
103
116
|
this.assertMutable();
|
|
104
117
|
this.operations.saveBucketData(options);
|
|
@@ -133,13 +146,13 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
|
|
|
133
146
|
}
|
|
134
147
|
}
|
|
135
148
|
|
|
136
|
-
/** Cache readiness, including failure; the v3 batch owns the
|
|
137
|
-
|
|
149
|
+
/** Cache packing/upload readiness, including failure; the v3 batch owns the lifecycle. */
|
|
150
|
+
packAndUploadPayloads(): Promise<void> {
|
|
138
151
|
if (!this.sealed) {
|
|
139
|
-
throw new ReplicationAssertionError('Cannot
|
|
152
|
+
throw new ReplicationAssertionError('Cannot pack or upload an unsealed publication');
|
|
140
153
|
}
|
|
141
|
-
return (this.
|
|
142
|
-
.then(() => this.
|
|
154
|
+
return (this.payloadsTask ??= Promise.resolve()
|
|
155
|
+
.then(() => this.packAndUploadPayloadsImpl())
|
|
143
156
|
.then(() => {
|
|
144
157
|
this.payloadsReady = true;
|
|
145
158
|
}));
|
|
@@ -150,10 +163,10 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
|
|
|
150
163
|
options?: storage.BucketBatchCommitOptions,
|
|
151
164
|
additionalWrites?: MongoWriteBatch
|
|
152
165
|
) {
|
|
153
|
-
//
|
|
154
|
-
// awaits
|
|
166
|
+
// Preparation packs/uploads once, outside transaction retries. The
|
|
167
|
+
// coordinator awaits the entire bounded prefix before opening a transaction.
|
|
155
168
|
if (!this.payloadsReady) {
|
|
156
|
-
throw new ReplicationAssertionError('
|
|
169
|
+
throw new ReplicationAssertionError('Pack and upload payloads before starting the transaction');
|
|
157
170
|
}
|
|
158
171
|
return this.write(session, options, additionalWrites);
|
|
159
172
|
}
|
|
@@ -343,7 +356,7 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
|
|
|
343
356
|
private readonly preparedUsageDeltas = new Map<BucketDefinitionId, bigint>();
|
|
344
357
|
private preparedUploads: PreparedObjectStorageUpload[] = [];
|
|
345
358
|
|
|
346
|
-
private async
|
|
359
|
+
private async packAndUploadPayloadsImpl(): Promise<void> {
|
|
347
360
|
const operationsByDefinition = new Map<BucketDefinitionId, BucketDataDoc[]>();
|
|
348
361
|
for (const document of this.operations.bucketData) {
|
|
349
362
|
const existing = operationsByDefinition.get(document.bucketKey.definitionId) ?? [];
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { mongo } from '@powersync/lib-service-mongodb';
|
|
2
|
+
import { ReplicationAbortedError, ReplicationAssertionError } from '@powersync/lib-services-framework';
|
|
3
|
+
import { PerformanceTracer } from '@powersync/service-core';
|
|
4
|
+
import { LoadedSourceRecord } from '../common/SourceRecordStore.js';
|
|
5
|
+
import { MongoOpIdAllocator } from '../MongoOpIdAllocator.js';
|
|
6
|
+
import { MongoSyncRulesLock } from '../MongoSyncRulesLock.js';
|
|
7
|
+
import { MAX_PIPELINE_BATCHES, ReplicationBatchLimits } from '../ReplicationBatchLimits.js';
|
|
8
|
+
import type { MongoBucketBatchV3 } from './MongoBucketBatchV3.js';
|
|
9
|
+
|
|
10
|
+
interface Publication {
|
|
11
|
+
readonly records: ReadonlyMap<string, LoadedSourceRecord>;
|
|
12
|
+
readonly bytes: number;
|
|
13
|
+
done: Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Two stages, with at most two in-flight batches per lease:
|
|
18
|
+
* 1. Preparation reads stored source records, evaluates changes and seals writes
|
|
19
|
+
* on lock.session under writerMutex. After admission, background preparation
|
|
20
|
+
* packs bucket operations and uploads offloaded chunks to object storage (e.g. S3).
|
|
21
|
+
* 2. Publishing commits the prepared MongoDB writes and object references, in FIFO
|
|
22
|
+
* order on a separate session. The successor can read/evaluate, pack and upload
|
|
23
|
+
* while its predecessor uploads or publishes. Both batches share the existing
|
|
24
|
+
* object-storage request limiter; there is no additional upload queue.
|
|
25
|
+
* Reads/evaluation and MongoDB publishing each remain serialized. Both slots can
|
|
26
|
+
* be uploading at once. No background task acquires writerMutex or uses lock.session.
|
|
27
|
+
*
|
|
28
|
+
* Each source writer separately buffers one bounded input block. Only full
|
|
29
|
+
* blocks (or explicit boundaries) enter preparation: alternating snapshot and
|
|
30
|
+
* streaming saves must not turn those blocks into single-row publications.
|
|
31
|
+
*/
|
|
32
|
+
export class ReplicationPipelineV3 {
|
|
33
|
+
readonly publicationSession: mongo.ClientSession;
|
|
34
|
+
readonly tracer = new PerformanceTracer<'storage' | 'evaluate'>('MongoDB publication');
|
|
35
|
+
/**
|
|
36
|
+
* Live writers can buffer raw rows/checkpoints that are not yet in `pending`.
|
|
37
|
+
* Metadata barriers must include all of those buffers before changing table state.
|
|
38
|
+
* Writers register at construction and unregister on disposal, not on each save.
|
|
39
|
+
*/
|
|
40
|
+
private readonly writers = new Set<MongoBucketBatchV3>();
|
|
41
|
+
private readonly pending: Publication[] = [];
|
|
42
|
+
private reading?: Publication;
|
|
43
|
+
/**
|
|
44
|
+
* MongoDB operationTime from the last successful queued publication. The
|
|
45
|
+
* publisher records it here so preparation can copy its causal history from
|
|
46
|
+
* publicationSession into lock.session before reading stored source records.
|
|
47
|
+
*/
|
|
48
|
+
private publishedTime?: mongo.Timestamp;
|
|
49
|
+
|
|
50
|
+
constructor(
|
|
51
|
+
private readonly lock: MongoSyncRulesLock,
|
|
52
|
+
readonly allocator: MongoOpIdAllocator,
|
|
53
|
+
private readonly limits: ReplicationBatchLimits
|
|
54
|
+
) {
|
|
55
|
+
this.publicationSession = lock.db.client.startSession({ causalConsistency: true });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
registerWriter(writer: MongoBucketBatchV3): void {
|
|
59
|
+
this.writers.add(writer);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
unregisterWriter(writer: MongoBucketBatchV3): void {
|
|
63
|
+
this.writers.delete(writer);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Synchronously capture and queue every writer's current input. The caller
|
|
68
|
+
* then queues its metadata operation on writerMutex and drains publication
|
|
69
|
+
* there. Do not await between writers: rows appended after this boundary must
|
|
70
|
+
* stay behind the metadata change, even while earlier inputs are being prepared.
|
|
71
|
+
*/
|
|
72
|
+
enqueueBufferedInputs(): void {
|
|
73
|
+
for (const writer of this.writers) {
|
|
74
|
+
void writer.flushBufferedInputToPipeline().catch((error) => this.fail(error));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
get pendingCount() {
|
|
79
|
+
return this.pending.length;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
get accountedBytes() {
|
|
83
|
+
return (
|
|
84
|
+
this.pending.reduce((sum, batch) => sum + batch.bytes, 0) +
|
|
85
|
+
(this.reading != null && !this.pending.includes(this.reading) ? this.reading.bytes : 0)
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Caller holds writerMutex. Reserve the preparation slot before reading another block. */
|
|
90
|
+
async capacity(bytes = 0): Promise<void> {
|
|
91
|
+
this.lock.throwIfAborted();
|
|
92
|
+
while (
|
|
93
|
+
this.pending.length >= MAX_PIPELINE_BATCHES ||
|
|
94
|
+
(this.pending.length > 0 && this.accountedBytes + bytes > this.limits.maxPipelineBytes)
|
|
95
|
+
) {
|
|
96
|
+
const signal = this.lock.signal;
|
|
97
|
+
const aborted = Promise.withResolvers<void>();
|
|
98
|
+
const onAbort = () => aborted.reject(signal.reason);
|
|
99
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
100
|
+
try {
|
|
101
|
+
signal.throwIfAborted();
|
|
102
|
+
await Promise.race([this.pending[0].done, aborted.promise]);
|
|
103
|
+
} finally {
|
|
104
|
+
signal.removeEventListener('abort', onAbort);
|
|
105
|
+
}
|
|
106
|
+
this.lock.throwIfAborted();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
get overlayEntryCount() {
|
|
111
|
+
const batches = new Set(this.pending);
|
|
112
|
+
if (this.reading != null) {
|
|
113
|
+
batches.add(this.reading);
|
|
114
|
+
}
|
|
115
|
+
return [...batches].reduce((sum, batch) => sum + batch.records.size, 0);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Caller holds writerMutex. Advance the preparation session's MongoDB logical
|
|
120
|
+
* time so subsequent majority reads include completed publications from the
|
|
121
|
+
* separate publication session. Later batches can read that persisted state
|
|
122
|
+
* without retaining every earlier batch's delta. A predecessor whose publication
|
|
123
|
+
* overlaps the current preparation still needs the pinned overlay from beginRead().
|
|
124
|
+
*
|
|
125
|
+
* Only preparation code advances the read session. The background publisher
|
|
126
|
+
* records publishedTime instead of mutating lock.session during an active read
|
|
127
|
+
* or transaction. Advancing the clock neither waits for nor flushes queued work.
|
|
128
|
+
*/
|
|
129
|
+
advanceReadTime(): void {
|
|
130
|
+
if (this.publishedTime != null) {
|
|
131
|
+
this.lock.session.advanceOperationTime(this.publishedTime);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Capacity guarantees at most one predecessor. Keep its immutable delta alive
|
|
137
|
+
* until preparation finishes, even when a read straddles its commit. Earlier
|
|
138
|
+
* batches are already durable and covered by the read session's causal clock.
|
|
139
|
+
*/
|
|
140
|
+
beginRead(): ReadonlyMap<string, LoadedSourceRecord> {
|
|
141
|
+
this.lock.throwIfAborted();
|
|
142
|
+
if (this.pending.length > 1) {
|
|
143
|
+
throw new ReplicationAssertionError('Preparation requires an available pipeline slot');
|
|
144
|
+
}
|
|
145
|
+
this.advanceReadTime();
|
|
146
|
+
this.reading = this.pending.at(-1);
|
|
147
|
+
return this.reading?.records ?? new Map();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
endRead(): void {
|
|
151
|
+
this.reading = undefined;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Own the sealed batch before starting uploads; only MongoDB publication waits for its turn. */
|
|
155
|
+
enqueue(
|
|
156
|
+
records: ReadonlyMap<string, LoadedSourceRecord>,
|
|
157
|
+
bytes: number,
|
|
158
|
+
preparePayloads: () => Promise<void>,
|
|
159
|
+
publish: (session: mongo.ClientSession) => Promise<void>
|
|
160
|
+
): Promise<void> {
|
|
161
|
+
const previous = this.pending.at(-1)?.done;
|
|
162
|
+
const preparationTime = this.lock.session.operationTime;
|
|
163
|
+
const batch: Publication = { records, bytes, done: Promise.resolve() };
|
|
164
|
+
this.pending.push(batch);
|
|
165
|
+
// Start payload work as soon as this batch is accounted for. Observe failure
|
|
166
|
+
// immediately, even while the predecessor is blocked in MongoDB. Keep this
|
|
167
|
+
// promise fulfilled: the lease carries the error, and FIFO teardown must join
|
|
168
|
+
// both the predecessor and all started uploads before removing this batch.
|
|
169
|
+
const payloads = Promise.resolve()
|
|
170
|
+
.then(() => {
|
|
171
|
+
this.lock.throwIfAborted();
|
|
172
|
+
return preparePayloads();
|
|
173
|
+
})
|
|
174
|
+
.catch((error) => this.fail(error));
|
|
175
|
+
const task = (async () => {
|
|
176
|
+
try {
|
|
177
|
+
await previous;
|
|
178
|
+
await payloads;
|
|
179
|
+
this.lock.throwIfAborted();
|
|
180
|
+
if (preparationTime != null) {
|
|
181
|
+
this.publicationSession.advanceOperationTime(preparationTime);
|
|
182
|
+
}
|
|
183
|
+
await publish(this.publicationSession);
|
|
184
|
+
// Hand off the confirmed publication time before removing the batch from pending.
|
|
185
|
+
this.publishedTime = this.publicationSession.operationTime;
|
|
186
|
+
} catch (error) {
|
|
187
|
+
this.fail(error);
|
|
188
|
+
throw error;
|
|
189
|
+
} finally {
|
|
190
|
+
this.pending.shift();
|
|
191
|
+
}
|
|
192
|
+
})();
|
|
193
|
+
// Failure aborts the lease before the successor can publish. Keep teardown and
|
|
194
|
+
// capacity waits rejection-free; public operations surface the lease error.
|
|
195
|
+
batch.done = task.catch(() => {});
|
|
196
|
+
return task;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
fail(error: unknown): void {
|
|
200
|
+
this.lock.invalidate(
|
|
201
|
+
new ReplicationAbortedError('Replication pipeline failed; restart from persisted progress', error)
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async join(): Promise<void> {
|
|
206
|
+
await this.pending.at(-1)?.done;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async drain(): Promise<void> {
|
|
210
|
+
await this.join();
|
|
211
|
+
this.lock.throwIfAborted();
|
|
212
|
+
this.advanceReadTime();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async dispose(): Promise<void> {
|
|
216
|
+
await this.join();
|
|
217
|
+
this.writers.clear();
|
|
218
|
+
await this.publicationSession.endSession();
|
|
219
|
+
}
|
|
220
|
+
}
|
|
@@ -17,10 +17,10 @@ import { CurrentDataDocumentV3, serializeParameterLookup, SourceTableDocumentV3
|
|
|
17
17
|
* The loadSizes(), loadDocuments() and loadTruncateBatch() methods are preparation
|
|
18
18
|
* reads: callers must hold the lease's writer mutex and use its shared causal
|
|
19
19
|
* session outside any transaction. These reads always request primary/majority
|
|
20
|
-
* consistency
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
20
|
+
* consistency. The lease pipeline advances the session clock from confirmed
|
|
21
|
+
* publications before reads, and overlays pending source-record versions while
|
|
22
|
+
* publication proceeds on a separate session. Pin those versions through reads
|
|
23
|
+
* that overlap commit. Publication never repeats these reads on transaction retry.
|
|
24
24
|
*/
|
|
25
25
|
export class SourceRecordStoreV3 implements SourceRecordStore {
|
|
26
26
|
constructor(
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { bson } from '@powersync/service-core';
|
|
2
1
|
import { BucketDataDoc } from '../common/BucketDataDoc.js';
|
|
3
2
|
|
|
4
3
|
export const DEFAULT_MAX_DOC_SIZE_BYTES = 1024 * 1024; // 1MB
|
|
@@ -19,8 +18,14 @@ export function chunkBucketData(
|
|
|
19
18
|
let currentSize = 0;
|
|
20
19
|
|
|
21
20
|
for (const op of operations) {
|
|
22
|
-
//
|
|
23
|
-
|
|
21
|
+
// Chunk boundaries only need an estimate, but should be close to actual values.
|
|
22
|
+
// This estimate is more CPU-efficient than calculating the actual BSON size.
|
|
23
|
+
const opSize =
|
|
24
|
+
192 +
|
|
25
|
+
Buffer.byteLength(op.data ?? '') +
|
|
26
|
+
2 * Buffer.byteLength(op.subkey ?? '') +
|
|
27
|
+
Buffer.byteLength(op.table ?? '') +
|
|
28
|
+
Buffer.byteLength(op.row_id ?? '');
|
|
24
29
|
|
|
25
30
|
if (currentSize + opSize > maxDocSizeBytes && currentChunk.length > 0) {
|
|
26
31
|
chunks.push(currentChunk);
|
package/src/types/types.ts
CHANGED
|
@@ -44,6 +44,10 @@ export const MongoStorageReadPreference = service_types.enumLiteral(
|
|
|
44
44
|
|
|
45
45
|
export type MongoStorageReadPreference = t.Encoded<typeof MongoStorageReadPreference>;
|
|
46
46
|
|
|
47
|
+
/** Coordinated replication batch/transaction targets; default: medium. */
|
|
48
|
+
export const MongoReplicationBatchSize = service_types.enumLiteral('small', 'medium', 'large');
|
|
49
|
+
export type MongoReplicationBatchSize = t.Encoded<typeof MongoReplicationBatchSize>;
|
|
50
|
+
|
|
47
51
|
export const MongoStorageConfig = service_types.configFile.BaseStorageConfig.and(lib_mongo.BaseMongoConfig).and(
|
|
48
52
|
t.object({
|
|
49
53
|
/**
|
|
@@ -74,6 +78,9 @@ export const MongoStorageConfig = service_types.configFile.BaseStorageConfig.and
|
|
|
74
78
|
/** Maximum concurrent buckets across V3 chunk-compaction jobs. Range: 1–64. Default: 4 with object storage, otherwise 2. */
|
|
75
79
|
chunk_compaction_concurrency: t.number.optional(),
|
|
76
80
|
|
|
81
|
+
/** Larger batches improve throughput at the cost of retained memory. Default: medium. */
|
|
82
|
+
replication_batch_size: MongoReplicationBatchSize.optional(),
|
|
83
|
+
|
|
77
84
|
object_storage: S3ObjectStorageConfig.optional()
|
|
78
85
|
})
|
|
79
86
|
);
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { isMongoServerError, mongo } from '@powersync/lib-service-mongodb';
|
|
2
|
+
|
|
3
|
+
type CollectionNames = readonly { name: string }[];
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Creates a size reader with command support cached for the owning storage factory's lifetime.
|
|
7
|
+
*/
|
|
8
|
+
export function createCollectionSizeReader(db: mongo.Db, readPreference?: mongo.ReadPreference) {
|
|
9
|
+
let dataSizeSupported = true;
|
|
10
|
+
return async (collections: CollectionNames): Promise<Map<string, number>> => {
|
|
11
|
+
if (dataSizeSupported) {
|
|
12
|
+
try {
|
|
13
|
+
return await getDataSizes(db, collections, readPreference);
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (isDataSizeUnsupported(error)) {
|
|
16
|
+
// Remember unsupported commands for this factory's lifetime, including subsequent scrapes.
|
|
17
|
+
dataSizeSupported = false;
|
|
18
|
+
} else {
|
|
19
|
+
throw error;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return getCollStatsSizes(db, collections, readPreference);
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function isDataSizeUnsupported(error: unknown): boolean {
|
|
29
|
+
// Observed on M0 cluster:
|
|
30
|
+
// errmsg: 'CMD_NOT_ALLOWED: dataSize',
|
|
31
|
+
// code: 8000,
|
|
32
|
+
// codeName: 'AtlasError'
|
|
33
|
+
// We support other permutations in case it other error codes are used in other scenarios.
|
|
34
|
+
|
|
35
|
+
return (
|
|
36
|
+
isMongoServerError(error) &&
|
|
37
|
+
(error.code === 59 || // CommandNotFound
|
|
38
|
+
error.code === 115 || // CommandNotSupported
|
|
39
|
+
(error.code === 8000 && // AtlasError: the command is unavailable on this Atlas tier.
|
|
40
|
+
/dataSize/i.test(error.message) &&
|
|
41
|
+
/not allowed|not supported|unsupported|CMD_NOT_ALLOWED/i.test(error.message)))
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Get collection sizes via the `dataSize` command. This does not require opening storage statistics cursors,
|
|
47
|
+
* resulting in less work and lower memory usage on the server.
|
|
48
|
+
*
|
|
49
|
+
* Two disadvantages:
|
|
50
|
+
* 1. No batch support - each collection is queried sequentially, which can be slower for large numbers of collections.
|
|
51
|
+
* 2. The `dataSize` command is not supported on all MongoDB deployments, so we fall back to `collStats` if it fails.
|
|
52
|
+
*
|
|
53
|
+
* We avoid concurrent queries to avoid filling connection pools, which can cause delays in other queriers, and can
|
|
54
|
+
* also increase overhead on the server.
|
|
55
|
+
*/
|
|
56
|
+
async function getDataSizes(
|
|
57
|
+
db: mongo.Db,
|
|
58
|
+
collections: CollectionNames,
|
|
59
|
+
readPreference?: mongo.ReadPreference
|
|
60
|
+
): Promise<Map<string, number>> {
|
|
61
|
+
const sizesByCollection = new Map<string, number>();
|
|
62
|
+
// With estimate enabled and no bounds, dataSize reads the cached logical size without
|
|
63
|
+
// opening storage statistics cursors that keep idle collections' WiredTiger handles warm.
|
|
64
|
+
// Query sequentially so metrics collection does not fill the connection pool on standby pods.
|
|
65
|
+
for (const collection of collections) {
|
|
66
|
+
const stats = await db.command(
|
|
67
|
+
{ dataSize: `${db.databaseName}.${collection.name}`, estimate: true },
|
|
68
|
+
{ readPreference }
|
|
69
|
+
);
|
|
70
|
+
sizesByCollection.set(collection.name, Number(stats.size));
|
|
71
|
+
}
|
|
72
|
+
return sizesByCollection;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Query collection sizes using $collStats, batched using $unionWith.
|
|
77
|
+
*/
|
|
78
|
+
async function getCollStatsSizes(
|
|
79
|
+
db: mongo.Db,
|
|
80
|
+
collections: CollectionNames,
|
|
81
|
+
readPreference?: mongo.ReadPreference
|
|
82
|
+
): Promise<Map<string, number>> {
|
|
83
|
+
const sizesByCollection = new Map<string, number>();
|
|
84
|
+
const statsPipeline: mongo.Document[] = [
|
|
85
|
+
{ $collStats: { storageStats: {} } },
|
|
86
|
+
{ $project: { ns: 1, size: '$storageStats.size' } }
|
|
87
|
+
];
|
|
88
|
+
// MongoDB has a limit of 1000 stages per aggregation pipeline. Additionally, we want
|
|
89
|
+
// to avoid too much work per aggregation, so we limit the number of collections per batch.
|
|
90
|
+
const COLLECTIONS_PER_BATCH = 100;
|
|
91
|
+
// Query batches sequentially so metrics collection does not fill the connection pool on standby pods.
|
|
92
|
+
// If a collection disappears during aggregation, let the next metrics collection retry.
|
|
93
|
+
for (let offset = 0; offset < collections.length; offset += COLLECTIONS_PER_BATCH) {
|
|
94
|
+
const batch = collections.slice(offset, offset + COLLECTIONS_PER_BATCH);
|
|
95
|
+
const pipeline = [
|
|
96
|
+
...statsPipeline,
|
|
97
|
+
...batch.slice(1).map((collection) => ({
|
|
98
|
+
$unionWith: { coll: collection.name, pipeline: statsPipeline }
|
|
99
|
+
}))
|
|
100
|
+
];
|
|
101
|
+
const stats = await db
|
|
102
|
+
.collection(batch[0].name)
|
|
103
|
+
.aggregate<{ ns: string; size: number | bigint }>(pipeline, {
|
|
104
|
+
readPreference
|
|
105
|
+
})
|
|
106
|
+
.toArray();
|
|
107
|
+
for (const stat of stats) {
|
|
108
|
+
const name = stat.ns.slice(db.databaseName.length + 1);
|
|
109
|
+
sizesByCollection.set(name, (sizesByCollection.get(name) ?? 0) + Number(stat.size));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return sizesByCollection;
|
|
114
|
+
}
|
package/src/utils/test-utils.ts
CHANGED
|
@@ -15,11 +15,6 @@ export function mongoTestStorageFactoryGenerator(factoryOptions: MongoTestStorag
|
|
|
15
15
|
factory: async (options?: TestStorageOptions) => {
|
|
16
16
|
const db = connectMongoForTests(factoryOptions.url, factoryOptions.isCI, factoryOptions.monitorCommands);
|
|
17
17
|
|
|
18
|
-
// None of the tests insert data into this collection, so it was never created
|
|
19
|
-
if (!(await db.db.listCollections({ name: db.bucket_parameters.collectionName }).hasNext())) {
|
|
20
|
-
await db.db.createCollection('bucket_parameters');
|
|
21
|
-
}
|
|
22
|
-
|
|
23
18
|
// Full migrations are not currently run for tests, so we manually create this
|
|
24
19
|
await db.createCheckpointEventsCollection();
|
|
25
20
|
|
|
@@ -33,6 +28,7 @@ export function mongoTestStorageFactoryGenerator(factoryOptions: MongoTestStorag
|
|
|
33
28
|
supportsMultipleSyncConfigs: factoryOptions.supportsMultipleSyncConfigs,
|
|
34
29
|
objectStorage: factoryOptions.objectStorage,
|
|
35
30
|
chunkCompactionConcurrency: factoryOptions.chunkCompactionConcurrency,
|
|
31
|
+
replicationBatchSize: factoryOptions.replicationBatchSize,
|
|
36
32
|
inlineThresholdBytes: factoryOptions.inlineThresholdBytes
|
|
37
33
|
});
|
|
38
34
|
},
|
|
@@ -200,8 +200,6 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
|
|
|
200
200
|
factoryGen,
|
|
201
201
|
a.stream.replicationStreamId
|
|
202
202
|
);
|
|
203
|
-
await insert(first, a.table, 'first');
|
|
204
|
-
await insert(last, lastTable, 'last');
|
|
205
203
|
|
|
206
204
|
const entered = Promise.withResolvers<void>();
|
|
207
205
|
const release = Promise.withResolvers<void>();
|
|
@@ -225,6 +223,8 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
|
|
|
225
223
|
});
|
|
226
224
|
const pending: Promise<unknown>[] = [];
|
|
227
225
|
try {
|
|
226
|
+
await insert(first, a.table, 'first');
|
|
227
|
+
await insert(last, lastTable, 'last');
|
|
228
228
|
pending.push(first.flush());
|
|
229
229
|
await entered.promise;
|
|
230
230
|
// The empty checkpoint must run before the later flush.
|
|
@@ -462,18 +462,12 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
|
|
|
462
462
|
await writerB.flush();
|
|
463
463
|
const higher = writerB.last_flushed_op!;
|
|
464
464
|
await insert(writerA, a.table, 'c');
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
} else {
|
|
472
|
-
await writerA.flush();
|
|
473
|
-
expect(writerA.last_flushed_op).toBeGreaterThan(higher);
|
|
474
|
-
await writerA.commit('1/2');
|
|
475
|
-
expect((await a.bucketStorage.getCheckpoint()).checkpoint).toBe(writerA.last_flushed_op);
|
|
476
|
-
}
|
|
465
|
+
// The v3/v4 coordinator also shares allocation across factories on the
|
|
466
|
+
// same lease, so reservation order cannot make a later publisher stale.
|
|
467
|
+
await writerA.flush();
|
|
468
|
+
expect(writerA.last_flushed_op).toBeGreaterThan(higher);
|
|
469
|
+
await writerA.commit('1/2');
|
|
470
|
+
expect((await a.bucketStorage.getCheckpoint()).checkpoint).toBe(writerA.last_flushed_op);
|
|
477
471
|
});
|
|
478
472
|
|
|
479
473
|
test('lease takeover fences stale row, metadata, and checkpoint writes', async () => {
|
|
@@ -548,7 +542,7 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
|
|
|
548
542
|
});
|
|
549
543
|
});
|
|
550
544
|
|
|
551
|
-
describe.each([1, 2])('
|
|
545
|
+
describe.each([1, 2])('v%s batch lifecycle', (version) => {
|
|
552
546
|
test('clears a successful flush and can accumulate the next writes independently', async () => {
|
|
553
547
|
await using factory = await factoryGen.factory();
|
|
554
548
|
const context = await openStream(factory, version);
|