@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
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { MongoReplicationBatchSize } from '../../types/types.js';
|
|
2
|
+
|
|
3
|
+
/** Headroom for JS objects, memberships, packed chunks and upload buffers. */
|
|
4
|
+
export const RETAINED_BYTES_FACTOR = 4;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One predecessor plus its successor. Preparation's overlay assumes at most one
|
|
8
|
+
* predecessor, so increasing this requires more than changing a capacity limit.
|
|
9
|
+
*/
|
|
10
|
+
export const MAX_PIPELINE_BATCHES = 2;
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_REPLICATION_BATCH_SIZE: MongoReplicationBatchSize = 'medium';
|
|
13
|
+
|
|
14
|
+
/** Flush/backpressure targets, not hard memory ceilings or single-row limits. */
|
|
15
|
+
export interface ReplicationBatchLimits {
|
|
16
|
+
/** Row operations or custom checkpoints in a writer's input buffer. */
|
|
17
|
+
readonly maxInputBatchCount: number;
|
|
18
|
+
/** Estimated input bytes before row evaluation. */
|
|
19
|
+
readonly maxInputBatchBytes: number;
|
|
20
|
+
/** Per write category, preserving the existing transaction splitting rules. */
|
|
21
|
+
readonly maxTransactionBatchCount: number;
|
|
22
|
+
readonly maxTransactionBatchBytes: number;
|
|
23
|
+
/** Accounted work including packing headroom; excludes source/raw input buffers. */
|
|
24
|
+
readonly maxPipelineBytes: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function profile(count: number, inputBytes: number, transactionBytes: number): ReplicationBatchLimits {
|
|
28
|
+
return Object.freeze({
|
|
29
|
+
maxInputBatchCount: count,
|
|
30
|
+
maxInputBatchBytes: inputBytes,
|
|
31
|
+
maxTransactionBatchCount: count,
|
|
32
|
+
maxTransactionBatchBytes: transactionBytes,
|
|
33
|
+
maxPipelineBytes: MAX_PIPELINE_BATCHES * RETAINED_BYTES_FACTOR * transactionBytes
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Larger profiles trade higher retained memory for fewer flushes and round trips. */
|
|
38
|
+
export const REPLICATION_BATCH_LIMITS: Readonly<Record<MongoReplicationBatchSize, ReplicationBatchLimits>> =
|
|
39
|
+
Object.freeze({
|
|
40
|
+
small: profile(4_000, 2 * 1024 * 1024, 4 * 1024 * 1024),
|
|
41
|
+
medium: profile(8_000, 4 * 1024 * 1024, 8 * 1024 * 1024),
|
|
42
|
+
large: profile(16_000, 8 * 1024 * 1024, 16 * 1024 * 1024)
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_REPLICATION_BATCH_LIMITS = REPLICATION_BATCH_LIMITS[DEFAULT_REPLICATION_BATCH_SIZE];
|
|
@@ -4,33 +4,13 @@ import { JSONBig } from '@powersync/service-jsonbig';
|
|
|
4
4
|
import { BucketDataSource, BucketDefinitionId } from '@powersync/service-sync-rules';
|
|
5
5
|
import { mongoTableId, replicaIdToSubkey } from '../../../utils/util.js';
|
|
6
6
|
import { currentBucketKey, MAX_ROW_SIZE } from '../MongoBucketBatchShared.js';
|
|
7
|
+
import { DEFAULT_REPLICATION_BATCH_LIMITS, ReplicationBatchLimits } from '../ReplicationBatchLimits.js';
|
|
7
8
|
import { TaggedBucketParameterDocument } from '../models.js';
|
|
8
9
|
import { BucketDataDoc, BucketKey } from './BucketDataDoc.js';
|
|
9
10
|
import { BucketStateUpdate, SaveBucketDataOptions } from './PersistedBatch.js';
|
|
10
11
|
import { PublicationStats } from './PreparedPublication.js';
|
|
11
12
|
import { SourceRecordBucketState } from './SourceRecordStore.js';
|
|
12
13
|
|
|
13
|
-
/**
|
|
14
|
-
* Maximum size of operations we write in a single transaction.
|
|
15
|
-
*
|
|
16
|
-
* It's tricky to find the exact limit, but from experience, over 100MB
|
|
17
|
-
* can cause an error:
|
|
18
|
-
* > transaction is too large and will not fit in the storage engine cache
|
|
19
|
-
*
|
|
20
|
-
* Additionally, unbounded size here can balloon our memory usage in some edge
|
|
21
|
-
* cases.
|
|
22
|
-
*
|
|
23
|
-
* When we reach this threshold, we commit the transaction and start a new one.
|
|
24
|
-
*/
|
|
25
|
-
const MAX_TRANSACTION_BATCH_SIZE = 30_000_000;
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Limit number of documents to write in a single transaction.
|
|
29
|
-
*
|
|
30
|
-
* This has an effect on error message size in some cases.
|
|
31
|
-
*/
|
|
32
|
-
const MAX_TRANSACTION_DOC_COUNT = 2_000;
|
|
33
|
-
|
|
34
14
|
/**
|
|
35
15
|
* Shared operation generation, size accounting and diagnostics. Each storage
|
|
36
16
|
* version owns this buffer and decides when to write, retain or clear its data.
|
|
@@ -58,7 +38,8 @@ export class BatchOperationBuffer {
|
|
|
58
38
|
checkDefinitionId(id: BucketDefinitionId | null): BucketDefinitionId;
|
|
59
39
|
getBucketDefinitionId(source: BucketDataSource): BucketDefinitionId;
|
|
60
40
|
},
|
|
61
|
-
private readonly logger: Logger = defaultLogger
|
|
41
|
+
private readonly logger: Logger = defaultLogger,
|
|
42
|
+
private readonly limits: ReplicationBatchLimits = DEFAULT_REPLICATION_BATCH_LIMITS
|
|
62
43
|
) {
|
|
63
44
|
this.currentSize = writtenSize;
|
|
64
45
|
}
|
|
@@ -257,12 +238,26 @@ export class BatchOperationBuffer {
|
|
|
257
238
|
});
|
|
258
239
|
}
|
|
259
240
|
|
|
241
|
+
/**
|
|
242
|
+
* Maximum size of operations we write in a single transaction.
|
|
243
|
+
*
|
|
244
|
+
* It's tricky to find the exact limit, but from experience, over 100MB
|
|
245
|
+
* can cause an error:
|
|
246
|
+
* > transaction is too large and will not fit in the storage engine cache
|
|
247
|
+
*
|
|
248
|
+
* Additionally, unbounded size here can balloon our memory usage in some edge
|
|
249
|
+
* cases.
|
|
250
|
+
*
|
|
251
|
+
* When we reach this threshold, we commit the transaction and start a new one.
|
|
252
|
+
* We also limit the number of documents per write category; this has an effect
|
|
253
|
+
* on error message size in some cases.
|
|
254
|
+
*/
|
|
260
255
|
shouldFlushTransaction(currentDataCount: number) {
|
|
261
256
|
return (
|
|
262
|
-
this.currentSize >=
|
|
263
|
-
this.bucketDataCount >=
|
|
264
|
-
currentDataCount >=
|
|
265
|
-
this.bucketParameters.length >=
|
|
257
|
+
this.currentSize >= this.limits.maxTransactionBatchBytes ||
|
|
258
|
+
this.bucketDataCount >= this.limits.maxTransactionBatchCount ||
|
|
259
|
+
currentDataCount >= this.limits.maxTransactionBatchCount ||
|
|
260
|
+
this.bucketParameters.length >= this.limits.maxTransactionBatchCount
|
|
266
261
|
);
|
|
267
262
|
}
|
|
268
263
|
|
|
@@ -3,6 +3,7 @@ import { InternalOpId, storage } from '@powersync/service-core';
|
|
|
3
3
|
import { BucketDefinitionId, EvaluatedParameters, EvaluatedRow } from '@powersync/service-sync-rules';
|
|
4
4
|
import * as bson from 'bson';
|
|
5
5
|
import { MongoIdSequence } from '../MongoIdSequence.js';
|
|
6
|
+
import { ReplicationBatchLimits } from '../ReplicationBatchLimits.js';
|
|
6
7
|
import { SourceRecordBucketState, SourceRecordLookupState } from './SourceRecordStore.js';
|
|
7
8
|
|
|
8
9
|
export interface SaveBucketDataOptions {
|
|
@@ -30,6 +31,7 @@ export interface UpsertCurrentDataOptions {
|
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
export interface PersistedBatchOptions {
|
|
34
|
+
batchLimits?: ReplicationBatchLimits;
|
|
33
35
|
logger?: Logger;
|
|
34
36
|
}
|
|
35
37
|
|
|
@@ -10,8 +10,9 @@ export interface PublicationStats {
|
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
* Sealed
|
|
14
|
-
*
|
|
13
|
+
* Sealed writes from v3/v4 row preparation. Payload packing and uploads finish
|
|
14
|
+
* preparation once, including on failure; MongoDB transaction retries create
|
|
15
|
+
* fresh writes on every attempt without clearing the sealed batch.
|
|
15
16
|
*
|
|
16
17
|
* Scheduling metadata belongs to the caller: lease, selected config/mappings,
|
|
17
18
|
* input suffix, checkpoint intent and durable progress. Replay is valid only
|
|
@@ -20,7 +21,7 @@ export interface PublicationStats {
|
|
|
20
21
|
* fit a different context or overwrite its object paths. Publication also
|
|
21
22
|
* asserts that assigned IDs advance the freshly fenced persisted head.
|
|
22
23
|
*
|
|
23
|
-
* No
|
|
24
|
+
* No connector repair callbacks run here. The coordinator collects
|
|
24
25
|
* markRecordUnavailable records during evaluation and delivers them only after
|
|
25
26
|
* confirmed commit. Diagnostics run during evaluation.
|
|
26
27
|
* Before/after-flush hooks, source events and custom checkpoint consumption also
|
|
@@ -29,14 +30,17 @@ export interface PublicationStats {
|
|
|
29
30
|
*/
|
|
30
31
|
export interface PreparedPublication {
|
|
31
32
|
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
33
|
+
* Finish preparation by packing payloads and uploading offloaded chunks.
|
|
34
|
+
* This can overlap a predecessor's uploads or MongoDB publication.
|
|
35
|
+
* Preparation has already consumed assigned IDs. Sealing itself starts no I/O,
|
|
36
|
+
* so the coordinator can establish ownership before yielding.
|
|
37
|
+
* A packing/upload failure is terminal for this generation; all started uploads
|
|
38
|
+
* must settle before this promise rejects.
|
|
36
39
|
*/
|
|
37
|
-
|
|
40
|
+
packAndUploadPayloads(): Promise<void>;
|
|
38
41
|
/**
|
|
39
|
-
*
|
|
42
|
+
* Commit the MongoDB portion of the publishing stage. Packing and uploads must
|
|
43
|
+
* finish before starting the transaction.
|
|
40
44
|
* An optional batch supplies independent head/checkpoint writes to execute
|
|
41
45
|
* together with this group's data. This method owns execution of that batch;
|
|
42
46
|
* callers must not execute it again or include another group's dependent writes.
|
|
@@ -178,6 +178,21 @@ export class PowerSyncMongo {
|
|
|
178
178
|
return collections.map((c) => this.db.collection<CommonSourceTableDocument>(c.name));
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
+
get v1DataCollections() {
|
|
182
|
+
return [this.current_data, this.bucket_data, this.bucket_parameters, this.bucket_state, this.source_tables];
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async initializeV1StorageCollections(): Promise<void> {
|
|
186
|
+
for (const collection of this.v1DataCollections) {
|
|
187
|
+
await this.db.createCollection(collection.collectionName).catch((error) => {
|
|
188
|
+
if (!lib_mongo.isMongoServerError(error) || error.codeName !== 'NamespaceExists') throw error;
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
await this.bucket_parameters.createIndex({ 'key.g': 1, lookup: 1, _id: 1 }, { name: 'lookup1' });
|
|
192
|
+
await this.createBucketStateIndex();
|
|
193
|
+
await this.createBucketStateIndex2();
|
|
194
|
+
}
|
|
195
|
+
|
|
181
196
|
/**
|
|
182
197
|
* Clear all collections.
|
|
183
198
|
*/
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { mongo } from '@powersync/lib-service-mongodb';
|
|
2
2
|
import { ErrorCode, ReplicationAssertionError, ServiceError } from '@powersync/lib-services-framework';
|
|
3
3
|
import { ColumnDescriptor, InternalOpId, SourceTable, storage } from '@powersync/service-core';
|
|
4
|
-
import { HydratedSyncConfig } from '@powersync/service-sync-rules';
|
|
4
|
+
import { HydratedEventDescriptor, HydratedSyncConfig } from '@powersync/service-sync-rules';
|
|
5
5
|
import * as bson from 'bson';
|
|
6
|
+
import * as timers from 'node:timers/promises';
|
|
6
7
|
import { mongoTableId } from '../../../utils/util.js';
|
|
7
8
|
import { calculateCheckpointState } from '../CheckpointState.js';
|
|
8
9
|
import { MongoBucketBatch, MongoBucketBatchOptions } from '../MongoBucketBatch.js';
|
|
@@ -39,6 +40,64 @@ export class MongoBucketBatchV1 extends MongoBucketBatch {
|
|
|
39
40
|
this.store = new SourceRecordStoreV1(this.db, this.replicationStreamId);
|
|
40
41
|
}
|
|
41
42
|
|
|
43
|
+
protected override getTableEvents(table: storage.SourceTable): { event: HydratedEventDescriptor }[] {
|
|
44
|
+
// V1/v2 leave eventDefinitionIds undefined and selects events by table ref.
|
|
45
|
+
return this.sync_rules.eventDescriptors
|
|
46
|
+
.filter((event) => event.tableTriggersEvent(table.ref))
|
|
47
|
+
.map((event) => ({ event }));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
override async save(record: storage.SaveOptions): Promise<storage.FlushedResult | null> {
|
|
51
|
+
if (this.bufferRecord(record)) {
|
|
52
|
+
return this.automaticFlush();
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
override async commit(lsn: string, options?: storage.BucketBatchCommitOptions): Promise<storage.CheckpointResult> {
|
|
58
|
+
return this.withWriterLock(() => this.commitInternal(lsn, options), false);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
protected override async withWriterLock<T>(callback: () => Promise<T>, _flushAllWriters = true): Promise<T> {
|
|
62
|
+
using lockSpan = this.tracer.span('storage', 'internal_lock');
|
|
63
|
+
this.options.replicationLock.throwIfAborted();
|
|
64
|
+
return this.options.replicationLock.writerMutex.exclusiveLock(async () => {
|
|
65
|
+
lockSpan.end();
|
|
66
|
+
this.options.replicationLock.throwIfAborted();
|
|
67
|
+
return callback();
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
protected override async withTransaction<T>(
|
|
72
|
+
cb: (stream: SyncRuleDocumentBase) => Promise<T>,
|
|
73
|
+
session = this.session
|
|
74
|
+
): Promise<T> {
|
|
75
|
+
return this.withFencedTransaction(() => this.fence(session), cb, session);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
protected override async prepareCustomWriteCheckpoints(
|
|
79
|
+
_checkpoints: readonly storage.CustomWriteCheckpointOptions[]
|
|
80
|
+
): Promise<void> {}
|
|
81
|
+
|
|
82
|
+
override async [Symbol.asyncDispose](): Promise<void> {
|
|
83
|
+
if (this.batch?.hasData()) {
|
|
84
|
+
// We don't error here, since:
|
|
85
|
+
// 1. In error states, this is expected (we can't distinguish between disposing after success or error).
|
|
86
|
+
// 2. SuppressedError is messy to deal with.
|
|
87
|
+
this.logger.warn('Disposing writer with unflushed changes');
|
|
88
|
+
}
|
|
89
|
+
// The lease owns the shared session and ends it after all writers stop.
|
|
90
|
+
super.clearListeners();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** V1/v2 automatic flushes remain durable. */
|
|
94
|
+
protected override async automaticFlush(): Promise<storage.FlushedResult | null> {
|
|
95
|
+
const result = await this.flush();
|
|
96
|
+
// HACK: Give other streams a chance to also flush.
|
|
97
|
+
await timers.setTimeout(5);
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
|
|
42
101
|
private async withReplicationTransaction(
|
|
43
102
|
description: string,
|
|
44
103
|
callback: (session: mongo.ClientSession, opSeq: MongoIdSequence) => Promise<void>,
|
|
@@ -99,12 +158,52 @@ export class MongoBucketBatchV1 extends MongoBucketBatch {
|
|
|
99
158
|
);
|
|
100
159
|
}
|
|
101
160
|
|
|
102
|
-
|
|
161
|
+
/** Internal helpers require the public operation to hold the writer mutex. */
|
|
162
|
+
protected override async flushInternal(
|
|
163
|
+
options?: storage.BatchBucketFlushOptions
|
|
164
|
+
): Promise<storage.FlushedResult | null> {
|
|
165
|
+
let result: storage.FlushedResult | null = null;
|
|
166
|
+
// One flush may be split over multiple transactions.
|
|
167
|
+
// Each flushInner() is one transaction.
|
|
168
|
+
while (this.batch != null) {
|
|
169
|
+
let r = await this.flushInner(options);
|
|
170
|
+
if (r) {
|
|
171
|
+
result = r;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return result;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Publish the checkpoint in the final flush transaction, or use the empty-commit path. */
|
|
178
|
+
private async flushAndCommit<T>(
|
|
179
|
+
checkpoint: (stream: SyncRuleDocumentBase, lastOp: InternalOpId, writes?: MongoWriteBatch) => Promise<T>,
|
|
180
|
+
commitWithoutFlush: () => Promise<T>,
|
|
181
|
+
options?: storage.BatchBucketFlushOptions,
|
|
182
|
+
projection?: mongo.Document
|
|
183
|
+
): Promise<T> {
|
|
184
|
+
if (this.batch == null) {
|
|
185
|
+
return commitWithoutFlush();
|
|
186
|
+
}
|
|
187
|
+
let result!: T;
|
|
188
|
+
while (this.batch != null) {
|
|
189
|
+
await this.flushInner(
|
|
190
|
+
options,
|
|
191
|
+
async (stream, lastOp, writes) => {
|
|
192
|
+
result = await checkpoint(stream, lastOp, writes);
|
|
193
|
+
},
|
|
194
|
+
projection
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return result;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
private async flushInner(
|
|
103
201
|
options?: storage.BatchBucketFlushOptions,
|
|
104
202
|
checkpoint?: (stream: SyncRuleDocumentBase, lastOp: InternalOpId, writes?: MongoWriteBatch) => Promise<void>,
|
|
105
203
|
projection?: mongo.Document
|
|
106
204
|
): Promise<storage.FlushedResult | null> {
|
|
107
205
|
const batch = this.batch;
|
|
206
|
+
const checkpoints = batch?.customWriteCheckpoints ?? [];
|
|
108
207
|
let last_op: InternalOpId | null = null;
|
|
109
208
|
let resumeBatch: OperationBatch | null = null;
|
|
110
209
|
let clearedError = false;
|
|
@@ -112,9 +211,9 @@ export class MongoBucketBatchV1 extends MongoBucketBatch {
|
|
|
112
211
|
using _ = this.tracer.span('storage', 'flush');
|
|
113
212
|
|
|
114
213
|
await this.hooks?.beforeBatchFlush?.(this);
|
|
115
|
-
if (
|
|
214
|
+
if (checkpoints.length > 0) {
|
|
116
215
|
// Collection/index creation cannot run inside the replication transaction.
|
|
117
|
-
await this.prepareCustomWriteCheckpoints();
|
|
216
|
+
await this.prepareCustomWriteCheckpoints(checkpoints);
|
|
118
217
|
}
|
|
119
218
|
|
|
120
219
|
await this.withReplicationTransaction(
|
|
@@ -127,9 +226,9 @@ export class MongoBucketBatchV1 extends MongoBucketBatch {
|
|
|
127
226
|
clearedError ||= result.clearedError;
|
|
128
227
|
}
|
|
129
228
|
|
|
130
|
-
if (
|
|
131
|
-
this.logger.info(`Writing ${
|
|
132
|
-
await this.batchCreateCustomWriteCheckpoints(session, opSeq.next());
|
|
229
|
+
if (checkpoints.length > 0) {
|
|
230
|
+
this.logger.info(`Writing ${checkpoints.length} custom write checkpoints`);
|
|
231
|
+
await this.batchCreateCustomWriteCheckpoints(session, opSeq.next(), checkpoints);
|
|
133
232
|
}
|
|
134
233
|
|
|
135
234
|
last_op = opSeq.last();
|
|
@@ -145,13 +244,11 @@ export class MongoBucketBatchV1 extends MongoBucketBatch {
|
|
|
145
244
|
projection
|
|
146
245
|
);
|
|
147
246
|
|
|
148
|
-
// Keep checkpoints available if the transaction retries after writing them.
|
|
149
|
-
this.write_checkpoint_batch = [];
|
|
150
|
-
|
|
151
247
|
if (clearedError) {
|
|
152
248
|
this.clearedError = true;
|
|
153
249
|
}
|
|
154
250
|
|
|
251
|
+
// Keep checkpoints available if the transaction retries after writing them.
|
|
155
252
|
// null if done, set if we need another flush
|
|
156
253
|
this.batch = resumeBatch;
|
|
157
254
|
|
|
@@ -260,7 +357,7 @@ export class MongoBucketBatchV1 extends MongoBucketBatch {
|
|
|
260
357
|
// Computing our current progress is a little tricky here, since
|
|
261
358
|
// we're stopping in the middle of a batch.
|
|
262
359
|
// We create a new batch, and push any remaining operations to it.
|
|
263
|
-
resumeBatch = new OperationBatch();
|
|
360
|
+
resumeBatch = new OperationBatch(this.options.batchLimits);
|
|
264
361
|
persistSpan.end();
|
|
265
362
|
evalSpan = this.tracer.span('evaluate');
|
|
266
363
|
}
|
|
@@ -288,6 +385,25 @@ export class MongoBucketBatchV1 extends MongoBucketBatch {
|
|
|
288
385
|
};
|
|
289
386
|
}
|
|
290
387
|
|
|
388
|
+
protected override async truncateInternal(
|
|
389
|
+
sourceTables: storage.SourceTable[]
|
|
390
|
+
): Promise<storage.FlushedResult | null> {
|
|
391
|
+
await this.flushInternal();
|
|
392
|
+
|
|
393
|
+
let last_op: InternalOpId | null = null;
|
|
394
|
+
for (let table of sourceTables) {
|
|
395
|
+
last_op = await this.truncateSingleInternal(table);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
if (last_op) {
|
|
399
|
+
return {
|
|
400
|
+
flushed_op: last_op
|
|
401
|
+
};
|
|
402
|
+
} else {
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
291
407
|
protected override async truncateSingleInternal(sourceTable: storage.SourceTable): Promise<InternalOpId> {
|
|
292
408
|
let last_op: InternalOpId | null = null;
|
|
293
409
|
|
|
@@ -366,7 +482,8 @@ export class MongoBucketBatchV1 extends MongoBucketBatch {
|
|
|
366
482
|
|
|
367
483
|
protected createPersistedBatch(writtenSize: number): PersistedBatchV1 {
|
|
368
484
|
return new PersistedBatchV1(this.db, this.replicationStreamId, writtenSize, {
|
|
369
|
-
logger: this.logger
|
|
485
|
+
logger: this.logger,
|
|
486
|
+
batchLimits: this.options.batchLimits
|
|
370
487
|
});
|
|
371
488
|
}
|
|
372
489
|
|
|
@@ -377,13 +494,14 @@ export class MongoBucketBatchV1 extends MongoBucketBatch {
|
|
|
377
494
|
// No-op for V1: source records live in a shared collection.
|
|
378
495
|
}
|
|
379
496
|
|
|
380
|
-
private async batchCreateCustomWriteCheckpoints(
|
|
497
|
+
private async batchCreateCustomWriteCheckpoints(
|
|
498
|
+
session: mongo.ClientSession,
|
|
499
|
+
opId: InternalOpId,
|
|
500
|
+
inputCheckpoints: readonly storage.CustomWriteCheckpointOptions[]
|
|
501
|
+
): Promise<void> {
|
|
381
502
|
// Only the final checkpoint per user/stream is visible after this transaction.
|
|
382
503
|
const checkpoints = new Map(
|
|
383
|
-
|
|
384
|
-
JSON.stringify([checkpoint.sync_rules_id, checkpoint.user_id]),
|
|
385
|
-
checkpoint
|
|
386
|
-
])
|
|
504
|
+
inputCheckpoints.map((checkpoint) => [JSON.stringify([checkpoint.sync_rules_id, checkpoint.user_id]), checkpoint])
|
|
387
505
|
);
|
|
388
506
|
await this.db.custom_write_checkpoints.bulkWrite(
|
|
389
507
|
[...checkpoints.values()].map((checkpointOptions) => {
|
|
@@ -45,7 +45,8 @@ export class PersistedBatchV1 implements PersistedBatch {
|
|
|
45
45
|
checkDefinitionId: () => LEGACY_BUCKET_DATA_DEFINITION_ID,
|
|
46
46
|
getBucketDefinitionId: () => LEGACY_BUCKET_DATA_DEFINITION_ID
|
|
47
47
|
},
|
|
48
|
-
options?.logger
|
|
48
|
+
options?.logger,
|
|
49
|
+
options?.batchLimits
|
|
49
50
|
);
|
|
50
51
|
}
|
|
51
52
|
|
|
@@ -26,7 +26,9 @@ export class VersionedPowerSyncMongoV1 extends BaseVersionedPowerSyncMongo {
|
|
|
26
26
|
return this.upstream.source_tables as any as mongo.Collection<SourceTableDocumentV1>;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
async initializeStreamStorage(_replicationStreamId: number): Promise<void> {
|
|
29
|
+
async initializeStreamStorage(_replicationStreamId: number): Promise<void> {
|
|
30
|
+
await this.upstream.initializeV1StorageCollections();
|
|
31
|
+
}
|
|
30
32
|
|
|
31
33
|
get bucketDataV1(): mongo.Collection<BucketDataDocumentV1> {
|
|
32
34
|
return this.upstream.bucket_data;
|