@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
|
@@ -7,12 +7,20 @@ import { canCheckpointState } from '../CheckpointState.js';
|
|
|
7
7
|
import { MongoBucketBatch } from '../MongoBucketBatch.js';
|
|
8
8
|
import { OpIdRangeExhausted } from '../MongoIdSequence.js';
|
|
9
9
|
import { OperationBatch } from '../OperationBatch.js';
|
|
10
|
+
import { RETAINED_BYTES_FACTOR } from '../ReplicationBatchLimits.js';
|
|
10
11
|
import { stopReplicationStreamPipeline } from '../SyncRuleStateUpdate.js';
|
|
11
12
|
import { PersistedBatchV3 } from './PersistedBatchV3.js';
|
|
13
|
+
import { ReplicationPipelineV3 } from './ReplicationPipelineV3.js';
|
|
12
14
|
import { SourceRecordStoreV3 } from './SourceRecordStoreV3.js';
|
|
13
15
|
import { createNewSourceTable, overlappingSourceTableFilter, planSourceTableReconciliation, sourceTableDesiredResolution, sourceTableFromDocument } from './source-table-utils.js';
|
|
14
16
|
export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
15
17
|
store;
|
|
18
|
+
pipeline;
|
|
19
|
+
enqueuePublication = false;
|
|
20
|
+
pendingPublications = 0;
|
|
21
|
+
pendingInputs = 0;
|
|
22
|
+
/** Owned by the current mutex operation; saves only append to this.batch. */
|
|
23
|
+
capturedInput = null;
|
|
16
24
|
/** Avoid repeating idempotent createIndexes calls for every checkpoint flush. */
|
|
17
25
|
initializedCustomCheckpointEventIds = new Set();
|
|
18
26
|
// Used only to validate supplied checkpoint ids; it does not initialize collections.
|
|
@@ -22,6 +30,7 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
22
30
|
lastWaitingLogThrottledV3 = 0;
|
|
23
31
|
constructor(options) {
|
|
24
32
|
super(options);
|
|
33
|
+
this.pipeline = options.replicationLock.replicationPipeline ??= new ReplicationPipelineV3(options.replicationLock, options.opIdAllocator, options.batchLimits);
|
|
25
34
|
const syncConfigIds = options.syncConfigIds ?? [];
|
|
26
35
|
if (syncConfigIds.length == 0) {
|
|
27
36
|
throw new ReplicationAssertionError('Missing sync config id for v3 batch');
|
|
@@ -29,10 +38,157 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
29
38
|
this.syncConfigIds = syncConfigIds;
|
|
30
39
|
this.knownEventIds = new Set(this.mapping.allEventDefinitionIds());
|
|
31
40
|
this.store = new SourceRecordStoreV3(this.db, this.replicationStreamId, this.mapping);
|
|
41
|
+
this.pipeline.registerWriter(this);
|
|
42
|
+
}
|
|
43
|
+
getTableEvents(table) {
|
|
44
|
+
// V3 storage assigns event-definition ids to each source table, so membership is authoritative.
|
|
45
|
+
// Iterate the table's distinct ids and resolve each through the stream's deduped event map, so a
|
|
46
|
+
// definition reused across configs has one evaluator for that id. The evaluator may still return
|
|
47
|
+
// multiple payloads from matching queries.
|
|
48
|
+
const ids = table.eventDefinitionIds;
|
|
49
|
+
if (ids == null) {
|
|
50
|
+
throw new ReplicationAssertionError('Expected assigned event-definition ids for a v3 source table');
|
|
51
|
+
}
|
|
52
|
+
const eventById = this.options.parsedSyncConfig.eventById;
|
|
53
|
+
const events = [];
|
|
54
|
+
for (const id of ids) {
|
|
55
|
+
const event = eventById.get(id);
|
|
56
|
+
if (event != null && event.tableTriggersEvent(table.ref)) {
|
|
57
|
+
events.push({ event, eventId: id });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return events;
|
|
61
|
+
}
|
|
62
|
+
async save(record) {
|
|
63
|
+
try {
|
|
64
|
+
this.options.replicationLock.throwIfAborted();
|
|
65
|
+
// No await or mutex is needed to append an input event. Flushes detach their
|
|
66
|
+
// input before yielding, so preparation never reads this mutable buffer.
|
|
67
|
+
// A full buffer still waits for preparation capacity, bounding read-ahead.
|
|
68
|
+
if (this.bufferRecord(record)) {
|
|
69
|
+
return await this.automaticFlush();
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
this.pipeline.fail(error);
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async commit(lsn, options) {
|
|
79
|
+
this.options.replicationLock.throwIfAborted();
|
|
80
|
+
if (this.markRecordUnavailable != null && (this.batch?.length ?? 0) > 0) {
|
|
81
|
+
// A combined data+checkpoint commit cannot return control to the connector
|
|
82
|
+
// to process repair notifications between those two durable boundaries.
|
|
83
|
+
// Require its explicit flush -> repair -> commit ordering even when this
|
|
84
|
+
// particular input might turn out not to need repair. An empty batch does
|
|
85
|
+
// not prove its external repair queue is drained; that remains the caller's
|
|
86
|
+
// responsibility. keepalive() delegates here and has the same requirement.
|
|
87
|
+
throw new ReplicationAssertionError('Flush pending rows and process markRecordUnavailable repairs before committing source progress');
|
|
88
|
+
}
|
|
89
|
+
// Reject invalid repair ordering before detaching input, so the connector
|
|
90
|
+
// can still flush, repair, and retry its commit on this writer.
|
|
91
|
+
return this.withWriterLock(() => this.commitInternal(lsn, options), false);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Capture this writer's rows/checkpoints and queue preparation under writerMutex.
|
|
95
|
+
* Capture and enqueue happen before yielding, establishing the input's place
|
|
96
|
+
* relative to metadata barriers. Wait for preparation/admission, not necessarily
|
|
97
|
+
* publication. Repairs retain their synchronous flush path.
|
|
98
|
+
*/
|
|
99
|
+
async flushBufferedInputToPipeline() {
|
|
100
|
+
if (!this.batch?.hasData()) {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
return this.withCapturedInputLock(this.takeBufferedInput(), () => this.flushInternal(), true);
|
|
104
|
+
}
|
|
105
|
+
async automaticFlush() {
|
|
106
|
+
return this.flushBufferedInputToPipeline();
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Metadata operations capture all live writers before changing shared table state.
|
|
110
|
+
* Explicit flush/commit pass false: they drain admitted work and flush their own
|
|
111
|
+
* input in the callback, without forcing other writers' partial buffers to publish.
|
|
112
|
+
*/
|
|
113
|
+
withWriterLock(callback, flushAllWriters = true) {
|
|
114
|
+
// Queue all captured inputs before queueing the metadata operation itself.
|
|
115
|
+
// Saves after this synchronous boundary use fresh buffers and queue behind it.
|
|
116
|
+
if (flushAllWriters) {
|
|
117
|
+
this.pipeline.enqueueBufferedInputs();
|
|
118
|
+
}
|
|
119
|
+
return this.withCapturedInputLock(this.takeBufferedInput(), async () => {
|
|
120
|
+
await this.pipeline.drain();
|
|
121
|
+
return callback();
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
takeBufferedInput() {
|
|
125
|
+
const input = this.batch;
|
|
126
|
+
this.batch = null;
|
|
127
|
+
return input;
|
|
128
|
+
}
|
|
129
|
+
/** Only captured batches and metadata operations acquire/trace the writer lock. */
|
|
130
|
+
async withCapturedInputLock(input, callback, enqueuePublication = false) {
|
|
131
|
+
const hasInput = input?.hasData() ?? false;
|
|
132
|
+
if (hasInput) {
|
|
133
|
+
this.pendingInputs++;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
using lockSpan = this.tracer.span('storage', 'internal_lock');
|
|
137
|
+
this.options.replicationLock.throwIfAborted();
|
|
138
|
+
return await this.options.replicationLock.writerMutex.exclusiveLock(async () => {
|
|
139
|
+
lockSpan.end();
|
|
140
|
+
this.options.replicationLock.throwIfAborted();
|
|
141
|
+
this.capturedInput = input;
|
|
142
|
+
this.enqueuePublication = enqueuePublication;
|
|
143
|
+
try {
|
|
144
|
+
return await callback();
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
this.capturedInput = null;
|
|
148
|
+
this.enqueuePublication = false;
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
// A captured input must never disappear after failure while other writers
|
|
154
|
+
// continue advancing source progress. Replay it under a fresh lease. An
|
|
155
|
+
// input-free metadata rejection can be retried, e.g. snapshot completion
|
|
156
|
+
// rejected because a table still needs snapshotting.
|
|
157
|
+
if (hasInput) {
|
|
158
|
+
this.pipeline.fail(error);
|
|
159
|
+
}
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
if (hasInput) {
|
|
164
|
+
this.pendingInputs--;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async [Symbol.asyncDispose]() {
|
|
169
|
+
const pending = this.pendingInputs > 0 || this.pendingPublications > 0 || this.batch?.hasData();
|
|
170
|
+
if (pending) {
|
|
171
|
+
this.pipeline.fail(new ReplicationAbortedError('Disposed writer with pending replication work'));
|
|
172
|
+
}
|
|
173
|
+
await this.options.replicationLock.writerMutex.exclusiveLock(async () => {
|
|
174
|
+
if (pending || this.options.replicationLock.signal.aborted) {
|
|
175
|
+
await this.pipeline.join();
|
|
176
|
+
}
|
|
177
|
+
this.pipeline.unregisterWriter(this);
|
|
178
|
+
if (this.batch?.hasData()) {
|
|
179
|
+
// We don't error here, since:
|
|
180
|
+
// 1. In error states, this is expected (we can't distinguish between disposing after success or error).
|
|
181
|
+
// 2. SuppressedError is messy to deal with.
|
|
182
|
+
this.logger.warn('Disposing writer with unflushed changes');
|
|
183
|
+
}
|
|
184
|
+
// The lease owns the shared session and ends it after all writers stop.
|
|
185
|
+
super.clearListeners();
|
|
186
|
+
});
|
|
32
187
|
}
|
|
33
188
|
createPersistedBatch(writtenSize) {
|
|
34
189
|
return new PersistedBatchV3(this.db, this.replicationStreamId, this.mapping, writtenSize, {
|
|
35
190
|
logger: this.logger,
|
|
191
|
+
batchLimits: this.options.batchLimits,
|
|
36
192
|
objectStorage: this.options.objectStorage,
|
|
37
193
|
inlineThresholdBytes: this.options.inlineThresholdBytes,
|
|
38
194
|
signal: this.options.signal,
|
|
@@ -48,18 +204,56 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
48
204
|
return callback(stream);
|
|
49
205
|
}, session);
|
|
50
206
|
}
|
|
207
|
+
/** Internal helpers require the public operation to hold the writer mutex. */
|
|
208
|
+
async flushInternal(options) {
|
|
209
|
+
let result = null;
|
|
210
|
+
// One captured input may be split over multiple publications. Each
|
|
211
|
+
// flushInner() consumes a prefix, retaining its remainder for this operation.
|
|
212
|
+
while (this.capturedInput != null) {
|
|
213
|
+
let r = await this.flushInner(options);
|
|
214
|
+
if (r) {
|
|
215
|
+
result = r;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return result;
|
|
219
|
+
}
|
|
220
|
+
/** Publish the checkpoint in the final flush transaction, or use the empty-commit path. */
|
|
221
|
+
async flushAndCommit(checkpoint, commitWithoutFlush, options, projection) {
|
|
222
|
+
if (this.capturedInput == null) {
|
|
223
|
+
return commitWithoutFlush();
|
|
224
|
+
}
|
|
225
|
+
let result;
|
|
226
|
+
while (this.capturedInput != null) {
|
|
227
|
+
await this.flushInner(options, async (stream, lastOp, writes) => {
|
|
228
|
+
result = await checkpoint(stream, lastOp, writes);
|
|
229
|
+
}, projection);
|
|
230
|
+
}
|
|
231
|
+
return result;
|
|
232
|
+
}
|
|
51
233
|
async flushInner(options, checkpoint, projection) {
|
|
52
234
|
using _span = this.tracer.span('storage', 'flush');
|
|
53
235
|
await this.hooks?.beforeBatchFlush?.(this);
|
|
54
|
-
const input = this.
|
|
55
|
-
const checkpoints =
|
|
56
|
-
const allocator = this.
|
|
236
|
+
const input = this.capturedInput;
|
|
237
|
+
const checkpoints = input?.customWriteCheckpoints ?? [];
|
|
238
|
+
const allocator = this.pipeline.allocator;
|
|
57
239
|
await allocator.ensureCapacity();
|
|
58
240
|
const contextProjection = { ...projection, state: 1, last_persisted_op: 1, sync_configs: 1 };
|
|
59
241
|
if (checkpoints.length > 0) {
|
|
60
|
-
await this.prepareCustomWriteCheckpoints();
|
|
242
|
+
await this.prepareCustomWriteCheckpoints(checkpoints);
|
|
61
243
|
}
|
|
62
|
-
|
|
244
|
+
await this.pipeline.capacity();
|
|
245
|
+
const overlay = this.pipeline.beginRead();
|
|
246
|
+
let prepared;
|
|
247
|
+
try {
|
|
248
|
+
prepared = await this.prepareRows(this.session, input, overlay);
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
this.pipeline.endRead();
|
|
252
|
+
}
|
|
253
|
+
const { publications, repairs, resumeBatch, changes, hasWrites } = prepared;
|
|
254
|
+
const retainedBytes = prepared.retainedBytes +
|
|
255
|
+
checkpoints.reduce((bytes, checkpoint) => bytes + (bson.calculateObjectSize(checkpoint) + 256) * RETAINED_BYTES_FACTOR, 0);
|
|
256
|
+
const publishCheckpoint = checkpoint != null && resumeBatch == null;
|
|
63
257
|
let lastOp = prepared.lastOp;
|
|
64
258
|
let checkpointOp;
|
|
65
259
|
if (checkpoints.length > 0) {
|
|
@@ -79,59 +273,82 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
79
273
|
}
|
|
80
274
|
// Reservations are globally disjoint and this lease's allocator consumes IDs
|
|
81
275
|
// assigned to sealed work, even if publication is abandoned. The writer mutex
|
|
82
|
-
//
|
|
276
|
+
// serializes preparation under this lease; the shared overlay covers pending writes;
|
|
83
277
|
// the transaction fence excludes a different lease owner. Thus preparation
|
|
84
278
|
// does not need to read the persisted head to allocate IDs or reuse records.
|
|
85
279
|
allocator.consume(lastOp);
|
|
86
|
-
const clearError = !this.clearedError &&
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
lastOp
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
280
|
+
const clearError = !this.clearedError && hasWrites;
|
|
281
|
+
const publish = async (session) => {
|
|
282
|
+
await this.publishPrepared(lastOp, contextProjection, publications, options, async (stream, writes) => {
|
|
283
|
+
// An empty flush allocates no ID. Use the durable head from the
|
|
284
|
+
// fresh fence for its checkpoint and returned flushed operation.
|
|
285
|
+
if (lastOp === 0n) {
|
|
286
|
+
lastOp = this.persistedOpHead(stream);
|
|
287
|
+
}
|
|
288
|
+
if (clearError) {
|
|
289
|
+
writes.updateOne(this.db.sync_rules, { _id: this.replicationStreamId }, {
|
|
290
|
+
$set: { last_fatal_error: null, last_fatal_error_ts: null }
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
if (checkpointOp != null) {
|
|
294
|
+
this.queueCustomWriteCheckpoints(writes, checkpointOp, checkpoints);
|
|
295
|
+
}
|
|
296
|
+
if (publishCheckpoint) {
|
|
297
|
+
// Checkpoint decisions use this attempt's freshly fenced state.
|
|
298
|
+
await checkpoint(stream, lastOp, writes);
|
|
299
|
+
}
|
|
300
|
+
else {
|
|
301
|
+
this.onReplicationTransactionFlush(writes, lastOp);
|
|
302
|
+
}
|
|
303
|
+
}, session);
|
|
304
|
+
this.clearedError ||= clearError;
|
|
305
|
+
this.last_flushed_op = lastOp;
|
|
306
|
+
// markRecordUnavailable only synchronously queues connector-owned repair
|
|
307
|
+
// keys. It must not mutate input, perform async work, or re-enter storage:
|
|
308
|
+
// publication is serialized, but queued publication does not hold the
|
|
309
|
+
// writer mutex. Delivery must finish before flush() returns;
|
|
310
|
+
// WalStream drains that queue before commit()/ack().
|
|
311
|
+
// Once committed, these writes cannot be rolled back if the callback
|
|
312
|
+
// throws. Invalidate the whole local lease before publication completes, so
|
|
313
|
+
// no writer sharing it (including queued calls) can advance progress
|
|
314
|
+
// past an undelivered repair. A fresh replication attempt must replay
|
|
315
|
+
// from the old source position and redetect incomplete rows.
|
|
316
|
+
try {
|
|
317
|
+
const notify = this.markRecordUnavailable;
|
|
318
|
+
if (notify != null) {
|
|
319
|
+
for (const record of repairs) {
|
|
320
|
+
notify(record);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
104
323
|
}
|
|
105
|
-
|
|
106
|
-
this.
|
|
324
|
+
catch (error) {
|
|
325
|
+
this.options.replicationLock.invalidate(new ReplicationAbortedError('Committed replication repair notification failed; restart replication before advancing source progress', error));
|
|
326
|
+
throw error;
|
|
107
327
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
this.
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
// past an undelivered repair. A fresh replication attempt must replay
|
|
121
|
-
// from the old source position and redetect incomplete rows.
|
|
122
|
-
try {
|
|
123
|
-
const notify = this.markRecordUnavailable;
|
|
124
|
-
if (notify != null) {
|
|
125
|
-
for (const record of prepared.repairs) {
|
|
126
|
-
notify(record);
|
|
328
|
+
await this.hooks?.afterBatchFlush?.(this);
|
|
329
|
+
};
|
|
330
|
+
// Repairs stay synchronous so the connector can repair rows before source
|
|
331
|
+
// progress advances. Ordinary rows may pipeline even for repair-capable sources.
|
|
332
|
+
const shouldQueue = this.enqueuePublication && repairs.length === 0;
|
|
333
|
+
if (shouldQueue) {
|
|
334
|
+
await this.pipeline.capacity(retainedBytes);
|
|
335
|
+
this.capturedInput = resumeBatch;
|
|
336
|
+
this.pendingPublications++;
|
|
337
|
+
const receipt = this.pipeline.enqueue(changes, retainedBytes, async () => {
|
|
338
|
+
for (const publication of publications) {
|
|
339
|
+
await publication.packAndUploadPayloads();
|
|
127
340
|
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
341
|
+
}, publish);
|
|
342
|
+
void receipt
|
|
343
|
+
.finally(() => {
|
|
344
|
+
this.pendingPublications--;
|
|
345
|
+
})
|
|
346
|
+
.catch(() => { });
|
|
347
|
+
return null;
|
|
133
348
|
}
|
|
134
|
-
await this.
|
|
349
|
+
await this.pipeline.drain();
|
|
350
|
+
await publish(this.session);
|
|
351
|
+
this.capturedInput = resumeBatch;
|
|
135
352
|
return { flushed_op: lastOp };
|
|
136
353
|
}
|
|
137
354
|
assertPreparationContext(stream) {
|
|
@@ -141,71 +358,96 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
141
358
|
this.options.parsedSyncConfig.assertPublicationConfigs(stream.sync_configs);
|
|
142
359
|
}
|
|
143
360
|
/**
|
|
144
|
-
* Internal publisher:
|
|
361
|
+
* Internal publisher: called either by a durable barrier or by the lease FIFO.
|
|
145
362
|
* finish() must only queue writes independent of the final data group, using
|
|
146
363
|
* the fresh fence and planned IDs; it must not execute the supplied batch or
|
|
147
364
|
* read results from unpublished data. Activation and cleanup remain separate.
|
|
148
365
|
*/
|
|
149
|
-
async publishPrepared(lastOp, projection, publications, options, finish) {
|
|
366
|
+
async publishPrepared(lastOp, projection, publications, options, finish, session = this.session) {
|
|
367
|
+
const tracer = session === this.session ? this.tracer : this.pipeline.tracer;
|
|
150
368
|
// This gate covers every sealed batch in the prefix, including truncate/drop.
|
|
151
369
|
// The transaction must never wait for source reads, evaluation or S3 PUTs.
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
await publication.preparePayloads();
|
|
156
|
-
}
|
|
370
|
+
// Queued work can pack/upload ahead of its publication turn. This idempotent
|
|
371
|
+
// gate also handles synchronous flushes and truncate/drop, which start their
|
|
372
|
+
// payload work here. Every upload must finish before opening the transaction.
|
|
157
373
|
let attempts = 0;
|
|
158
|
-
const
|
|
374
|
+
const startedAt = Date.now();
|
|
159
375
|
try {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
376
|
+
for (const publication of publications) {
|
|
377
|
+
await publication.packAndUploadPayloads();
|
|
378
|
+
}
|
|
379
|
+
// Groups can update the same bucket. Preserve the order of their deltas
|
|
380
|
+
// and reuse the same write models on every transaction attempt.
|
|
381
|
+
const bucketStates = this.db.createWriteBatch(session, { ordered: true });
|
|
382
|
+
for (const publication of publications) {
|
|
383
|
+
publication.queueBucketStates(bucketStates);
|
|
384
|
+
}
|
|
385
|
+
await this.withFencedTransaction(async () => {
|
|
386
|
+
const elapsedMs = Date.now() - startedAt;
|
|
387
|
+
if (attempts >= 20 && elapsedMs > 90_000) {
|
|
388
|
+
throw new ServiceError(ErrorCode.PSYNC_S1402, `Publication retry limit reached after ${attempts} attempts (${elapsedMs} ms since publication started)`);
|
|
164
389
|
}
|
|
390
|
+
attempts++;
|
|
391
|
+
// Start with the bucket writes to minimize the time compaction has
|
|
392
|
+
// to modify them after the transaction starts. The fence still
|
|
393
|
+
// protects the entire transaction, including these writes.
|
|
394
|
+
await tracer.span('storage', 'publish_bucket_state').with(() => bucketStates.execute());
|
|
395
|
+
return tracer.span('storage', 'publish_fence').with(() => this.fence(session, projection));
|
|
396
|
+
}, async (document) => {
|
|
165
397
|
const stream = document;
|
|
166
398
|
this.assertPreparationContext(stream);
|
|
167
399
|
const head = this.persistedOpHead(stream);
|
|
168
400
|
if (lastOp !== 0n && lastOp <= head) {
|
|
169
401
|
throw new ReplicationAssertionError(`Prepared operation ${lastOp} does not advance persisted stream head ${head}`);
|
|
170
402
|
}
|
|
171
|
-
// Earlier groups may replace the same source record
|
|
403
|
+
// Earlier groups may replace the same source record.
|
|
172
404
|
// Preserve their execution order; only the final group's writes are
|
|
173
405
|
// independent of the head/checkpoint tail built from this fresh fence.
|
|
174
406
|
for (const publication of publications.slice(0, -1)) {
|
|
175
|
-
using _persist =
|
|
176
|
-
await publication.publish(
|
|
407
|
+
using _persist = tracer.span('storage', 'persist_flush');
|
|
408
|
+
await publication.publish(session, options);
|
|
177
409
|
}
|
|
178
|
-
const writes = this.db.createWriteBatch(
|
|
410
|
+
const writes = this.db.createWriteBatch(session, { ordered: false });
|
|
179
411
|
await finish(stream, writes);
|
|
180
412
|
const finalPublication = publications.at(-1);
|
|
181
413
|
if (finalPublication != null) {
|
|
182
|
-
using _persist =
|
|
183
|
-
await finalPublication.publish(
|
|
414
|
+
using _persist = tracer.span('storage', 'persist_flush');
|
|
415
|
+
await finalPublication.publish(session, options, writes);
|
|
184
416
|
}
|
|
185
417
|
else {
|
|
186
418
|
await writes.execute();
|
|
187
419
|
}
|
|
188
|
-
},
|
|
420
|
+
}, session, 'Publishing prepared work', tracer);
|
|
189
421
|
}
|
|
190
422
|
catch (error) {
|
|
191
|
-
//
|
|
192
|
-
//
|
|
423
|
+
// Packing, upload or MongoDB publication failed. Marker registration or the
|
|
424
|
+
// commit may have succeeded, so leave uploaded objects and markers alone.
|
|
193
425
|
// Stop every writer on this lease and recover from persisted source progress.
|
|
194
426
|
this.options.replicationLock.invalidate(new ReplicationAbortedError('Publication failed; restart replication from persisted progress', error));
|
|
195
427
|
throw error;
|
|
196
428
|
}
|
|
197
429
|
}
|
|
198
|
-
async prepareRows(session, input) {
|
|
430
|
+
async prepareRows(session, input, overlay) {
|
|
199
431
|
const publications = [];
|
|
200
432
|
const repairs = [];
|
|
201
433
|
let resumeBatch = null;
|
|
202
434
|
let lastOp = 0n;
|
|
203
435
|
let hasWrites = false;
|
|
436
|
+
let retainedBytes = 0;
|
|
437
|
+
const changes = new Map();
|
|
204
438
|
if (input == null) {
|
|
205
|
-
return {
|
|
439
|
+
return {
|
|
440
|
+
publications,
|
|
441
|
+
repairs,
|
|
442
|
+
resumeBatch,
|
|
443
|
+
lastOp,
|
|
444
|
+
hasWrites,
|
|
445
|
+
changes,
|
|
446
|
+
retainedBytes
|
|
447
|
+
};
|
|
206
448
|
}
|
|
207
449
|
using _preparation = this.tracer.span('storage', 'prepare');
|
|
208
|
-
const allocator = this.
|
|
450
|
+
const allocator = this.pipeline.allocator;
|
|
209
451
|
let sizes;
|
|
210
452
|
// Keep the existing size-based read partitioning, including per-table raw
|
|
211
453
|
// data storage and snapshot skip-existing exceptions. Move these reads;
|
|
@@ -217,10 +459,19 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
217
459
|
.filter((op) => op.record.sourceTable.storeCurrentData)
|
|
218
460
|
.map((op) => ({ sourceTableId: mongoTableId(op.record.sourceTable.id), replicaId: op.beforeId })));
|
|
219
461
|
}
|
|
220
|
-
//
|
|
221
|
-
//
|
|
222
|
-
const
|
|
462
|
+
// The predecessor's immutable delta overrides durable records. Its lifetime
|
|
463
|
+
// is pinned through this preparation, including reads that straddle commit.
|
|
464
|
+
for (const [key, record] of overlay) {
|
|
465
|
+
sizes?.set(key, record.data?.length() ?? 0);
|
|
466
|
+
}
|
|
467
|
+
const records = new Map(overlay);
|
|
223
468
|
let writtenSize = 0;
|
|
469
|
+
// Sealing is pure. After capacity is checked and ownership transfers to the
|
|
470
|
+
// pipeline, packing/uploads can overlap the predecessor's remaining work.
|
|
471
|
+
const prepareGroup = (group) => {
|
|
472
|
+
retainedBytes += group.estimatedRetainedBytes;
|
|
473
|
+
publications.push(group.seal());
|
|
474
|
+
};
|
|
224
475
|
for (const block of input.batched(sizes)) {
|
|
225
476
|
if (resumeBatch != null) {
|
|
226
477
|
for (const op of block) {
|
|
@@ -228,6 +479,8 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
228
479
|
}
|
|
229
480
|
continue;
|
|
230
481
|
}
|
|
482
|
+
this.options.replicationLock.throwIfAborted();
|
|
483
|
+
this.pipeline.advanceReadTime();
|
|
231
484
|
const missing = block.filter((op) => !records.has(op.internalBeforeKey));
|
|
232
485
|
if (missing.length > 0) {
|
|
233
486
|
using _lookup = this.tracer.span('storage', 'lookup');
|
|
@@ -267,7 +520,7 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
267
520
|
if (!(error instanceof OpIdRangeExhausted)) {
|
|
268
521
|
throw error;
|
|
269
522
|
}
|
|
270
|
-
// Retry only the unfinished row;
|
|
523
|
+
// Retry only the unfinished row; its payload has not been uploaded.
|
|
271
524
|
this.options.replicationLock.throwIfAborted();
|
|
272
525
|
await allocator.reserve();
|
|
273
526
|
}
|
|
@@ -276,29 +529,64 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
276
529
|
// Preserve evaluation's existing repeated-row behavior: a deleted
|
|
277
530
|
// identity no longer supplies raw values or membership to later rows.
|
|
278
531
|
records.set(op.internalBeforeKey, null);
|
|
532
|
+
// Persisted soft deletes still exist for snapshot skip-existing
|
|
533
|
+
// lookups, even though repeated streaming updates use empty state.
|
|
534
|
+
changes.set(op.internalBeforeKey, {
|
|
535
|
+
sourceTableId: mongoTableId(op.record.sourceTable.id),
|
|
536
|
+
replicaId: op.beforeId,
|
|
537
|
+
cacheKey: op.internalBeforeKey,
|
|
538
|
+
data: null,
|
|
539
|
+
buckets: [],
|
|
540
|
+
lookups: []
|
|
541
|
+
});
|
|
279
542
|
}
|
|
280
543
|
if (next != null) {
|
|
281
544
|
records.set(op.internalAfterKey, next);
|
|
545
|
+
changes.set(op.internalAfterKey, next);
|
|
282
546
|
sizes?.set(op.internalAfterKey, next.data?.length() ?? 0);
|
|
283
547
|
}
|
|
284
548
|
if (group.shouldFlushTransaction()) {
|
|
285
|
-
|
|
549
|
+
prepareGroup(group);
|
|
286
550
|
group = null;
|
|
287
|
-
resumeBatch = new OperationBatch();
|
|
551
|
+
resumeBatch = new OperationBatch(this.options.batchLimits);
|
|
288
552
|
}
|
|
289
553
|
}
|
|
290
554
|
if (group != null) {
|
|
291
555
|
writtenSize = group.currentSize;
|
|
292
|
-
|
|
556
|
+
prepareGroup(group);
|
|
293
557
|
}
|
|
294
558
|
}
|
|
295
|
-
return {
|
|
559
|
+
return {
|
|
560
|
+
publications,
|
|
561
|
+
repairs,
|
|
562
|
+
resumeBatch: resumeBatch?.hasData() ? resumeBatch : null,
|
|
563
|
+
lastOp,
|
|
564
|
+
hasWrites,
|
|
565
|
+
changes,
|
|
566
|
+
retainedBytes
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
async truncateInternal(sourceTables) {
|
|
570
|
+
// The metadata barrier has already published every captured input. Rows
|
|
571
|
+
// buffered after that boundary belong to later operations and stay untouched.
|
|
572
|
+
let last_op = null;
|
|
573
|
+
for (let table of sourceTables) {
|
|
574
|
+
last_op = await this.truncateSingleInternal(table);
|
|
575
|
+
}
|
|
576
|
+
if (last_op) {
|
|
577
|
+
return {
|
|
578
|
+
flushed_op: last_op
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
else {
|
|
582
|
+
return null;
|
|
583
|
+
}
|
|
296
584
|
}
|
|
297
585
|
async truncateSingleInternal(sourceTable) {
|
|
298
586
|
const sourceId = mongoTableId(sourceTable.id);
|
|
299
587
|
const session = this.session;
|
|
300
588
|
const projection = { state: 1, sync_configs: 1, last_persisted_op: 1 };
|
|
301
|
-
const allocator = this.
|
|
589
|
+
const allocator = this.pipeline.allocator;
|
|
302
590
|
while (true) {
|
|
303
591
|
await allocator.ensureCapacity();
|
|
304
592
|
// Preserve the existing bounded table scan. Hard deletion lets the next
|
|
@@ -509,15 +797,6 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
509
797
|
}
|
|
510
798
|
async commitInternal(lsn, options) {
|
|
511
799
|
this.options.replicationLock.throwIfAborted();
|
|
512
|
-
if (this.markRecordUnavailable != null && this.batch?.hasData()) {
|
|
513
|
-
// A combined data+checkpoint commit cannot return control to the connector
|
|
514
|
-
// to process repair notifications between those two durable boundaries.
|
|
515
|
-
// Require its explicit flush -> repair -> commit ordering even when this
|
|
516
|
-
// particular input might turn out not to need repair. An empty batch does
|
|
517
|
-
// not prove its external repair queue is drained; that remains the caller's
|
|
518
|
-
// responsibility. keepalive() delegates here and has the same requirement.
|
|
519
|
-
throw new ReplicationAssertionError('Flush pending rows and process markRecordUnavailable repairs before committing source progress');
|
|
520
|
-
}
|
|
521
800
|
const { createEmptyCheckpoints } = { ...storage.DEFAULT_BUCKET_BATCH_COMMIT_OPTIONS, ...options };
|
|
522
801
|
using _ = this.tracer.span('storage', 'commit');
|
|
523
802
|
const checkpoint = async (stream, lastOp, additionalWrites) => {
|
|
@@ -840,11 +1119,11 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
840
1119
|
this.batchCreateEventCustomWriteCheckpoints(writes, opId, eventId, checkpoints);
|
|
841
1120
|
}
|
|
842
1121
|
}
|
|
843
|
-
async prepareCustomWriteCheckpoints() {
|
|
1122
|
+
async prepareCustomWriteCheckpoints(checkpoints) {
|
|
844
1123
|
// Most events never produce custom checkpoints, so create collections lazily
|
|
845
1124
|
// only for the event ids present in this batch. This hook runs before the
|
|
846
1125
|
// replication transaction because MongoDB cannot create indexes within it.
|
|
847
|
-
const eventIds = new Set(
|
|
1126
|
+
const eventIds = new Set(checkpoints.map((checkpoint) => this.validateCustomCheckpointEventId(checkpoint.event_id)));
|
|
848
1127
|
for (const eventId of eventIds) {
|
|
849
1128
|
if (this.initializedCustomCheckpointEventIds.has(eventId)) {
|
|
850
1129
|
continue;
|