@powersync/service-module-mongodb-storage 0.26.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 +8 -0
- package/dist/storage/implementation/MongoBucketBatch.d.ts +5 -4
- package/dist/storage/implementation/MongoBucketBatch.js +5 -4
- package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
- package/dist/storage/implementation/MongoSyncRulesLock.js +5 -1
- package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
- package/dist/storage/implementation/common/PreparedPublication.d.ts +6 -2
- 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.js +19 -6
- 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 +1 -1
- package/dist/storage/implementation/v3/PersistedBatchV3.js +3 -3
- package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
- package/package.json +2 -2
- package/src/storage/implementation/MongoBucketBatch.ts +5 -4
- package/src/storage/implementation/MongoSyncRulesLock.ts +5 -1
- package/src/storage/implementation/common/PreparedPublication.ts +6 -2
- package/src/storage/implementation/v3/CompactionLease.ts +91 -15
- package/src/storage/implementation/v3/MongoBucketBatchV3.ts +23 -7
- package/src/storage/implementation/v3/MongoCompactorV3.ts +217 -127
- package/src/storage/implementation/v3/PersistedBatchV3.ts +4 -4
- package/test/src/concurrent_writers.test.ts +13 -0
- package/test/src/helpers/PublicationCommandMonitor.ts +18 -3
- package/test/src/prepared_publication.test.ts +23 -1
- package/test/src/replication_publication_baseline.test.ts +26 -16
- package/test/src/replication_publication_batching.test.ts +6 -2
- package/test/src/storage_compacting.test.ts +253 -47
- package/tsconfig.json +1 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { ReplicationAssertionError, ServiceAssertionError } from '@powersync/lib-services-framework';
|
|
2
2
|
import { acquireSemaphoreAbortable, addChecksums, formatBytes, utils } from '@powersync/service-core';
|
|
3
|
-
import { setImmediate } from 'node:timers/promises';
|
|
3
|
+
import { setImmediate, setTimeout } from 'node:timers/promises';
|
|
4
4
|
import { ConcurrentCompactionError, MongoCompactor } from '../MongoCompactor.js';
|
|
5
5
|
import { cacheKey } from '../OperationBatch.js';
|
|
6
6
|
import { loadBucketDataDocument, maxOpId, serializeBucketData } from './bucket-format.js';
|
|
7
7
|
import { BucketDataContextV3 } from './BucketDataContextV3.js';
|
|
8
8
|
import { DEFAULT_MAX_DOC_SIZE_BYTES } from './chunking.js';
|
|
9
|
-
import { applyStatsReplacement, bucketStats, chooseCompactionKind, chooseRequestedCompactionKind, combineAdjacentStats, combineChunkStats, CompactionContext, CompactionKind, emptyBucketStats, firstUncompactedWrite, readCompactionBatch, statsForDocument, statsForDocuments, unclaimedSnapshotFilter } from './compact-utils.js';
|
|
9
|
+
import { applyStatsReplacement, bucketStats, chooseCompactionKind, chooseRequestedCompactionKind, combineAdjacentStats, combineChunkStats, CompactionContext, CompactionKind, emptyBucketStats, firstUncompactedWrite, FULL_COMPACT_RESCHEDULE_MARGIN_MS, fullCompactionCheckAt, readCompactionBatch, statsForDocument, statsForDocuments, unclaimedSnapshotFilter } from './compact-utils.js';
|
|
10
10
|
import { DEFAULT_MIN_COMPACT_CHUNK_INTERVAL_MS } from './compaction-constants.js';
|
|
11
|
-
import { AVAILABLE_LEASE_EXPR, CompactionLease } from './CompactionLease.js';
|
|
11
|
+
import { AVAILABLE_LEASE_EXPR, CompactionLease, withBucketStateTransaction } from './CompactionLease.js';
|
|
12
12
|
import { BucketDataObjectStorage, hydrateBucketDataDocuments } from './object-storage/BucketDataObjectStorage.js';
|
|
13
13
|
import { ObjectStorageLifecycle } from './object-storage/ObjectStorageLifecycle.js';
|
|
14
14
|
import { createObjectStorageUsageWriterId, ObjectStorageUsage } from './object-storage/ObjectStorageUsage.js';
|
|
@@ -16,6 +16,8 @@ const DEFAULT_MIN_COMPACT_FULL_INTERVAL_MS = 2 * 60 * 60 * 1000;
|
|
|
16
16
|
const DEFAULT_MAX_COMPACT_FULL_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
17
17
|
const DEFAULT_COMPACT_LEASE_DURATION_MS = 10 * 60 * 1000;
|
|
18
18
|
const SCHEDULED_COMPACTION_BATCH_SIZE = 100;
|
|
19
|
+
const MIN_CHUNK_LEASE_GROUP_SIZE = 32;
|
|
20
|
+
const MAX_CHUNK_GROUP_PAUSE_MS = 50;
|
|
19
21
|
export class MongoCompactorV3 extends MongoCompactor {
|
|
20
22
|
minCompactChunkIntervalMs;
|
|
21
23
|
minCompactFullIntervalMs;
|
|
@@ -102,7 +104,8 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
102
104
|
continue;
|
|
103
105
|
}
|
|
104
106
|
const decision = chooseCompactionKind(lease.state, lease.startedAt, this);
|
|
105
|
-
await this.compactClaimedBucket(lease, CompactionKind.Full, decision);
|
|
107
|
+
const update = await this.compactClaimedBucket(lease, CompactionKind.Full, decision);
|
|
108
|
+
await this.publishSingleBucket(lease, update);
|
|
106
109
|
}
|
|
107
110
|
}
|
|
108
111
|
}
|
|
@@ -133,6 +136,7 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
133
136
|
const rescheduleNotBefore = new Date(dueBefore.getTime() + 1);
|
|
134
137
|
// Keep accounting documents bounded by workers, not buckets or scan batches.
|
|
135
138
|
const workerUsage = Array.from({ length: this.storage.factory.chunkCompactionConcurrency }, () => new ObjectStorageUsage(this.db, this.group_id, createObjectStorageUsageWriterId()));
|
|
139
|
+
const groupSize = Math.max(MIN_CHUNK_LEASE_GROUP_SIZE, workerUsage.length);
|
|
136
140
|
while (true) {
|
|
137
141
|
this.signal?.throwIfAborted();
|
|
138
142
|
const states = await this.findScheduledBucketBatch(dueBefore);
|
|
@@ -142,68 +146,142 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
142
146
|
// Keep eligibility bounded by dueBefore, but classify with the current
|
|
143
147
|
// server time so buckets that age into full compaction can advance.
|
|
144
148
|
const batchStartedAt = await this.readCompactionTime();
|
|
145
|
-
const
|
|
149
|
+
const noOpStates = [];
|
|
150
|
+
const chunkBuckets = [];
|
|
151
|
+
const sequentialBuckets = [];
|
|
146
152
|
for (const state of states) {
|
|
147
153
|
try {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
154
|
+
const decision = chooseCompactionKind(state, batchStartedAt, this);
|
|
155
|
+
const kind = requestedKind == null ? decision.kind : chooseRequestedCompactionKind(state, requestedKind, this);
|
|
156
|
+
// A due bucket may already cover this run's checkpoint. Reschedule
|
|
157
|
+
// from the snapshot unless an expired lease needs to be reclaimed.
|
|
158
|
+
if (state.compact_lease == null && (kind == null || this.isCompactionTargetCovered(state, kind))) {
|
|
159
|
+
noOpStates.push({ state, decision });
|
|
160
|
+
}
|
|
161
|
+
else if (kind === CompactionKind.Chunks) {
|
|
162
|
+
chunkBuckets.push(state);
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
sequentialBuckets.push(state);
|
|
166
|
+
}
|
|
153
167
|
}
|
|
154
168
|
catch (error) {
|
|
155
169
|
await this.rescheduleFailedBucket(state, rescheduleNotBefore, error);
|
|
156
170
|
}
|
|
157
171
|
}
|
|
158
|
-
const noOpStates = scheduled.filter(({ state, decision, selectedKind }) => state.compact_lease == null && (requestedKind == null ? decision.kind : selectedKind) == null);
|
|
159
172
|
await this.rescheduleUnclaimedBuckets(noOpStates, rescheduleNotBefore);
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
173
|
+
// One group can use every configured worker. Publish and release its
|
|
174
|
+
// leases before claiming the next group.
|
|
175
|
+
for (let i = 0; i < chunkBuckets.length; i += groupSize) {
|
|
176
|
+
await this.compactChunkGroup(chunkBuckets.slice(i, i + groupSize), workerUsage, dueBefore, requestedKind, rescheduleNotBefore);
|
|
177
|
+
// Give replication a window to update bucket state after releasing the group's leases.
|
|
178
|
+
await setTimeout(Math.random() * MAX_CHUNK_GROUP_PAUSE_MS, undefined, { signal: this.signal });
|
|
179
|
+
}
|
|
180
|
+
// Full compaction cannot overlap chunk workers from this job, and only
|
|
181
|
+
// one full bucket is processed at a time.
|
|
182
|
+
for (const state of sequentialBuckets) {
|
|
165
183
|
try {
|
|
184
|
+
this.signal?.throwIfAborted();
|
|
166
185
|
await using lease = await this.claimBucket({ _id: state._id, next_compact_check: { $lte: dueBefore } });
|
|
167
186
|
if (lease == null) {
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
const claimedDecision = chooseCompactionKind(lease.state, lease.startedAt, this);
|
|
171
|
-
const claimedKind = requestedKind == null
|
|
172
|
-
? claimedDecision.kind
|
|
173
|
-
: chooseRequestedCompactionKind(lease.state, requestedKind, this);
|
|
174
|
-
if (chunksOnly && claimedKind === CompactionKind.Full) {
|
|
175
|
-
// The decision changed after scanning. Release the lease without
|
|
176
|
-
// rescheduling; the next batch will classify it with a fresh timestamp.
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
if (claimedKind == null) {
|
|
180
|
-
await this.rescheduleClaimedBucket(lease, claimedDecision, rescheduleNotBefore);
|
|
187
|
+
continue;
|
|
181
188
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
await this.rescheduleClaimedBucket(lease, claimedDecision, rescheduleNotBefore);
|
|
186
|
-
}
|
|
187
|
-
else {
|
|
188
|
-
await this.compactClaimedBucket(lease, claimedKind, claimedDecision, rescheduleNotBefore, objectStorageUsage);
|
|
189
|
+
const update = await this.processScheduledLease(lease, requestedKind, rescheduleNotBefore, this.objectStorageUsage, false);
|
|
190
|
+
if (update != null) {
|
|
191
|
+
await this.publishSingleBucket(lease, update);
|
|
189
192
|
}
|
|
190
193
|
}
|
|
191
194
|
catch (error) {
|
|
192
195
|
if (this.signal?.aborted) {
|
|
193
|
-
// When aborted, stop completely, rather than logging and re-scheduling individual buckets.
|
|
194
|
-
// The lease on the current bucket is still released automatically.
|
|
195
196
|
throw error;
|
|
196
197
|
}
|
|
197
198
|
await this.rescheduleFailedBucket(state, rescheduleNotBefore, error);
|
|
198
199
|
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
async processScheduledLease(lease, requestedKind, rescheduleNotBefore, usage, chunksOnly) {
|
|
204
|
+
await lease.throwIfLost();
|
|
205
|
+
const decision = chooseCompactionKind(lease.state, lease.startedAt, this);
|
|
206
|
+
const kind = requestedKind == null ? decision.kind : chooseRequestedCompactionKind(lease.state, requestedKind, this);
|
|
207
|
+
if (chunksOnly && kind === CompactionKind.Full) {
|
|
208
|
+
// The decision changed after scanning. Release without rescheduling so
|
|
209
|
+
// the next batch can classify it with a fresh timestamp.
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (kind == null || this.isCompactionTargetCovered(lease.state, kind)) {
|
|
213
|
+
// The run cannot advance this kind's watermark. Keep any newer work scheduled.
|
|
214
|
+
return {
|
|
215
|
+
fields: { next_compact_check: this.rescheduleAtOrAfter(decision.nextCompactCheck, rescheduleNotBefore) }
|
|
199
216
|
};
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
217
|
+
}
|
|
218
|
+
return this.compactClaimedBucket(lease, kind, decision, rescheduleNotBefore, usage);
|
|
219
|
+
}
|
|
220
|
+
async publishSingleBucket(lease, update) {
|
|
221
|
+
await lease.finalize(update.fields);
|
|
222
|
+
if (update.completedMessage != null) {
|
|
223
|
+
this.compactedBucketCount++;
|
|
224
|
+
this.logger.info(update.completedMessage);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
async compactChunkGroup(states, workerUsage, dueBefore, requestedKind, rescheduleNotBefore) {
|
|
228
|
+
this.signal?.throwIfAborted();
|
|
229
|
+
await using owned = new AsyncDisposableStack();
|
|
230
|
+
// Each claim returns the state it actually acquired. Renew immediately,
|
|
231
|
+
// including while waiting for sibling claims, a worker slot, or publication.
|
|
232
|
+
const claims = await Promise.allSettled(states.map(async (state) => {
|
|
233
|
+
const lease = await this.claimBucket({ _id: state._id, next_compact_check: { $lte: dueBefore } });
|
|
234
|
+
return owned.use(lease);
|
|
235
|
+
}));
|
|
236
|
+
const leases = [];
|
|
237
|
+
for (const [i, claim] of claims.entries()) {
|
|
238
|
+
this.signal?.throwIfAborted();
|
|
239
|
+
if (claim.status === 'rejected') {
|
|
240
|
+
await this.rescheduleFailedBucket(states[i], rescheduleNotBefore, claim.reason);
|
|
241
|
+
}
|
|
242
|
+
else if (claim.value != null) {
|
|
243
|
+
leases.push(claim.value);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const updates = [];
|
|
247
|
+
try {
|
|
248
|
+
await this.runChunkCompactionWorkers(leases, workerUsage, async (lease, usage) => {
|
|
249
|
+
try {
|
|
250
|
+
const update = await this.processScheduledLease(lease, requestedKind, rescheduleNotBefore, usage, true);
|
|
251
|
+
await lease.throwIfLost();
|
|
252
|
+
if (update != null) {
|
|
253
|
+
updates.push({ lease, ...update });
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
if (this.signal?.aborted) {
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
// Release before the snapshot-conditional reschedule. Concurrent
|
|
261
|
+
// replication or takeover must be able to invalidate that update.
|
|
262
|
+
await lease[Symbol.asyncDispose]();
|
|
263
|
+
await this.rescheduleFailedBucket(lease.state, rescheduleNotBefore, error);
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
// Workers have drained, even on cancellation. Publish completed work
|
|
269
|
+
// before disposing unused leases.
|
|
270
|
+
const collection = this.db.bucketState(this.group_id);
|
|
271
|
+
const rescheduleFailed = (lease, error) => this.rescheduleFailedBucket(lease.state, rescheduleNotBefore, error);
|
|
272
|
+
const completed = updates.filter((update) => update.completedMessage != null);
|
|
273
|
+
const matched = await CompactionLease.finalizeBatch(collection, updates, rescheduleFailed);
|
|
274
|
+
// A partial match in a mixed batch only gives an upper bound on published compactions.
|
|
275
|
+
this.compactedBucketCount += Math.min(completed.length, matched);
|
|
276
|
+
if (matched === updates.length) {
|
|
277
|
+
for (const update of completed) {
|
|
278
|
+
this.logger.info(update.completedMessage);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
else {
|
|
282
|
+
// This happens when the job lost ownership of a bucket or MongoDB rejected an update.
|
|
283
|
+
// If this repeats, check for competing compaction jobs and earlier per-bucket errors.
|
|
284
|
+
this.logger.warn(`Published ${matched} of ${updates.length} compaction updates to bucket_state. Remaining work will be retried when due.`);
|
|
207
285
|
}
|
|
208
286
|
}
|
|
209
287
|
}
|
|
@@ -226,7 +304,7 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
226
304
|
// A worker takes another only after finishing its current bucket.
|
|
227
305
|
const bucket = buckets[nextBucket++];
|
|
228
306
|
// This pool bounds one job; the factory semaphore bounds all jobs together.
|
|
229
|
-
//
|
|
307
|
+
// The group owns its leases; only active chunk work needs a slot.
|
|
230
308
|
const acquired = await acquireSemaphoreAbortable(this.storage.factory.chunkCompactionSlots, signal);
|
|
231
309
|
if (acquired === 'aborted') {
|
|
232
310
|
signal?.throwIfAborted();
|
|
@@ -235,8 +313,9 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
235
313
|
const [, releaseSlot] = acquired;
|
|
236
314
|
try {
|
|
237
315
|
// A sibling may have failed while this worker waited for a slot.
|
|
238
|
-
if (failed)
|
|
316
|
+
if (failed) {
|
|
239
317
|
return;
|
|
318
|
+
}
|
|
240
319
|
signal?.throwIfAborted();
|
|
241
320
|
await processBucket(bucket, usage);
|
|
242
321
|
}
|
|
@@ -256,9 +335,7 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
256
335
|
// Concurrent transactions must not all increment the same usage document.
|
|
257
336
|
// Reuse one writer for each worker instead of creating one per bucket.
|
|
258
337
|
const workers = workerUsage.map(runWorker);
|
|
259
|
-
//
|
|
260
|
-
// sibling worker still owns a bucket lease or is finishing a replacement.
|
|
261
|
-
// Wait for every worker even on failure, then propagate the first error.
|
|
338
|
+
// Drain every sibling before releasing leases, including on failure.
|
|
262
339
|
const results = await Promise.allSettled(workers);
|
|
263
340
|
for (const result of results) {
|
|
264
341
|
if (result.status === 'rejected') {
|
|
@@ -288,12 +365,14 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
288
365
|
if (states.length == 0) {
|
|
289
366
|
return;
|
|
290
367
|
}
|
|
291
|
-
|
|
368
|
+
const collection = this.db.bucketState(this.group_id);
|
|
369
|
+
const operations = states.map(({ state, decision }) => ({
|
|
292
370
|
updateOne: {
|
|
293
371
|
filter: unclaimedSnapshotFilter(state),
|
|
294
372
|
update: [{ $set: { next_compact_check: this.rescheduleAtOrAfter(decision.nextCompactCheck, notBefore) } }]
|
|
295
373
|
}
|
|
296
|
-
}))
|
|
374
|
+
}));
|
|
375
|
+
await withBucketStateTransaction(collection, (session) => collection.bulkWrite(operations, { ordered: false, session }));
|
|
297
376
|
}
|
|
298
377
|
/**
|
|
299
378
|
* Isolate a malformed bucket so it cannot prevent other scheduled buckets
|
|
@@ -321,11 +400,7 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
321
400
|
}
|
|
322
401
|
async compactClaimedBucket(lease, kind, decision, rescheduleNotBefore, objectStorageUsage = this.objectStorageUsage) {
|
|
323
402
|
const context = new CompactionContext(lease, kind, decision, rescheduleNotBefore, this.compactionTarget(lease.state));
|
|
324
|
-
|
|
325
|
-
await this.compactSingleBucket(context, objectStorageUsage);
|
|
326
|
-
}
|
|
327
|
-
async rescheduleClaimedBucket(lease, decision, notBefore) {
|
|
328
|
-
await lease.reschedule(this.rescheduleAtOrAfter(decision.nextCompactCheck, notBefore));
|
|
403
|
+
return this.compactSingleBucket(context, objectStorageUsage);
|
|
329
404
|
}
|
|
330
405
|
rescheduleAtOrAfter(nextCompactCheck, notBefore) {
|
|
331
406
|
return notBefore == null ? nextCompactCheck : { $max: [nextCompactCheck, notBefore] };
|
|
@@ -461,8 +536,7 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
461
536
|
compactedTail = combineAdjacentStats(compactedTail, groupStats);
|
|
462
537
|
}
|
|
463
538
|
if (compactedOpId == null) {
|
|
464
|
-
|
|
465
|
-
return;
|
|
539
|
+
return this.skippedBucketUpdate(context);
|
|
466
540
|
}
|
|
467
541
|
const compactedState = previousCompactedState == null
|
|
468
542
|
? compactedTail
|
|
@@ -474,9 +548,10 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
474
548
|
compactedState,
|
|
475
549
|
bucketStats: tailStats == null ? compactedState : combineAdjacentStats(compactedState, tailStats)
|
|
476
550
|
};
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
551
|
+
return {
|
|
552
|
+
fields: this.compactedBucketFields({ context, compactedOpId, compactionResult: result, puts: 0 }),
|
|
553
|
+
completedMessage: `Compacted bucket chunks ${bucket}: ${result.bucketStats.count} ops, ${result.bucketStats.chunks} chunks, ${formatBytes(result.bucketStats.bytes)}`
|
|
554
|
+
};
|
|
480
555
|
}
|
|
481
556
|
async flushChunkMerge(bucket, inputs, collection, context, bucketContext, objectStorageUsage) {
|
|
482
557
|
if (inputs.length == 1 && !this.shouldMoveToObjectStorage(inputs[0])) {
|
|
@@ -517,8 +592,7 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
517
592
|
await setImmediate();
|
|
518
593
|
}
|
|
519
594
|
}
|
|
520
|
-
|
|
521
|
-
await context.lease.throwIfLost();
|
|
595
|
+
compactedBucketFields({ context, compactedOpId, compactionResult, puts }) {
|
|
522
596
|
const startedStats = bucketStats(context.state);
|
|
523
597
|
const delta = {
|
|
524
598
|
count: compactionResult.bucketStats.count - startedStats.count,
|
|
@@ -529,12 +603,24 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
529
603
|
const concurrentWriteCheck = { $gt: ['$last_op', context.lastOp] };
|
|
530
604
|
const remainingFullWorkCheck = coveredClaimedHead ? concurrentWriteCheck : true;
|
|
531
605
|
const nextAfterPartialFullCompact = this.rescheduleAtOrAfter({ $dateAdd: { startDate: '$$NOW', unit: 'millisecond', amount: this.minCompactChunkIntervalMs } }, context.rescheduleNotBefore);
|
|
532
|
-
|
|
606
|
+
let nextChunkCheck = {
|
|
533
607
|
$min: [
|
|
534
608
|
new Date(firstUncompactedWrite(context.state).getTime() + this.maxCompactFullIntervalMs),
|
|
535
609
|
{ $dateAdd: { startDate: '$$NOW', unit: 'millisecond', amount: this.minCompactChunkIntervalMs } }
|
|
536
610
|
]
|
|
537
|
-
}
|
|
611
|
+
};
|
|
612
|
+
if (context.kind === CompactionKind.Chunks && coveredClaimedHead) {
|
|
613
|
+
// If the head still matches at finalization, every chunk is covered.
|
|
614
|
+
// A later replication write will bring the check forward again.
|
|
615
|
+
const fullCheckAt = fullCompactionCheckAt({ ...context.state, bucket_stats: compactionResult.bucketStats }, this);
|
|
616
|
+
nextChunkCheck = {
|
|
617
|
+
$cond: [
|
|
618
|
+
{ $eq: ['$last_op', context.lastOp] },
|
|
619
|
+
new Date(fullCheckAt.getTime() + FULL_COMPACT_RESCHEDULE_MARGIN_MS),
|
|
620
|
+
nextChunkCheck
|
|
621
|
+
]
|
|
622
|
+
};
|
|
623
|
+
}
|
|
538
624
|
const update = {
|
|
539
625
|
compacted_state: {
|
|
540
626
|
op_id: compactedOpId,
|
|
@@ -554,7 +640,7 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
554
640
|
: '$first_uncompacted_write',
|
|
555
641
|
next_compact_check: context.kind == CompactionKind.Full
|
|
556
642
|
? { $cond: [remainingFullWorkCheck, nextAfterPartialFullCompact, '$$REMOVE'] }
|
|
557
|
-
:
|
|
643
|
+
: this.rescheduleAtOrAfter(nextChunkCheck, context.rescheduleNotBefore)
|
|
558
644
|
};
|
|
559
645
|
if (context.kind == CompactionKind.Full) {
|
|
560
646
|
update.last_full_compact = {
|
|
@@ -564,20 +650,21 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
564
650
|
at: '$$NOW'
|
|
565
651
|
};
|
|
566
652
|
}
|
|
567
|
-
|
|
653
|
+
return update;
|
|
568
654
|
}
|
|
569
|
-
|
|
655
|
+
skippedBucketUpdate(context) {
|
|
570
656
|
// A maxOpId cap can exclude the first remaining document entirely. Avoid
|
|
571
657
|
// immediately claiming the same no-progress bucket again in this run.
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
658
|
+
return {
|
|
659
|
+
fields: {
|
|
660
|
+
next_compact_check: this.rescheduleAtOrAfter({
|
|
661
|
+
$max: [
|
|
662
|
+
context.decision.nextCompactCheck,
|
|
663
|
+
{ $dateAdd: { startDate: '$$NOW', unit: 'millisecond', amount: this.minCompactChunkIntervalMs } }
|
|
664
|
+
]
|
|
665
|
+
}, context.rescheduleNotBefore)
|
|
579
666
|
}
|
|
580
|
-
}
|
|
667
|
+
};
|
|
581
668
|
}
|
|
582
669
|
/**
|
|
583
670
|
* Read bucket stats directly from bucket_data documents.
|
|
@@ -798,8 +885,7 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
798
885
|
}
|
|
799
886
|
}
|
|
800
887
|
if (compactedOpId == null) {
|
|
801
|
-
|
|
802
|
-
return;
|
|
888
|
+
return this.skippedBucketUpdate(context);
|
|
803
889
|
}
|
|
804
890
|
// --- Clear: collapse leading MOVE/REMOVE/CLEAR sequence ---
|
|
805
891
|
if (lastNotPut != null && opsSincePut >= 2) {
|
|
@@ -818,9 +904,10 @@ export class MongoCompactorV3 extends MongoCompactor {
|
|
|
818
904
|
bucketStats: tailStats == null ? compactedStats : combineAdjacentStats(compactedStats, tailStats)
|
|
819
905
|
};
|
|
820
906
|
// --- Finalize: update bucket checksums and state ---
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
907
|
+
return {
|
|
908
|
+
fields: this.compactedBucketFields({ context, compactedOpId, compactionResult: result, puts: putCount }),
|
|
909
|
+
completedMessage: `Compacted bucket ${bucket}: ${totalOpCount} ops, ${result.bucketStats.chunks} chunks, ${formatBytes(result.bucketStats.bytes)}`
|
|
910
|
+
};
|
|
824
911
|
}
|
|
825
912
|
/**
|
|
826
913
|
* Persist replacement objects before starting the transaction, then atomically
|