@powersync/service-module-mongodb-storage 0.0.0-dev-20260803144812 → 0.0.0-dev-20260929095716
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 +129 -7
- package/dist/storage/MongoBucketStorage.d.ts +42 -5
- package/dist/storage/MongoBucketStorage.js +404 -215
- package/dist/storage/MongoBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoBucketBatch.d.ts +39 -14
- package/dist/storage/implementation/MongoBucketBatch.js +169 -98
- package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
- package/dist/storage/implementation/MongoCompactor.d.ts +21 -79
- package/dist/storage/implementation/MongoCompactor.js +27 -238
- package/dist/storage/implementation/MongoCompactor.js.map +1 -1
- package/dist/storage/implementation/MongoIdSequence.d.ts +10 -1
- package/dist/storage/implementation/MongoIdSequence.js +14 -1
- package/dist/storage/implementation/MongoIdSequence.js.map +1 -1
- package/dist/storage/implementation/MongoOpIdAllocator.d.ts +27 -0
- package/dist/storage/implementation/MongoOpIdAllocator.js +97 -0
- package/dist/storage/implementation/MongoOpIdAllocator.js.map +1 -0
- package/dist/storage/implementation/MongoParameterCompactor.d.ts +83 -10
- package/dist/storage/implementation/MongoParameterCompactor.js +309 -96
- package/dist/storage/implementation/MongoParameterCompactor.js.map +1 -1
- package/dist/storage/implementation/MongoParsedSyncConfigSet.d.ts +9 -1
- package/dist/storage/implementation/MongoParsedSyncConfigSet.js +35 -2
- package/dist/storage/implementation/MongoParsedSyncConfigSet.js.map +1 -1
- package/dist/storage/implementation/MongoPersistedReplicationStream.d.ts +2 -1
- package/dist/storage/implementation/MongoPersistedReplicationStream.js +7 -4
- package/dist/storage/implementation/MongoPersistedReplicationStream.js.map +1 -1
- package/dist/storage/implementation/MongoPersistedSyncConfigContent.d.ts +3 -3
- package/dist/storage/implementation/MongoPersistedSyncConfigContent.js +10 -8
- package/dist/storage/implementation/MongoPersistedSyncConfigContent.js.map +1 -1
- package/dist/storage/implementation/MongoStorageProvider.js +8 -4
- package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
- package/dist/storage/implementation/MongoSyncBucketStorage.d.ts +32 -11
- package/dist/storage/implementation/MongoSyncBucketStorage.js +95 -31
- package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoSyncRulesLock.d.ts +26 -2
- package/dist/storage/implementation/MongoSyncRulesLock.js +59 -10
- package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
- package/dist/storage/implementation/MongoWriteBatch.d.ts +49 -0
- package/dist/storage/implementation/MongoWriteBatch.js +149 -0
- package/dist/storage/implementation/MongoWriteBatch.js.map +1 -0
- package/dist/storage/implementation/MongoWriteCheckpointAPI.d.ts +9 -7
- package/dist/storage/implementation/MongoWriteCheckpointAPI.js +9 -30
- package/dist/storage/implementation/MongoWriteCheckpointAPI.js.map +1 -1
- package/dist/storage/implementation/SyncRuleStateUpdate.d.ts +11 -5
- package/dist/storage/implementation/SyncRuleStateUpdate.js +14 -6
- package/dist/storage/implementation/SyncRuleStateUpdate.js.map +1 -1
- package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.d.ts +22 -2
- package/dist/storage/implementation/common/PersistedBatch.d.ts +32 -4
- package/dist/storage/implementation/common/PersistedBatch.js +57 -14
- package/dist/storage/implementation/common/PersistedBatch.js.map +1 -1
- package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.d.ts +3 -0
- package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js +3 -0
- package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js.map +1 -1
- package/dist/storage/implementation/db.d.ts +9 -1
- package/dist/storage/implementation/db.js +28 -1
- package/dist/storage/implementation/db.js.map +1 -1
- package/dist/storage/implementation/models.d.ts +35 -0
- package/dist/storage/implementation/models.js.map +1 -1
- package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +11 -0
- package/dist/storage/implementation/v1/MongoBucketBatchV1.js +227 -221
- package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
- package/dist/storage/implementation/v1/MongoCompactorV1.d.ts +38 -6
- package/dist/storage/implementation/v1/MongoCompactorV1.js +247 -20
- package/dist/storage/implementation/v1/MongoCompactorV1.js.map +1 -1
- package/dist/storage/implementation/v1/MongoParameterCompactorV1.d.ts +16 -2
- package/dist/storage/implementation/v1/MongoParameterCompactorV1.js +20 -9
- package/dist/storage/implementation/v1/MongoParameterCompactorV1.js.map +1 -1
- package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.d.ts +18 -11
- package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js +66 -17
- package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js.map +1 -1
- package/dist/storage/implementation/v1/PersistedBatchV1.d.ts +7 -5
- package/dist/storage/implementation/v1/PersistedBatchV1.js +22 -28
- package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
- package/dist/storage/implementation/v1/models.js +1 -0
- package/dist/storage/implementation/v1/models.js.map +1 -1
- package/dist/storage/implementation/v3/CompactionLease.d.ts +50 -0
- package/dist/storage/implementation/v3/CompactionLease.js +131 -0
- package/dist/storage/implementation/v3/CompactionLease.js.map +1 -0
- package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +14 -2
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js +261 -194
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +83 -25
- package/dist/storage/implementation/v3/MongoCompactorV3.js +702 -159
- package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoParameterCompactorV3.d.ts +18 -0
- package/dist/storage/implementation/v3/MongoParameterCompactorV3.js +23 -0
- package/dist/storage/implementation/v3/MongoParameterCompactorV3.js.map +1 -0
- package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.d.ts +2 -15
- package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js +60 -92
- package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js.map +1 -1
- package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.d.ts +19 -9
- package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js +92 -32
- package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.d.ts +26 -0
- package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.js +82 -0
- package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.js.map +1 -0
- package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -8
- package/dist/storage/implementation/v3/PersistedBatchV3.js +77 -45
- package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.d.ts +12 -2
- package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js +42 -3
- package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js.map +1 -1
- package/dist/storage/implementation/v3/bucket-format.js +2 -0
- package/dist/storage/implementation/v3/bucket-format.js.map +1 -1
- package/dist/storage/implementation/v3/compact-utils.d.ts +108 -0
- package/dist/storage/implementation/v3/compact-utils.js +223 -0
- package/dist/storage/implementation/v3/compact-utils.js.map +1 -0
- package/dist/storage/implementation/v3/compaction-constants.d.ts +5 -0
- package/dist/storage/implementation/v3/compaction-constants.js +6 -0
- package/dist/storage/implementation/v3/compaction-constants.js.map +1 -0
- package/dist/storage/implementation/v3/models.d.ts +90 -6
- package/dist/storage/implementation/v3/models.js.map +1 -1
- package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.d.ts +7 -8
- package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.js +16 -5
- package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.js.map +1 -1
- package/dist/storage/implementation/v3/object-storage/ObjectStorage.d.ts +14 -11
- package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.d.ts +6 -8
- package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.js +17 -11
- package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.js.map +1 -1
- package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.d.ts +38 -0
- package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.js +164 -0
- package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.js.map +1 -0
- package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.d.ts +37 -12
- package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.js +197 -25
- package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.js.map +1 -1
- package/dist/storage/implementation/v3/source-table-utils.d.ts +15 -7
- package/dist/storage/implementation/v3/source-table-utils.js +49 -57
- package/dist/storage/implementation/v3/source-table-utils.js.map +1 -1
- package/dist/storage/storage-index.d.ts +2 -1
- package/dist/storage/storage-index.js +1 -0
- package/dist/storage/storage-index.js.map +1 -1
- package/dist/types/types.d.ts +28 -1
- package/dist/types/types.js +28 -7
- package/dist/types/types.js.map +1 -1
- package/dist/utils/test-utils.d.ts +4 -2
- package/dist/utils/test-utils.js +7 -4
- package/dist/utils/test-utils.js.map +1 -1
- package/dist/utils/util.js +3 -1
- package/dist/utils/util.js.map +1 -1
- package/package.json +10 -9
- package/src/storage/MongoBucketStorage.ts +545 -277
- package/src/storage/implementation/MongoBucketBatch.ts +258 -124
- package/src/storage/implementation/MongoCompactor.ts +37 -346
- package/src/storage/implementation/MongoIdSequence.ts +21 -1
- package/src/storage/implementation/MongoOpIdAllocator.ts +105 -0
- package/src/storage/implementation/MongoParameterCompactor.ts +388 -102
- package/src/storage/implementation/MongoParsedSyncConfigSet.ts +46 -1
- package/src/storage/implementation/MongoPersistedReplicationStream.ts +12 -4
- package/src/storage/implementation/MongoPersistedSyncConfigContent.ts +48 -29
- package/src/storage/implementation/MongoStorageProvider.ts +16 -4
- package/src/storage/implementation/MongoSyncBucketStorage.ts +133 -40
- package/src/storage/implementation/MongoSyncRulesLock.ts +78 -12
- package/src/storage/implementation/MongoWriteBatch.ts +172 -0
- package/src/storage/implementation/MongoWriteCheckpointAPI.ts +16 -46
- package/src/storage/implementation/SyncRuleStateUpdate.ts +13 -6
- package/src/storage/implementation/common/MongoSyncBucketStorageCheckpoint.ts +24 -2
- package/src/storage/implementation/common/PersistedBatch.ts +76 -20
- package/src/storage/implementation/common/VersionedPowerSyncMongoBase.ts +4 -0
- package/src/storage/implementation/db.ts +36 -2
- package/src/storage/implementation/models.ts +39 -0
- package/src/storage/implementation/v1/MongoBucketBatchV1.ts +272 -254
- package/src/storage/implementation/v1/MongoCompactorV1.ts +327 -40
- package/src/storage/implementation/v1/MongoParameterCompactorV1.ts +25 -9
- package/src/storage/implementation/v1/MongoSyncBucketStorageV1.ts +88 -28
- package/src/storage/implementation/v1/PersistedBatchV1.ts +25 -30
- package/src/storage/implementation/v1/models.ts +1 -0
- package/src/storage/implementation/v3/CompactionLease.ts +152 -0
- package/src/storage/implementation/v3/MongoBucketBatchV3.ts +339 -247
- package/src/storage/implementation/v3/MongoCompactorV3.ts +955 -225
- package/src/storage/implementation/v3/MongoParameterCompactorV3.ts +34 -0
- package/src/storage/implementation/v3/MongoStoppedSyncConfigCleanup.ts +100 -109
- package/src/storage/implementation/v3/MongoSyncBucketStorageV3.ts +112 -42
- package/src/storage/implementation/v3/MongoWriteCheckpointAPIV3.ts +111 -0
- package/src/storage/implementation/v3/PersistedBatchV3.ts +94 -51
- package/src/storage/implementation/v3/VersionedPowerSyncMongoV3.ts +55 -4
- package/src/storage/implementation/v3/bucket-format.ts +2 -0
- package/src/storage/implementation/v3/compact-utils.ts +329 -0
- package/src/storage/implementation/v3/compaction-constants.ts +5 -0
- package/src/storage/implementation/v3/models.ts +97 -4
- package/src/storage/implementation/v3/object-storage/BucketDataObjectStorage.ts +24 -9
- package/src/storage/implementation/v3/object-storage/ObjectStorage.ts +20 -5
- package/src/storage/implementation/v3/object-storage/ObjectStorageLifecycle.ts +26 -14
- package/src/storage/implementation/v3/object-storage/ObjectStorageUsage.ts +229 -0
- package/src/storage/implementation/v3/object-storage/S3ObjectStorage.ts +279 -29
- package/src/storage/implementation/v3/source-table-utils.ts +82 -76
- package/src/storage/storage-index.ts +2 -0
- package/src/types/types.ts +42 -7
- package/src/utils/test-utils.ts +9 -5
- package/src/utils/util.ts +3 -1
- package/test/src/__snapshots__/storage.test.ts.snap +25 -0
- package/test/src/__snapshots__/storage_sync.test.ts.snap +794 -205
- package/test/src/chunk_compaction_config.test.ts +38 -0
- package/test/src/cleanup-stopped-sync-configs.test.ts +59 -26
- package/test/src/compact-utils.test.ts +251 -0
- package/test/src/concurrent_writers.test.ts +599 -0
- package/test/src/connection_config.test.ts +159 -0
- package/test/src/helpers/MemoryObjectStorage.ts +14 -6
- package/test/src/helpers/concurrentWriter.mjs +29 -0
- package/test/src/helpers/s3TestFactory.ts +12 -12
- package/test/src/object_storage_usage.test.ts +268 -0
- package/test/src/parameter_compacting_v1.test.ts +120 -0
- package/test/src/parameter_compacting_v3.test.ts +192 -0
- package/test/src/parameter_compaction_fence.test.ts +276 -0
- package/test/src/storage.test.ts +280 -24
- package/test/src/storage_compacting.test.ts +1097 -253
- package/test/src/storage_object_storage_inline_threshold.test.ts +3 -3
- package/test/src/storage_s3_checksums.test.ts +6 -7
- package/test/src/storage_s3_compaction_lifecycle.test.ts +143 -17
- package/test/src/storage_s3_reading.test.ts +294 -6
- package/test/src/storage_s3_writing.test.ts +4 -3
- package/test/src/storage_sync.test.ts +412 -80
- package/test/src/storeCurrentData.test.ts +5 -5
- package/test/src/util.ts +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -1,64 +1,29 @@
|
|
|
1
1
|
import * as timers from 'node:timers/promises';
|
|
2
2
|
|
|
3
|
-
import { isMongoServerError, mongo
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
Logger,
|
|
7
|
-
ReplicationAssertionError,
|
|
8
|
-
ServiceAssertionError
|
|
9
|
-
} from '@powersync/lib-services-framework';
|
|
10
|
-
import { InternalOpId, isPartialChecksum, PopulateChecksumCacheResults, storage } from '@powersync/service-core';
|
|
11
|
-
import { BucketDefinitionId } from '@powersync/service-sync-rules';
|
|
3
|
+
import { isMongoServerError, mongo } from '@powersync/lib-service-mongodb';
|
|
4
|
+
import { logger as defaultLogger, Logger, ReplicationAssertionError } from '@powersync/lib-services-framework';
|
|
5
|
+
import { storage } from '@powersync/service-core';
|
|
12
6
|
|
|
13
7
|
import { BucketKey } from './common/BucketDataDoc.js';
|
|
14
8
|
import type { VersionedPowerSyncMongo } from './db.js';
|
|
15
|
-
import { BucketStateDocumentBase } from './models.js';
|
|
16
9
|
import type { MongoSyncBucketStorage } from './MongoSyncBucketStorage.js';
|
|
17
10
|
import { isRetryableObjectStorageError } from './v3/object-storage/ObjectStorage.js';
|
|
18
11
|
|
|
19
|
-
export interface
|
|
20
|
-
/** Bucket name */
|
|
21
|
-
bucket: string;
|
|
22
|
-
definitionId: BucketDefinitionId;
|
|
12
|
+
export interface MongoCompactOptions extends storage.CompactOptions {
|
|
23
13
|
/**
|
|
24
|
-
*
|
|
14
|
+
* Only merge adjacent V3 bucket-data chunks. This is used after initial
|
|
15
|
+
* replication, where reading every operation would defeat the purpose of
|
|
16
|
+
* the lightweight pass.
|
|
25
17
|
*/
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
|
|
29
|
-
*/
|
|
30
|
-
trackingSize: number;
|
|
31
|
-
/**
|
|
32
|
-
* Last (lowest) seen op_id that is not a PUT.
|
|
33
|
-
*/
|
|
34
|
-
lastNotPut: InternalOpId | null;
|
|
35
|
-
/**
|
|
36
|
-
* Number of REMOVE/MOVE operations seen since lastNotPut.
|
|
37
|
-
*/
|
|
38
|
-
opsSincePut: number;
|
|
39
|
-
/**
|
|
40
|
-
* Incrementally-updated checksum, up to maxOpId.
|
|
41
|
-
*/
|
|
42
|
-
checksum: number;
|
|
43
|
-
/**
|
|
44
|
-
* Op count for the checksum.
|
|
45
|
-
*/
|
|
46
|
-
opCount: number;
|
|
47
|
-
/**
|
|
48
|
-
* Byte size of ops covered by the checksum.
|
|
49
|
-
*/
|
|
50
|
-
opBytes: number;
|
|
18
|
+
compactChunksOnly?: boolean;
|
|
19
|
+
/** Internal/testing use: bypass the new-chunk threshold during chunk-only compaction. */
|
|
20
|
+
forceChunkCompaction?: boolean;
|
|
51
21
|
}
|
|
52
22
|
|
|
53
|
-
export interface MongoCompactOptions extends storage.CompactOptions {}
|
|
54
|
-
|
|
55
23
|
const DEFAULT_CLEAR_BATCH_LIMIT = 5000;
|
|
56
24
|
const DEFAULT_MOVE_BATCH_LIMIT = 2000;
|
|
57
25
|
const DEFAULT_MOVE_BATCH_QUERY_LIMIT = 10_000;
|
|
58
26
|
const DEFAULT_MOVE_BATCH_BYTE_LIMIT = 16 * 1024 * 1024;
|
|
59
|
-
const DEFAULT_MIN_BUCKET_CHANGES = 10;
|
|
60
|
-
const DEFAULT_MIN_CHANGE_RATIO = 0.1;
|
|
61
|
-
const DIRTY_BUCKET_SCAN_BATCH_SIZE = 2_000;
|
|
62
27
|
/** This default is primarily for tests. */
|
|
63
28
|
const DEFAULT_MEMORY_LIMIT_MB = 64;
|
|
64
29
|
const COMPACTION_RETRY_LIMIT = 3;
|
|
@@ -71,28 +36,30 @@ export class ConcurrentCompactionError extends Error {
|
|
|
71
36
|
}
|
|
72
37
|
}
|
|
73
38
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
39
|
+
/**
|
|
40
|
+
* A worker whose bucket lease has been replaced must stop immediately. Unlike
|
|
41
|
+
* a transactional replacement conflict, retrying it with the same compactor
|
|
42
|
+
* instance would still use the stale lease and could race the new owner.
|
|
43
|
+
*/
|
|
44
|
+
export class CompactionLeaseLostError extends ConcurrentCompactionError {
|
|
45
|
+
constructor(message: string) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = 'CompactionLeaseLostError';
|
|
48
|
+
}
|
|
79
49
|
}
|
|
80
50
|
|
|
81
51
|
export abstract class MongoCompactor {
|
|
82
|
-
protected bucketStateUpdates: mongo.AnyBulkWriteOperation<BucketStateDocumentBase>[] = [];
|
|
83
|
-
|
|
84
52
|
protected readonly idLimitBytes: number;
|
|
85
53
|
protected readonly moveBatchLimit: number;
|
|
86
54
|
protected readonly moveBatchQueryLimit: number;
|
|
87
55
|
protected readonly moveBatchByteLimit: number;
|
|
88
56
|
protected readonly clearBatchLimit: number;
|
|
89
|
-
protected readonly minBucketChanges: number;
|
|
90
|
-
protected readonly minChangeRatio: number;
|
|
91
|
-
protected readonly maxOpId: bigint;
|
|
92
57
|
protected readonly buckets: string[] | undefined;
|
|
93
58
|
protected readonly deleteCheckpointRequestsBefore: Date | undefined;
|
|
94
59
|
protected readonly signal?: AbortSignal;
|
|
95
60
|
protected readonly group_id: number;
|
|
61
|
+
protected readonly compactChunksOnly: boolean;
|
|
62
|
+
protected compactedBucketCount = 0;
|
|
96
63
|
|
|
97
64
|
protected readonly logger: Logger;
|
|
98
65
|
|
|
@@ -110,35 +77,16 @@ export abstract class MongoCompactor {
|
|
|
110
77
|
if (this.clearBatchLimit < 2) {
|
|
111
78
|
throw new ReplicationAssertionError('clearBatchLimit must be >= 2');
|
|
112
79
|
}
|
|
113
|
-
this.minBucketChanges = options.minBucketChanges ?? DEFAULT_MIN_BUCKET_CHANGES;
|
|
114
|
-
this.minChangeRatio = options.minChangeRatio ?? DEFAULT_MIN_CHANGE_RATIO;
|
|
115
|
-
this.maxOpId = options.maxOpId ?? 0n;
|
|
116
80
|
this.buckets = options.compactBuckets;
|
|
117
81
|
this.deleteCheckpointRequestsBefore = options.deleteCheckpointRequestsBefore;
|
|
118
82
|
this.signal = options.signal;
|
|
83
|
+
this.compactChunksOnly = options.compactChunksOnly ?? false;
|
|
119
84
|
this.logger = options.logger ?? defaultLogger;
|
|
120
85
|
}
|
|
121
86
|
|
|
122
|
-
|
|
123
|
-
* Compact buckets by converting operations into MOVE and/or CLEAR operations.
|
|
124
|
-
*
|
|
125
|
-
* See /docs/storage/compacting-operations.md for details.
|
|
126
|
-
*/
|
|
127
|
-
async compact() {
|
|
128
|
-
await this.deleteOldCheckpointRequests();
|
|
129
|
-
|
|
130
|
-
if (this.buckets) {
|
|
131
|
-
for (const bucket of this.buckets) {
|
|
132
|
-
// We can make this more efficient later on by iterating through the buckets in a single query.
|
|
133
|
-
// That makes batching more tricky, so we leave for later.
|
|
134
|
-
await this.compactSingleBucketRetried(bucket);
|
|
135
|
-
}
|
|
136
|
-
} else {
|
|
137
|
-
await this.compactDirtyBuckets();
|
|
138
|
-
}
|
|
139
|
-
}
|
|
87
|
+
abstract compact(): Promise<number>;
|
|
140
88
|
|
|
141
|
-
|
|
89
|
+
protected async deleteOldCheckpointRequests() {
|
|
142
90
|
if (this.deleteCheckpointRequestsBefore == null) {
|
|
143
91
|
return;
|
|
144
92
|
}
|
|
@@ -152,180 +100,17 @@ export abstract class MongoCompactor {
|
|
|
152
100
|
checkpoint_requested_at: { $exists: true, $lt: this.deleteCheckpointRequestsBefore },
|
|
153
101
|
processed_at_lsn: { $ne: null }
|
|
154
102
|
});
|
|
155
|
-
await this.
|
|
156
|
-
checkpoint_requested_at: { $exists: true, $lt: this.deleteCheckpointRequestsBefore }
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Subset of compact, only populating checksums where relevant.
|
|
162
|
-
*/
|
|
163
|
-
async populateChecksums(options: { minBucketChanges: number }): Promise<PopulateChecksumCacheResults> {
|
|
164
|
-
let count = 0;
|
|
165
|
-
// Paginate through dirty buckets in batches until no more buckets meet the criteria.
|
|
166
|
-
while (true) {
|
|
167
|
-
this.signal?.throwIfAborted();
|
|
168
|
-
const buckets = await this.dirtyBucketBatchForChecksums(options);
|
|
169
|
-
if (buckets.length == 0) {
|
|
170
|
-
break;
|
|
171
|
-
}
|
|
172
|
-
this.signal?.throwIfAborted();
|
|
173
|
-
|
|
174
|
-
const start = Date.now();
|
|
175
|
-
// Filter batch by estimated bucket size, to reduce possibility of timeouts.
|
|
176
|
-
const checkBuckets: typeof buckets = [];
|
|
177
|
-
let totalCountEstimate = 0;
|
|
178
|
-
for (const bucket of buckets) {
|
|
179
|
-
checkBuckets.push(bucket);
|
|
180
|
-
totalCountEstimate += bucket.estimatedCount;
|
|
181
|
-
if (totalCountEstimate > 50_000) {
|
|
182
|
-
break;
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
this.logger.info(
|
|
186
|
-
`Calculating checksums for batch of ${buckets.length} buckets, estimated count of ${totalCountEstimate}`
|
|
187
|
-
);
|
|
188
|
-
await this.updateChecksumsBatch(checkBuckets);
|
|
189
|
-
this.logger.info(`Updated checksums for batch of ${checkBuckets.length} buckets in ${Date.now() - start}ms`);
|
|
190
|
-
count += checkBuckets.length;
|
|
191
|
-
}
|
|
192
|
-
return { buckets: count };
|
|
103
|
+
await this.deleteOldCustomCheckpointRequests();
|
|
193
104
|
}
|
|
194
105
|
|
|
195
|
-
protected async
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
maxId: TCollectionBucketState['_id'],
|
|
199
|
-
options: {
|
|
200
|
-
minBucketChanges: number;
|
|
201
|
-
minChangeRatio: number;
|
|
202
|
-
},
|
|
203
|
-
getDefinitionId: (state: TCollectionBucketState) => BucketDefinitionId | null
|
|
204
|
-
): AsyncGenerator<DirtyBucket[]> {
|
|
205
|
-
// Paginate through the bucket state collection using cursor-based scanning.
|
|
206
|
-
while (true) {
|
|
207
|
-
// To avoid timeouts from too many buckets not meeting the minBucketChanges criteria, use an aggregation pipeline
|
|
208
|
-
// to scan a fixed batch of buckets at a time, but only return buckets that meet the criteria.
|
|
209
|
-
const [result] = await collection
|
|
210
|
-
.aggregate<{
|
|
211
|
-
buckets: TCollectionBucketState[];
|
|
212
|
-
cursor: Pick<TCollectionBucketState, '_id'>[];
|
|
213
|
-
}>(
|
|
214
|
-
[
|
|
215
|
-
{
|
|
216
|
-
$match: {
|
|
217
|
-
_id: { $gt: lastId, $lt: maxId }
|
|
218
|
-
}
|
|
219
|
-
},
|
|
220
|
-
{
|
|
221
|
-
$sort: { _id: 1 }
|
|
222
|
-
},
|
|
223
|
-
{
|
|
224
|
-
// Scan a fixed number of docs each query so sparse matches don't block progress.
|
|
225
|
-
$limit: DIRTY_BUCKET_SCAN_BATCH_SIZE
|
|
226
|
-
},
|
|
227
|
-
{
|
|
228
|
-
$facet: {
|
|
229
|
-
buckets: [
|
|
230
|
-
{
|
|
231
|
-
$match: {
|
|
232
|
-
'estimate_since_compact.count': { $gte: options.minBucketChanges }
|
|
233
|
-
}
|
|
234
|
-
},
|
|
235
|
-
{
|
|
236
|
-
$project: {
|
|
237
|
-
_id: 1,
|
|
238
|
-
estimate_since_compact: 1,
|
|
239
|
-
compacted_state: 1
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
],
|
|
243
|
-
// This is used for the next query.
|
|
244
|
-
cursor: [{ $sort: { _id: -1 } }, { $limit: 1 }, { $project: { _id: 1 } }]
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
],
|
|
248
|
-
{ maxTimeMS: MONGO_OPERATION_TIMEOUT_MS }
|
|
249
|
-
)
|
|
250
|
-
.toArray();
|
|
251
|
-
|
|
252
|
-
const cursor = result?.cursor?.[0];
|
|
253
|
-
if (cursor == null) {
|
|
254
|
-
break;
|
|
255
|
-
}
|
|
256
|
-
lastId = cursor._id;
|
|
257
|
-
|
|
258
|
-
const mapped = (result?.buckets ?? []).map((bucketState) => {
|
|
259
|
-
// The numbers, specifically the bytes, could be a bigint. Convert to Number to allow calculating ratios.
|
|
260
|
-
// BigInt precision is not needed here since this is only an estimate.
|
|
261
|
-
const updatedCount = bucketState.estimate_since_compact?.count ?? 0;
|
|
262
|
-
const totalCount = (bucketState.compacted_state?.count ?? 0) + updatedCount;
|
|
263
|
-
const updatedBytes = Number(bucketState.estimate_since_compact?.bytes ?? 0);
|
|
264
|
-
const totalBytes = Number(bucketState.compacted_state?.bytes ?? 0) + updatedBytes;
|
|
265
|
-
const dirtyChangeNumber = totalCount > 0 ? updatedCount / totalCount : 0;
|
|
266
|
-
const dirtyChangeBytes = totalBytes > 0 ? updatedBytes / totalBytes : 0;
|
|
267
|
-
return {
|
|
268
|
-
bucket: bucketState._id.b,
|
|
269
|
-
definitionId: getDefinitionId(bucketState),
|
|
270
|
-
estimatedCount: totalCount,
|
|
271
|
-
dirtyRatio: Math.max(dirtyChangeNumber, dirtyChangeBytes)
|
|
272
|
-
};
|
|
273
|
-
});
|
|
274
|
-
|
|
275
|
-
yield mapped.filter(
|
|
276
|
-
(bucket) => bucket.estimatedCount >= options.minBucketChanges && bucket.dirtyRatio >= options.minChangeRatio
|
|
277
|
-
);
|
|
106
|
+
protected async deleteOldCustomCheckpointRequests() {
|
|
107
|
+
if (this.deleteCheckpointRequestsBefore == null) {
|
|
108
|
+
return;
|
|
278
109
|
}
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
protected async dirtyBucketBatchForChecksumsForCollection<TBucketState extends BucketStateDocumentBase>(
|
|
282
|
-
collection: mongo.Collection<TBucketState>,
|
|
283
|
-
filter: mongo.Filter<TBucketState>,
|
|
284
|
-
getDefinitionId: (state: mongo.WithId<TBucketState>) => BucketDefinitionId | null
|
|
285
|
-
): Promise<DirtyBucket[]> {
|
|
286
|
-
const dirtyBuckets = await collection
|
|
287
|
-
.find(filter, {
|
|
288
|
-
projection: {
|
|
289
|
-
_id: 1,
|
|
290
|
-
estimate_since_compact: 1,
|
|
291
|
-
compacted_state: 1
|
|
292
|
-
},
|
|
293
|
-
sort: {
|
|
294
|
-
'estimate_since_compact.count': -1
|
|
295
|
-
},
|
|
296
|
-
limit: 200,
|
|
297
|
-
maxTimeMS: MONGO_OPERATION_TIMEOUT_MS
|
|
298
|
-
})
|
|
299
|
-
.toArray();
|
|
300
|
-
|
|
301
|
-
return dirtyBuckets.map((bucket) => ({
|
|
302
|
-
bucket: bucket._id.b,
|
|
303
|
-
definitionId: getDefinitionId(bucket),
|
|
304
|
-
estimatedCount: Number(bucket.estimate_since_compact!.count) + Number(bucket.compacted_state?.count ?? 0)
|
|
305
|
-
}));
|
|
306
|
-
}
|
|
307
110
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
}): AsyncGenerator<DirtyBucket[]>;
|
|
312
|
-
|
|
313
|
-
public abstract dirtyBucketBatchForChecksums(options: { minBucketChanges: number }): Promise<DirtyBucket[]>;
|
|
314
|
-
|
|
315
|
-
protected async compactDirtyBuckets() {
|
|
316
|
-
for await (const buckets of this.dirtyBucketBatches({
|
|
317
|
-
minBucketChanges: this.minBucketChanges,
|
|
318
|
-
minChangeRatio: this.minChangeRatio
|
|
319
|
-
})) {
|
|
320
|
-
this.signal?.throwIfAborted();
|
|
321
|
-
if (buckets.length == 0) {
|
|
322
|
-
continue;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
for (const { bucket, definitionId } of buckets) {
|
|
326
|
-
await this.compactSingleBucketRetried(bucket, definitionId);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
111
|
+
await this.db.custom_write_checkpoints.deleteMany({
|
|
112
|
+
checkpoint_requested_at: { $exists: true, $lt: this.deleteCheckpointRequestsBefore }
|
|
113
|
+
});
|
|
329
114
|
}
|
|
330
115
|
|
|
331
116
|
/**
|
|
@@ -336,14 +121,12 @@ export abstract class MongoCompactor {
|
|
|
336
121
|
* storage paths are also prepared with lifecycle markers, so a retry can
|
|
337
122
|
* safely overwrite or eventually clean up uploads from the failed attempt.
|
|
338
123
|
*/
|
|
339
|
-
protected async
|
|
124
|
+
protected async retryCompaction(bucket: string, compact: () => Promise<void>) {
|
|
340
125
|
let retryCount = 0;
|
|
341
126
|
while (true) {
|
|
342
127
|
this.signal?.throwIfAborted();
|
|
343
|
-
// Do not carry queued bucket state writes from a failed attempt into the rescan.
|
|
344
|
-
this.bucketStateUpdates = [];
|
|
345
128
|
try {
|
|
346
|
-
await
|
|
129
|
+
await compact();
|
|
347
130
|
return;
|
|
348
131
|
} catch (e) {
|
|
349
132
|
if (this.signal?.aborted) {
|
|
@@ -372,101 +155,6 @@ export abstract class MongoCompactor {
|
|
|
372
155
|
}
|
|
373
156
|
}
|
|
374
157
|
}
|
|
375
|
-
|
|
376
|
-
protected abstract compactSingleBucket(bucket: string, definitionId?: BucketDefinitionId | null): Promise<void>;
|
|
377
|
-
|
|
378
|
-
protected collectBucketStateUpdates(
|
|
379
|
-
state: CurrentBucketState,
|
|
380
|
-
compactedOpId: InternalOpId
|
|
381
|
-
): mongo.AnyBulkWriteOperation<BucketStateDocumentBase> {
|
|
382
|
-
if (state.opCount < 0) {
|
|
383
|
-
throw new ServiceAssertionError(
|
|
384
|
-
`Invalid opCount: ${state.opCount} checksum ${state.checksum} opsSincePut: ${state.opsSincePut} maxOpId: ${this.maxOpId}`
|
|
385
|
-
);
|
|
386
|
-
}
|
|
387
|
-
return {
|
|
388
|
-
updateOne: {
|
|
389
|
-
filter: this.bucketStateFilter(state.bucket, state.definitionId),
|
|
390
|
-
update: {
|
|
391
|
-
$set: {
|
|
392
|
-
compacted_state: {
|
|
393
|
-
op_id: compactedOpId,
|
|
394
|
-
count: state.opCount,
|
|
395
|
-
checksum: BigInt(state.checksum),
|
|
396
|
-
bytes: state.opBytes
|
|
397
|
-
},
|
|
398
|
-
estimate_since_compact: {
|
|
399
|
-
// There could have been a whole bunch of new operations added to the bucket while compacting,
|
|
400
|
-
// which we don't currently cater for. We could potentially query for that, but that adds overhead.
|
|
401
|
-
count: 0,
|
|
402
|
-
bytes: 0
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
} satisfies mongo.UpdateFilter<BucketStateDocumentBase>,
|
|
406
|
-
// We generally expect this to have been created before.
|
|
407
|
-
// We don't create new ones here, to avoid issues with the unique index on bucket_updates.
|
|
408
|
-
upsert: false
|
|
409
|
-
}
|
|
410
|
-
};
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
protected updateBucketChecksums(state: CurrentBucketState, compactedOpId: InternalOpId) {
|
|
414
|
-
this.bucketStateUpdates.push(this.collectBucketStateUpdates(state, compactedOpId));
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
protected async flushBucketStateUpdates() {
|
|
418
|
-
if (this.bucketStateUpdates.length > 0) {
|
|
419
|
-
this.logger.info(`Updating ${this.bucketStateUpdates.length} bucket states`);
|
|
420
|
-
await this.writeBucketStateUpdates();
|
|
421
|
-
this.bucketStateUpdates = [];
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
protected async updateChecksumsBatch(buckets: Pick<DirtyBucket, 'bucket' | 'definitionId'>[]) {
|
|
426
|
-
const checksums = await this.computeChecksumsForBuckets(buckets);
|
|
427
|
-
const definitionIdByBucket = new Map(buckets.map((bucket) => [bucket.bucket, bucket.definitionId]));
|
|
428
|
-
|
|
429
|
-
for (const bucketChecksum of checksums.values()) {
|
|
430
|
-
if (isPartialChecksum(bucketChecksum)) {
|
|
431
|
-
// Should never happen since we don't specify `start`.
|
|
432
|
-
throw new ServiceAssertionError(`Full checksum expected, got ${JSON.stringify(bucketChecksum)}`);
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
this.bucketStateUpdates.push({
|
|
436
|
-
updateOne: {
|
|
437
|
-
filter: this.bucketStateFilter(
|
|
438
|
-
bucketChecksum.bucket,
|
|
439
|
-
definitionIdByBucket.get(bucketChecksum.bucket) ?? null
|
|
440
|
-
),
|
|
441
|
-
update: {
|
|
442
|
-
$set: {
|
|
443
|
-
compacted_state: {
|
|
444
|
-
op_id: this.maxOpId,
|
|
445
|
-
count: bucketChecksum.count,
|
|
446
|
-
checksum: BigInt(bucketChecksum.checksum),
|
|
447
|
-
bytes: null
|
|
448
|
-
},
|
|
449
|
-
estimate_since_compact: {
|
|
450
|
-
count: 0,
|
|
451
|
-
bytes: 0
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
} satisfies mongo.UpdateFilter<BucketStateDocumentBase>,
|
|
455
|
-
// We don't create new ones here - it gets tricky to get the last_op right with the unique index on
|
|
456
|
-
// bucket_updates.
|
|
457
|
-
upsert: false
|
|
458
|
-
}
|
|
459
|
-
});
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
await this.flushBucketStateUpdates();
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
protected abstract writeBucketStateUpdates(): Promise<void>;
|
|
466
|
-
protected abstract computeChecksumsForBuckets(
|
|
467
|
-
buckets: Pick<DirtyBucket, 'bucket' | 'definitionId'>[]
|
|
468
|
-
): Promise<storage.PartialChecksumMap>;
|
|
469
|
-
protected abstract bucketStateFilter(bucket: string, definitionId: BucketDefinitionId | null): mongo.Document;
|
|
470
158
|
}
|
|
471
159
|
|
|
472
160
|
export interface BucketDataCollectionContext<TBucketData extends mongo.Document> {
|
|
@@ -475,6 +163,9 @@ export interface BucketDataCollectionContext<TBucketData extends mongo.Document>
|
|
|
475
163
|
}
|
|
476
164
|
|
|
477
165
|
function compactionRetryReason(error: unknown): string | null {
|
|
166
|
+
if (error instanceof CompactionLeaseLostError) {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
478
169
|
if (error instanceof ConcurrentCompactionError) {
|
|
479
170
|
return 'concurrent compaction';
|
|
480
171
|
}
|
|
@@ -9,7 +9,10 @@ import { ReplicationAssertionError } from '@powersync/lib-services-framework';
|
|
|
9
9
|
export class MongoIdSequence {
|
|
10
10
|
private _last: bigint;
|
|
11
11
|
|
|
12
|
-
constructor(
|
|
12
|
+
constructor(
|
|
13
|
+
last: bigint,
|
|
14
|
+
private readonly ranges?: readonly OpIdRange[]
|
|
15
|
+
) {
|
|
13
16
|
if (typeof last != 'bigint') {
|
|
14
17
|
throw new ReplicationAssertionError(`BigInt required, got ${last} ${typeof last}`);
|
|
15
18
|
}
|
|
@@ -17,6 +20,14 @@ export class MongoIdSequence {
|
|
|
17
20
|
}
|
|
18
21
|
|
|
19
22
|
next() {
|
|
23
|
+
if (this.ranges != null) {
|
|
24
|
+
const next = this.ranges.find((range) => range.end > this._last);
|
|
25
|
+
if (next == null) {
|
|
26
|
+
throw new OpIdRangeExhausted();
|
|
27
|
+
}
|
|
28
|
+
this._last = this._last + 1n < next.start ? next.start : this._last + 1n;
|
|
29
|
+
return this._last;
|
|
30
|
+
}
|
|
20
31
|
return ++this._last;
|
|
21
32
|
}
|
|
22
33
|
|
|
@@ -24,3 +35,12 @@ export class MongoIdSequence {
|
|
|
24
35
|
return this._last;
|
|
25
36
|
}
|
|
26
37
|
}
|
|
38
|
+
|
|
39
|
+
/** Inclusive, durably reserved operation IDs. Gaps between ranges are valid. */
|
|
40
|
+
export interface OpIdRange {
|
|
41
|
+
start: bigint;
|
|
42
|
+
end: bigint;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Abort the transaction before reserving more IDs and retrying its evaluation. */
|
|
46
|
+
export class OpIdRangeExhausted extends Error {}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { mongo } from '@powersync/lib-service-mongodb';
|
|
2
|
+
import { ReplicationAssertionError } from '@powersync/lib-services-framework';
|
|
3
|
+
import { VersionedPowerSyncMongo } from './db.js';
|
|
4
|
+
import { MongoIdSequence, OpIdRange } from './MongoIdSequence.js';
|
|
5
|
+
|
|
6
|
+
const RESERVATION_SIZE = 65_536n;
|
|
7
|
+
const LOW_WATER_MARK = 16_384n;
|
|
8
|
+
const MAX_OP_ID = (1n << 63n) - 1n;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Shared by writers of one stream and lease owner in this process. Reservations
|
|
12
|
+
* use short majority writes, never the publication session. A crashed owner
|
|
13
|
+
* abandons its unused ranges; the global sequence is an allocation watermark.
|
|
14
|
+
*/
|
|
15
|
+
export class MongoOpIdAllocator {
|
|
16
|
+
private ranges: OpIdRange[] = [];
|
|
17
|
+
private reserving?: Promise<void>;
|
|
18
|
+
|
|
19
|
+
constructor(private readonly db: VersionedPowerSyncMongo) {}
|
|
20
|
+
|
|
21
|
+
discard() {
|
|
22
|
+
this.ranges = [];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
sequence(persistedOp: bigint): MongoIdSequence {
|
|
26
|
+
// The stream is fenced before reading this head. Another writer may have
|
|
27
|
+
// committed since this allocator was last used, including in another process.
|
|
28
|
+
// Never reuse reserved IDs below that durable head.
|
|
29
|
+
return new MongoIdSequence(persistedOp, this.ranges.slice());
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
committed(lastOp: bigint) {
|
|
33
|
+
this.ranges = this.ranges
|
|
34
|
+
.filter((range) => range.end > lastOp)
|
|
35
|
+
.map((range) => ({ start: range.start > lastOp ? range.start : lastOp + 1n, end: range.end }));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Top up between transactions, retaining every unused ID in existing ranges. */
|
|
39
|
+
async ensureCapacity(): Promise<void> {
|
|
40
|
+
const remaining = this.ranges.reduce((total, range) => total + range.end - range.start + 1n, 0n);
|
|
41
|
+
if (remaining < LOW_WATER_MARK) {
|
|
42
|
+
await this.reserve();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async reserve(): Promise<void> {
|
|
47
|
+
if (this.reserving != null) {
|
|
48
|
+
return this.reserving;
|
|
49
|
+
}
|
|
50
|
+
this.reserving = this.reserveRange();
|
|
51
|
+
try {
|
|
52
|
+
await this.reserving;
|
|
53
|
+
} finally {
|
|
54
|
+
this.reserving = undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Atomically reserve a range of operation IDs in the global sequence.
|
|
60
|
+
*
|
|
61
|
+
* We continue using the range across multiple batches, until the range is exhausted,
|
|
62
|
+
* so we don't "waste" large segements in long-running processes with small batches.
|
|
63
|
+
* However, we can't return unused portions back to the database if we don't use them.
|
|
64
|
+
*/
|
|
65
|
+
private async reserveRange(): Promise<void> {
|
|
66
|
+
try {
|
|
67
|
+
// Return the previous watermark so an unchanged value at the limit can be
|
|
68
|
+
// distinguished from a successful reservation ending near the limit.
|
|
69
|
+
const previous = await this.db.op_id_sequence.findOneAndUpdate(
|
|
70
|
+
{ _id: 'main' },
|
|
71
|
+
[
|
|
72
|
+
{
|
|
73
|
+
$set: {
|
|
74
|
+
op_id: {
|
|
75
|
+
$let: {
|
|
76
|
+
vars: { current: { $ifNull: ['$op_id', 0n] } },
|
|
77
|
+
in: {
|
|
78
|
+
$cond: [
|
|
79
|
+
{ $lte: ['$$current', MAX_OP_ID - RESERVATION_SIZE] },
|
|
80
|
+
{ $add: ['$$current', RESERVATION_SIZE] },
|
|
81
|
+
'$$current'
|
|
82
|
+
]
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
],
|
|
89
|
+
{ upsert: true, returnDocument: 'before', writeConcern: { w: 'majority' } }
|
|
90
|
+
);
|
|
91
|
+
const last = previous?.op_id ?? 0n;
|
|
92
|
+
if (last > MAX_OP_ID - RESERVATION_SIZE) {
|
|
93
|
+
// Not expected to ever happen, unless the sequence was manually modified
|
|
94
|
+
throw new ReplicationAssertionError('Operation ID sequence exhausted');
|
|
95
|
+
}
|
|
96
|
+
this.ranges.push({ start: last + 1n, end: last + RESERVATION_SIZE });
|
|
97
|
+
} catch (error) {
|
|
98
|
+
// Concurrent first reservations may race to insert the sequence document - retry in that case.
|
|
99
|
+
if (error instanceof mongo.MongoServerError && error.code === 11000) {
|
|
100
|
+
return this.reserveRange();
|
|
101
|
+
}
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|