@powersync/service-module-mongodb-storage 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -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 +21 -16
- package/dist/storage/implementation/MongoBucketBatch.js +22 -125
- package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
- package/dist/storage/implementation/MongoStorageProvider.js +1 -0
- package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
- package/dist/storage/implementation/MongoSyncBucketStorage.js +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 +12 -3
- package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
- package/dist/storage/implementation/OperationBatch.d.ts +10 -3
- package/dist/storage/implementation/OperationBatch.js +22 -13
- package/dist/storage/implementation/OperationBatch.js.map +1 -1
- package/dist/storage/implementation/ReplicationBatchLimits.d.ts +24 -0
- package/dist/storage/implementation/ReplicationBatchLimits.js +25 -0
- package/dist/storage/implementation/ReplicationBatchLimits.js.map +1 -0
- package/dist/storage/implementation/common/BatchOperationBuffer.d.ts +17 -1
- package/dist/storage/implementation/common/BatchOperationBuffer.js +22 -24
- package/dist/storage/implementation/common/BatchOperationBuffer.js.map +1 -1
- package/dist/storage/implementation/common/PersistedBatch.d.ts +2 -0
- package/dist/storage/implementation/common/PreparedPublication.d.ts +13 -9
- package/dist/storage/implementation/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/MongoBucketBatchV3.d.ts +39 -3
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js +356 -90
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -5
- package/dist/storage/implementation/v3/PersistedBatchV3.js +26 -13
- package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/ReplicationPipelineV3.d.ts +84 -0
- package/dist/storage/implementation/v3/ReplicationPipelineV3.js +187 -0
- package/dist/storage/implementation/v3/ReplicationPipelineV3.js.map +1 -0
- package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +4 -4
- package/dist/storage/implementation/v3/SourceRecordStoreV3.js +4 -4
- package/dist/storage/implementation/v3/chunking.js +7 -3
- package/dist/storage/implementation/v3/chunking.js.map +1 -1
- package/dist/types/types.d.ts +5 -0
- package/dist/types/types.js +4 -0
- package/dist/types/types.js.map +1 -1
- package/dist/utils/collection-sizes.d.ts +9 -0
- package/dist/utils/collection-sizes.js +95 -0
- package/dist/utils/collection-sizes.js.map +1 -0
- package/dist/utils/test-utils.js +1 -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 +47 -137
- package/src/storage/implementation/MongoStorageProvider.ts +1 -0
- package/src/storage/implementation/MongoSyncBucketStorage.ts +1 -0
- package/src/storage/implementation/MongoSyncRulesLock.ts +13 -3
- package/src/storage/implementation/OperationBatch.ts +23 -15
- package/src/storage/implementation/ReplicationBatchLimits.ts +45 -0
- package/src/storage/implementation/common/BatchOperationBuffer.ts +21 -26
- package/src/storage/implementation/common/PersistedBatch.ts +2 -0
- package/src/storage/implementation/common/PreparedPublication.ts +13 -9
- package/src/storage/implementation/v1/MongoBucketBatchV1.ts +135 -17
- package/src/storage/implementation/v1/PersistedBatchV1.ts +2 -1
- package/src/storage/implementation/v3/MongoBucketBatchV3.ts +433 -101
- package/src/storage/implementation/v3/PersistedBatchV3.ts +26 -13
- package/src/storage/implementation/v3/ReplicationPipelineV3.ts +220 -0
- package/src/storage/implementation/v3/SourceRecordStoreV3.ts +4 -4
- package/src/storage/implementation/v3/chunking.ts +8 -3
- package/src/types/types.ts +7 -0
- package/src/utils/collection-sizes.ts +114 -0
- package/src/utils/test-utils.ts +1 -0
- package/test/src/concurrent_writers.test.ts +9 -15
- package/test/src/operation_batch.test.ts +207 -0
- package/test/src/prepared_publication.test.ts +187 -6
- package/test/src/replication_batch_config.test.ts +117 -0
- package/test/src/replication_pipeline.test.ts +738 -0
- package/test/src/replication_pipeline_benchmark.test.ts +133 -0
- package/test/src/replication_preparation.test.ts +4 -2
- package/test/src/replication_uploads.test.ts +28 -3
- package/test/src/storage.test.ts +24 -5
- package/test/src/storage_compacting.test.ts +16 -0
- package/test/src/storage_metrics.test.ts +88 -0
- package/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);
|
|
243
|
+
}
|
|
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);
|
|
61
249
|
}
|
|
62
|
-
|
|
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,23 +358,25 @@ 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
374
|
const retryDeadline = Date.now() + 90_000;
|
|
159
375
|
try {
|
|
160
|
-
|
|
376
|
+
for (const publication of publications) {
|
|
377
|
+
await publication.packAndUploadPayloads();
|
|
378
|
+
}
|
|
379
|
+
await this.withFencedTransaction(() => this.fence(session, projection), async (document) => {
|
|
161
380
|
attempts++;
|
|
162
381
|
if (attempts > 20 && Date.now() > retryDeadline) {
|
|
163
382
|
throw new ServiceError(ErrorCode.PSYNC_S1402, 'Max transaction tries exceeded');
|
|
@@ -172,40 +391,50 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
172
391
|
// Preserve their execution order; only the final group's writes are
|
|
173
392
|
// independent of the head/checkpoint tail built from this fresh fence.
|
|
174
393
|
for (const publication of publications.slice(0, -1)) {
|
|
175
|
-
using _persist =
|
|
176
|
-
await publication.publish(
|
|
394
|
+
using _persist = tracer.span('storage', 'persist_flush');
|
|
395
|
+
await publication.publish(session, options);
|
|
177
396
|
}
|
|
178
|
-
const writes = this.db.createWriteBatch(
|
|
397
|
+
const writes = this.db.createWriteBatch(session, { ordered: false });
|
|
179
398
|
await finish(stream, writes);
|
|
180
399
|
const finalPublication = publications.at(-1);
|
|
181
400
|
if (finalPublication != null) {
|
|
182
|
-
using _persist =
|
|
183
|
-
await finalPublication.publish(
|
|
401
|
+
using _persist = tracer.span('storage', 'persist_flush');
|
|
402
|
+
await finalPublication.publish(session, options, writes);
|
|
184
403
|
}
|
|
185
404
|
else {
|
|
186
405
|
await writes.execute();
|
|
187
406
|
}
|
|
188
|
-
},
|
|
407
|
+
}, session, 'Publishing prepared work', tracer);
|
|
189
408
|
}
|
|
190
409
|
catch (error) {
|
|
191
|
-
//
|
|
192
|
-
//
|
|
410
|
+
// Packing, upload or MongoDB publication failed. Marker registration or the
|
|
411
|
+
// commit may have succeeded, so leave uploaded objects and markers alone.
|
|
193
412
|
// Stop every writer on this lease and recover from persisted source progress.
|
|
194
413
|
this.options.replicationLock.invalidate(new ReplicationAbortedError('Publication failed; restart replication from persisted progress', error));
|
|
195
414
|
throw error;
|
|
196
415
|
}
|
|
197
416
|
}
|
|
198
|
-
async prepareRows(session, input) {
|
|
417
|
+
async prepareRows(session, input, overlay) {
|
|
199
418
|
const publications = [];
|
|
200
419
|
const repairs = [];
|
|
201
420
|
let resumeBatch = null;
|
|
202
421
|
let lastOp = 0n;
|
|
203
422
|
let hasWrites = false;
|
|
423
|
+
let retainedBytes = 0;
|
|
424
|
+
const changes = new Map();
|
|
204
425
|
if (input == null) {
|
|
205
|
-
return {
|
|
426
|
+
return {
|
|
427
|
+
publications,
|
|
428
|
+
repairs,
|
|
429
|
+
resumeBatch,
|
|
430
|
+
lastOp,
|
|
431
|
+
hasWrites,
|
|
432
|
+
changes,
|
|
433
|
+
retainedBytes
|
|
434
|
+
};
|
|
206
435
|
}
|
|
207
436
|
using _preparation = this.tracer.span('storage', 'prepare');
|
|
208
|
-
const allocator = this.
|
|
437
|
+
const allocator = this.pipeline.allocator;
|
|
209
438
|
let sizes;
|
|
210
439
|
// Keep the existing size-based read partitioning, including per-table raw
|
|
211
440
|
// data storage and snapshot skip-existing exceptions. Move these reads;
|
|
@@ -217,10 +446,19 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
217
446
|
.filter((op) => op.record.sourceTable.storeCurrentData)
|
|
218
447
|
.map((op) => ({ sourceTableId: mongoTableId(op.record.sourceTable.id), replicaId: op.beforeId })));
|
|
219
448
|
}
|
|
220
|
-
//
|
|
221
|
-
//
|
|
222
|
-
const
|
|
449
|
+
// The predecessor's immutable delta overrides durable records. Its lifetime
|
|
450
|
+
// is pinned through this preparation, including reads that straddle commit.
|
|
451
|
+
for (const [key, record] of overlay) {
|
|
452
|
+
sizes?.set(key, record.data?.length() ?? 0);
|
|
453
|
+
}
|
|
454
|
+
const records = new Map(overlay);
|
|
223
455
|
let writtenSize = 0;
|
|
456
|
+
// Sealing is pure. After capacity is checked and ownership transfers to the
|
|
457
|
+
// pipeline, packing/uploads can overlap the predecessor's remaining work.
|
|
458
|
+
const prepareGroup = (group) => {
|
|
459
|
+
retainedBytes += group.estimatedRetainedBytes;
|
|
460
|
+
publications.push(group.seal());
|
|
461
|
+
};
|
|
224
462
|
for (const block of input.batched(sizes)) {
|
|
225
463
|
if (resumeBatch != null) {
|
|
226
464
|
for (const op of block) {
|
|
@@ -228,6 +466,8 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
228
466
|
}
|
|
229
467
|
continue;
|
|
230
468
|
}
|
|
469
|
+
this.options.replicationLock.throwIfAborted();
|
|
470
|
+
this.pipeline.advanceReadTime();
|
|
231
471
|
const missing = block.filter((op) => !records.has(op.internalBeforeKey));
|
|
232
472
|
if (missing.length > 0) {
|
|
233
473
|
using _lookup = this.tracer.span('storage', 'lookup');
|
|
@@ -267,7 +507,7 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
267
507
|
if (!(error instanceof OpIdRangeExhausted)) {
|
|
268
508
|
throw error;
|
|
269
509
|
}
|
|
270
|
-
// Retry only the unfinished row;
|
|
510
|
+
// Retry only the unfinished row; its payload has not been uploaded.
|
|
271
511
|
this.options.replicationLock.throwIfAborted();
|
|
272
512
|
await allocator.reserve();
|
|
273
513
|
}
|
|
@@ -276,29 +516,64 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
276
516
|
// Preserve evaluation's existing repeated-row behavior: a deleted
|
|
277
517
|
// identity no longer supplies raw values or membership to later rows.
|
|
278
518
|
records.set(op.internalBeforeKey, null);
|
|
519
|
+
// Persisted soft deletes still exist for snapshot skip-existing
|
|
520
|
+
// lookups, even though repeated streaming updates use empty state.
|
|
521
|
+
changes.set(op.internalBeforeKey, {
|
|
522
|
+
sourceTableId: mongoTableId(op.record.sourceTable.id),
|
|
523
|
+
replicaId: op.beforeId,
|
|
524
|
+
cacheKey: op.internalBeforeKey,
|
|
525
|
+
data: null,
|
|
526
|
+
buckets: [],
|
|
527
|
+
lookups: []
|
|
528
|
+
});
|
|
279
529
|
}
|
|
280
530
|
if (next != null) {
|
|
281
531
|
records.set(op.internalAfterKey, next);
|
|
532
|
+
changes.set(op.internalAfterKey, next);
|
|
282
533
|
sizes?.set(op.internalAfterKey, next.data?.length() ?? 0);
|
|
283
534
|
}
|
|
284
535
|
if (group.shouldFlushTransaction()) {
|
|
285
|
-
|
|
536
|
+
prepareGroup(group);
|
|
286
537
|
group = null;
|
|
287
|
-
resumeBatch = new OperationBatch();
|
|
538
|
+
resumeBatch = new OperationBatch(this.options.batchLimits);
|
|
288
539
|
}
|
|
289
540
|
}
|
|
290
541
|
if (group != null) {
|
|
291
542
|
writtenSize = group.currentSize;
|
|
292
|
-
|
|
543
|
+
prepareGroup(group);
|
|
293
544
|
}
|
|
294
545
|
}
|
|
295
|
-
return {
|
|
546
|
+
return {
|
|
547
|
+
publications,
|
|
548
|
+
repairs,
|
|
549
|
+
resumeBatch: resumeBatch?.hasData() ? resumeBatch : null,
|
|
550
|
+
lastOp,
|
|
551
|
+
hasWrites,
|
|
552
|
+
changes,
|
|
553
|
+
retainedBytes
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
async truncateInternal(sourceTables) {
|
|
557
|
+
// The metadata barrier has already published every captured input. Rows
|
|
558
|
+
// buffered after that boundary belong to later operations and stay untouched.
|
|
559
|
+
let last_op = null;
|
|
560
|
+
for (let table of sourceTables) {
|
|
561
|
+
last_op = await this.truncateSingleInternal(table);
|
|
562
|
+
}
|
|
563
|
+
if (last_op) {
|
|
564
|
+
return {
|
|
565
|
+
flushed_op: last_op
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
else {
|
|
569
|
+
return null;
|
|
570
|
+
}
|
|
296
571
|
}
|
|
297
572
|
async truncateSingleInternal(sourceTable) {
|
|
298
573
|
const sourceId = mongoTableId(sourceTable.id);
|
|
299
574
|
const session = this.session;
|
|
300
575
|
const projection = { state: 1, sync_configs: 1, last_persisted_op: 1 };
|
|
301
|
-
const allocator = this.
|
|
576
|
+
const allocator = this.pipeline.allocator;
|
|
302
577
|
while (true) {
|
|
303
578
|
await allocator.ensureCapacity();
|
|
304
579
|
// Preserve the existing bounded table scan. Hard deletion lets the next
|
|
@@ -509,15 +784,6 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
509
784
|
}
|
|
510
785
|
async commitInternal(lsn, options) {
|
|
511
786
|
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
787
|
const { createEmptyCheckpoints } = { ...storage.DEFAULT_BUCKET_BATCH_COMMIT_OPTIONS, ...options };
|
|
522
788
|
using _ = this.tracer.span('storage', 'commit');
|
|
523
789
|
const checkpoint = async (stream, lastOp, additionalWrites) => {
|
|
@@ -840,11 +1106,11 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
|
|
|
840
1106
|
this.batchCreateEventCustomWriteCheckpoints(writes, opId, eventId, checkpoints);
|
|
841
1107
|
}
|
|
842
1108
|
}
|
|
843
|
-
async prepareCustomWriteCheckpoints() {
|
|
1109
|
+
async prepareCustomWriteCheckpoints(checkpoints) {
|
|
844
1110
|
// Most events never produce custom checkpoints, so create collections lazily
|
|
845
1111
|
// only for the event ids present in this batch. This hook runs before the
|
|
846
1112
|
// replication transaction because MongoDB cannot create indexes within it.
|
|
847
|
-
const eventIds = new Set(
|
|
1113
|
+
const eventIds = new Set(checkpoints.map((checkpoint) => this.validateCustomCheckpointEventId(checkpoint.event_id)));
|
|
848
1114
|
for (const eventId of eventIds) {
|
|
849
1115
|
if (this.initializedCustomCheckpointEventIds.has(eventId)) {
|
|
850
1116
|
continue;
|