@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
|
@@ -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
|
|
|
@@ -1,10 +1,41 @@
|
|
|
1
1
|
import { mongo } from '@powersync/lib-service-mongodb';
|
|
2
2
|
import { InternalOpId } from '@powersync/service-core';
|
|
3
|
+
import { setTimeout } from 'node:timers/promises';
|
|
3
4
|
import { CompactionLeaseLostError } from '../MongoCompactor.js';
|
|
4
5
|
import { BucketStateDocumentV3 } from './models.js';
|
|
5
6
|
|
|
6
7
|
const LEASE_RENEW_INTERVAL_MS = 60 * 1000;
|
|
7
8
|
|
|
9
|
+
/**
|
|
10
|
+
* We wrap bulk bucket_state updates in a transaction.
|
|
11
|
+
*
|
|
12
|
+
* This is not needed for consistency purposes. Instead, we use this to deprioritize these updates
|
|
13
|
+
* against replication bucket_state updates. If we update concurrently with replication with individual
|
|
14
|
+
* operations, each operation can race the replication transaction individually, and any operation
|
|
15
|
+
* winning can abort the replication transaction. While if we combine it into a transaction, it gives
|
|
16
|
+
* the replication transaction a fair chance to compete.
|
|
17
|
+
*/
|
|
18
|
+
export function withBucketStateTransaction<T>(
|
|
19
|
+
collection: mongo.Collection<BucketStateDocumentV3>,
|
|
20
|
+
write: (session: mongo.ClientSession) => Promise<T>
|
|
21
|
+
): Promise<T> {
|
|
22
|
+
return collection.db.client.withSession((session) => {
|
|
23
|
+
let retry = false;
|
|
24
|
+
return session.withTransaction(
|
|
25
|
+
async () => {
|
|
26
|
+
// After a write conflict, give replication time to finish before retrying.
|
|
27
|
+
// The first MongoDB command opens the transaction on the server.
|
|
28
|
+
if (retry) {
|
|
29
|
+
await setTimeout(Math.random() * 150);
|
|
30
|
+
}
|
|
31
|
+
retry = true;
|
|
32
|
+
return write(session);
|
|
33
|
+
},
|
|
34
|
+
{ readPreference: 'primary', readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' } }
|
|
35
|
+
);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
8
39
|
/**
|
|
9
40
|
* Filters for buckets that have no lease or an expired lease.
|
|
10
41
|
*/
|
|
@@ -42,6 +73,7 @@ export class CompactionLease implements AsyncDisposable {
|
|
|
42
73
|
) {
|
|
43
74
|
this.startedAt = new Date(state.compact_lease!.expires_at.getTime() - durationMs);
|
|
44
75
|
this.lastOp = state.last_op;
|
|
76
|
+
this.startRenewal();
|
|
45
77
|
}
|
|
46
78
|
|
|
47
79
|
static async claim(
|
|
@@ -70,7 +102,7 @@ export class CompactionLease implements AsyncDisposable {
|
|
|
70
102
|
return state == null ? null : new CompactionLease(collection, state, id, durationMs);
|
|
71
103
|
}
|
|
72
104
|
|
|
73
|
-
startRenewal() {
|
|
105
|
+
private startRenewal() {
|
|
74
106
|
const interval = Math.max(1, Math.min(LEASE_RENEW_INTERVAL_MS, Math.floor(this.durationMs / 2)));
|
|
75
107
|
this.timer = setInterval(() => {
|
|
76
108
|
if (this.renewalInFlight) {
|
|
@@ -94,12 +126,66 @@ export class CompactionLease implements AsyncDisposable {
|
|
|
94
126
|
}
|
|
95
127
|
}
|
|
96
128
|
|
|
97
|
-
async
|
|
98
|
-
await this.
|
|
129
|
+
async finalize(fields: mongo.Document) {
|
|
130
|
+
await this.throwIfLost();
|
|
131
|
+
this.finalizing = true;
|
|
132
|
+
const result = await this.collection.updateOne(this.filter, [{ $set: fields }, { $unset: 'compact_lease' }]);
|
|
133
|
+
if (result.matchedCount != 1) {
|
|
134
|
+
throw new CompactionLeaseLostError(`Lost compaction lease for bucket ${this.state._id.b}`);
|
|
135
|
+
}
|
|
136
|
+
this.finished = true;
|
|
99
137
|
}
|
|
100
138
|
|
|
101
|
-
|
|
102
|
-
|
|
139
|
+
/** Each update publishes and releases only the lease that produced it. */
|
|
140
|
+
static async finalizeBatch(
|
|
141
|
+
collection: mongo.Collection<BucketStateDocumentV3>,
|
|
142
|
+
updates: readonly { lease: CompactionLease; fields: mongo.Document }[],
|
|
143
|
+
rescheduleFailed: (lease: CompactionLease, error: unknown) => Promise<void>
|
|
144
|
+
): Promise<number> {
|
|
145
|
+
if (updates.length === 0) {
|
|
146
|
+
return 0;
|
|
147
|
+
}
|
|
148
|
+
for (const { lease } of updates) {
|
|
149
|
+
lease.finalizing = true;
|
|
150
|
+
}
|
|
151
|
+
let pending = updates;
|
|
152
|
+
while (pending.length > 0) {
|
|
153
|
+
const operations = pending.map(({ lease, fields }) => ({
|
|
154
|
+
updateOne: { filter: lease.filter, update: [{ $set: fields }, { $unset: 'compact_lease' }] }
|
|
155
|
+
}));
|
|
156
|
+
try {
|
|
157
|
+
const result = await withBucketStateTransaction(collection, (session) =>
|
|
158
|
+
collection.bulkWrite(operations, { ordered: false, session })
|
|
159
|
+
);
|
|
160
|
+
// A miss means another worker owns the bucket. Any remaining leases
|
|
161
|
+
// still owned by this run are released by disposal if publication throws.
|
|
162
|
+
for (const { lease } of pending) {
|
|
163
|
+
lease.finished = true;
|
|
164
|
+
}
|
|
165
|
+
return result.matchedCount;
|
|
166
|
+
} catch (error) {
|
|
167
|
+
// A rejected update aborts the transaction. Retry the siblings only
|
|
168
|
+
// when the server identified the invalid updates and the abort is known.
|
|
169
|
+
if (
|
|
170
|
+
!(error instanceof mongo.MongoBulkWriteError) ||
|
|
171
|
+
error.hasErrorLabel('TransientTransactionError') ||
|
|
172
|
+
!Array.isArray(error.writeErrors) ||
|
|
173
|
+
error.writeErrors.length === 0 ||
|
|
174
|
+
error.result.getWriteConcernError() != null
|
|
175
|
+
) {
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
const failed = new Set<number>();
|
|
179
|
+
for (const writeError of error.writeErrors) {
|
|
180
|
+
const { lease } = pending[writeError.index];
|
|
181
|
+
failed.add(writeError.index);
|
|
182
|
+
await lease[Symbol.asyncDispose]();
|
|
183
|
+
await rescheduleFailed(lease, writeError);
|
|
184
|
+
}
|
|
185
|
+
pending = pending.filter((_, index) => !failed.has(index));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return 0;
|
|
103
189
|
}
|
|
104
190
|
|
|
105
191
|
async [Symbol.asyncDispose]() {
|
|
@@ -139,14 +225,4 @@ export class CompactionLease implements AsyncDisposable {
|
|
|
139
225
|
this.renewalError = undefined;
|
|
140
226
|
}
|
|
141
227
|
}
|
|
142
|
-
|
|
143
|
-
private async finish(update: mongo.Document[]) {
|
|
144
|
-
await this.throwIfLost();
|
|
145
|
-
this.finalizing = true;
|
|
146
|
-
const result = await this.collection.updateOne(this.filter, update);
|
|
147
|
-
if (result.matchedCount != 1) {
|
|
148
|
-
throw new CompactionLeaseLostError(`Lost compaction lease for bucket ${this.state._id.b}`);
|
|
149
|
-
}
|
|
150
|
-
this.finished = true;
|
|
151
|
-
}
|
|
152
228
|
}
|