@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
|
@@ -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
|
@@ -28,6 +28,7 @@ export function mongoTestStorageFactoryGenerator(factoryOptions: MongoTestStorag
|
|
|
28
28
|
supportsMultipleSyncConfigs: factoryOptions.supportsMultipleSyncConfigs,
|
|
29
29
|
objectStorage: factoryOptions.objectStorage,
|
|
30
30
|
chunkCompactionConcurrency: factoryOptions.chunkCompactionConcurrency,
|
|
31
|
+
replicationBatchSize: factoryOptions.replicationBatchSize,
|
|
31
32
|
inlineThresholdBytes: factoryOptions.inlineThresholdBytes
|
|
32
33
|
});
|
|
33
34
|
},
|
|
@@ -12,6 +12,7 @@ import { MongoPersistedReplicationStream } from '../../src/storage/implementatio
|
|
|
12
12
|
import { PersistedBatchV1 } from '../../src/storage/implementation/v1/PersistedBatchV1.js';
|
|
13
13
|
import { VersionedPowerSyncMongoV1 } from '../../src/storage/implementation/v1/VersionedPowerSyncMongoV1.js';
|
|
14
14
|
import { PersistedBatchV3 } from '../../src/storage/implementation/v3/PersistedBatchV3.js';
|
|
15
|
+
import { VersionedPowerSyncMongoV3 } from '../../src/storage/implementation/v3/VersionedPowerSyncMongoV3.js';
|
|
15
16
|
import { mongoTestStorageFactoryGenerator } from '../../src/utils/test-utils.js';
|
|
16
17
|
import { env } from './env.js';
|
|
17
18
|
|
|
@@ -200,8 +201,6 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
|
|
|
200
201
|
factoryGen,
|
|
201
202
|
a.stream.replicationStreamId
|
|
202
203
|
);
|
|
203
|
-
await insert(first, a.table, 'first');
|
|
204
|
-
await insert(last, lastTable, 'last');
|
|
205
204
|
|
|
206
205
|
const entered = Promise.withResolvers<void>();
|
|
207
206
|
const release = Promise.withResolvers<void>();
|
|
@@ -225,6 +224,8 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
|
|
|
225
224
|
});
|
|
226
225
|
const pending: Promise<unknown>[] = [];
|
|
227
226
|
try {
|
|
227
|
+
await insert(first, a.table, 'first');
|
|
228
|
+
await insert(last, lastTable, 'last');
|
|
228
229
|
pending.push(first.flush());
|
|
229
230
|
await entered.promise;
|
|
230
231
|
// The empty checkpoint must run before the later flush.
|
|
@@ -462,18 +463,12 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
|
|
|
462
463
|
await writerB.flush();
|
|
463
464
|
const higher = writerB.last_flushed_op!;
|
|
464
465
|
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
|
-
}
|
|
466
|
+
// The v3/v4 coordinator also shares allocation across factories on the
|
|
467
|
+
// same lease, so reservation order cannot make a later publisher stale.
|
|
468
|
+
await writerA.flush();
|
|
469
|
+
expect(writerA.last_flushed_op).toBeGreaterThan(higher);
|
|
470
|
+
await writerA.commit('1/2');
|
|
471
|
+
expect((await a.bucketStorage.getCheckpoint()).checkpoint).toBe(writerA.last_flushed_op);
|
|
477
472
|
});
|
|
478
473
|
|
|
479
474
|
test('lease takeover fences stale row, metadata, and checkpoint writes', async () => {
|
|
@@ -503,8 +498,20 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
|
|
|
503
498
|
await insert(nextWriter, nextTable, 'new');
|
|
504
499
|
await nextWriter.commit('1/2');
|
|
505
500
|
expect(nextWriter.last_flushed_op).toBeGreaterThan(abandonedEnd);
|
|
501
|
+
const db = factory.db.versioned(stream.getStorageConfig());
|
|
502
|
+
const bucketState =
|
|
503
|
+
db instanceof VersionedPowerSyncMongoV3 ? db.bucketState(stream.replicationStreamId) : undefined;
|
|
504
|
+
const stateBefore = await bucketState?.findOne({});
|
|
505
|
+
if (bucketState != null) {
|
|
506
|
+
expect(stateBefore).not.toBeNull();
|
|
507
|
+
}
|
|
506
508
|
await insert(oldWriter, oldTable, 'stale');
|
|
507
509
|
await expect(oldWriter.flush()).rejects.toThrow('no longer owns');
|
|
510
|
+
if (bucketState != null) {
|
|
511
|
+
// The stale publication wrote bucket state inside its transaction before
|
|
512
|
+
// the fence rejected it. Neither its counters nor its head may leak.
|
|
513
|
+
expect(await bucketState.findOne({})).toEqual(stateBefore);
|
|
514
|
+
}
|
|
508
515
|
await expect(oldWriter.setResumeLsn('9/9')).rejects.toBeInstanceOf(ReplicationAbortedError);
|
|
509
516
|
await expect(oldWriter.markAllSnapshotDone('9/9')).rejects.toBeInstanceOf(ReplicationAbortedError);
|
|
510
517
|
await expect(oldWriter.markTableSnapshotRequired(oldTable)).rejects.toBeInstanceOf(ReplicationAbortedError);
|
|
@@ -548,7 +555,7 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
|
|
|
548
555
|
});
|
|
549
556
|
});
|
|
550
557
|
|
|
551
|
-
describe.each([1, 2])('
|
|
558
|
+
describe.each([1, 2])('v%s batch lifecycle', (version) => {
|
|
552
559
|
test('clears a successful flush and can accumulate the next writes independently', async () => {
|
|
553
560
|
await using factory = await factoryGen.factory();
|
|
554
561
|
const context = await openStream(factory, version);
|
|
@@ -74,9 +74,20 @@ export class PublicationCommandMonitor implements Disposable {
|
|
|
74
74
|
transaction = { key, startedAt, replication: false, commands: [] };
|
|
75
75
|
this.transactions.set(key, transaction);
|
|
76
76
|
}
|
|
77
|
-
//
|
|
78
|
-
//
|
|
79
|
-
transaction.replication ||=
|
|
77
|
+
// A publication can abort on bucket state before reaching the fence.
|
|
78
|
+
// Replication advances last_op, while compaction updates the lease and stats.
|
|
79
|
+
transaction.replication ||=
|
|
80
|
+
(event.commandName === 'findAndModify' && command.findAndModify === 'sync_rules') ||
|
|
81
|
+
(event.commandName === 'update' &&
|
|
82
|
+
command.update.startsWith('bucket_state_') &&
|
|
83
|
+
command.updates.some(({ u }: { u: unknown }) => advancesBucketHead(u))) ||
|
|
84
|
+
(event.commandName === 'bulkWrite' &&
|
|
85
|
+
command.ops.some(
|
|
86
|
+
({ update, updateMods }: { update?: number; updateMods?: unknown }) =>
|
|
87
|
+
update != null &&
|
|
88
|
+
command.nsInfo[update].ns.split('.')[1]?.startsWith('bucket_state_') &&
|
|
89
|
+
advancesBucketHead(updateMods)
|
|
90
|
+
));
|
|
80
91
|
}
|
|
81
92
|
const sample: CommandSample = { name: event.commandName, startedAt, transaction };
|
|
82
93
|
this.commands.push(sample);
|
|
@@ -117,3 +128,7 @@ export class PublicationCommandMonitor implements Disposable {
|
|
|
117
128
|
this.client.off('commandFailed', this.failed);
|
|
118
129
|
}
|
|
119
130
|
}
|
|
131
|
+
|
|
132
|
+
function advancesBucketHead(update: unknown) {
|
|
133
|
+
return Array.isArray(update) && update.some((stage) => Object.hasOwn(stage.$set ?? {}, 'last_op'));
|
|
134
|
+
}
|