@streamsy/core 0.1.0 → 0.2.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/dist/index.d.ts +378 -88
- package/dist/index.js +1692 -536
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,92 +1,4 @@
|
|
|
1
|
-
//#region src/
|
|
2
|
-
const systemClock = {
|
|
3
|
-
now: () => Date.now(),
|
|
4
|
-
date: (value) => new Date(value ?? Date.now())
|
|
5
|
-
};
|
|
6
|
-
|
|
7
|
-
//#endregion
|
|
8
|
-
//#region src/protocol/helpers/producer-idempotency-service.ts
|
|
9
|
-
function validateProducer(state, epoch, seq) {
|
|
10
|
-
if (!state) return seq === 0 ? {
|
|
11
|
-
kind: "accepted",
|
|
12
|
-
proposedState: {
|
|
13
|
-
epoch,
|
|
14
|
-
lastSeq: 0
|
|
15
|
-
}
|
|
16
|
-
} : {
|
|
17
|
-
kind: "gap",
|
|
18
|
-
expectedSeq: 0,
|
|
19
|
-
receivedSeq: seq
|
|
20
|
-
};
|
|
21
|
-
if (epoch < state.epoch) return {
|
|
22
|
-
kind: "stale-epoch",
|
|
23
|
-
currentEpoch: state.epoch
|
|
24
|
-
};
|
|
25
|
-
if (epoch > state.epoch) return seq === 0 ? {
|
|
26
|
-
kind: "accepted",
|
|
27
|
-
proposedState: {
|
|
28
|
-
epoch,
|
|
29
|
-
lastSeq: 0
|
|
30
|
-
}
|
|
31
|
-
} : { kind: "invalid-epoch-seq" };
|
|
32
|
-
if (seq <= state.lastSeq) return {
|
|
33
|
-
kind: "duplicate",
|
|
34
|
-
lastSeq: state.lastSeq,
|
|
35
|
-
epoch: state.epoch
|
|
36
|
-
};
|
|
37
|
-
if (seq === state.lastSeq + 1) return {
|
|
38
|
-
kind: "accepted",
|
|
39
|
-
proposedState: {
|
|
40
|
-
epoch,
|
|
41
|
-
lastSeq: seq
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
return {
|
|
45
|
-
kind: "gap",
|
|
46
|
-
expectedSeq: state.lastSeq + 1,
|
|
47
|
-
receivedSeq: seq
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
function rejectionToAppendResult(rejection, currentOffset, isClosed) {
|
|
51
|
-
switch (rejection.kind) {
|
|
52
|
-
case "duplicate": return {
|
|
53
|
-
status: "duplicate",
|
|
54
|
-
offset: currentOffset,
|
|
55
|
-
producerEpoch: rejection.epoch,
|
|
56
|
-
producerSeq: rejection.lastSeq,
|
|
57
|
-
closed: isClosed
|
|
58
|
-
};
|
|
59
|
-
case "stale-epoch": return {
|
|
60
|
-
status: "stale-epoch",
|
|
61
|
-
currentEpoch: rejection.currentEpoch
|
|
62
|
-
};
|
|
63
|
-
case "gap": return {
|
|
64
|
-
status: "producer-gap",
|
|
65
|
-
expectedSeq: rejection.expectedSeq,
|
|
66
|
-
receivedSeq: rejection.receivedSeq
|
|
67
|
-
};
|
|
68
|
-
case "invalid-epoch-seq": return { status: "invalid-epoch-seq" };
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
var ProducerIdempotencyService = class {
|
|
72
|
-
constructor(deps) {
|
|
73
|
-
this.deps = deps;
|
|
74
|
-
}
|
|
75
|
-
load(producerId) {
|
|
76
|
-
return this.deps.store.getProducerState(producerId);
|
|
77
|
-
}
|
|
78
|
-
validate(state, epoch, seq) {
|
|
79
|
-
return validateProducer(state, epoch, seq);
|
|
80
|
-
}
|
|
81
|
-
async persistIfAccepted(producer, validation) {
|
|
82
|
-
if (!producer || validation?.kind !== "accepted") return void 0;
|
|
83
|
-
await this.deps.store.setProducerState(producer.producerId, validation.proposedState);
|
|
84
|
-
return void 0;
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
//#endregion
|
|
89
|
-
//#region src/types/factory.ts
|
|
1
|
+
//#region src/types/storage-adapter.ts
|
|
90
2
|
/** Internal/storage-level unsupported-feature error. */
|
|
91
3
|
var NotSupportedError = class extends Error {
|
|
92
4
|
constructor(feature, message) {
|
|
@@ -125,6 +37,13 @@ function isNotSupported(value) {
|
|
|
125
37
|
return status === "not-supported";
|
|
126
38
|
}
|
|
127
39
|
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/protocol/helpers/clock.ts
|
|
42
|
+
const systemClock = {
|
|
43
|
+
now: () => Date.now(),
|
|
44
|
+
date: (value) => new Date(value ?? Date.now())
|
|
45
|
+
};
|
|
46
|
+
|
|
128
47
|
//#endregion
|
|
129
48
|
//#region src/protocol/helpers/content-type-matcher.ts
|
|
130
49
|
/**
|
|
@@ -139,7 +58,7 @@ function isNotSupported(value) {
|
|
|
139
58
|
*
|
|
140
59
|
* Used by `AppendService` for append content-type conflicts, by
|
|
141
60
|
* `CreateStreamService` via `configMatches` for idempotent create checks, and
|
|
142
|
-
* by `
|
|
61
|
+
* by `ForkPlanBuilder` for fork content-type compatibility.
|
|
143
62
|
*/
|
|
144
63
|
function normalizeContentType(ct) {
|
|
145
64
|
return ct.toLowerCase().split(";")[0].trim();
|
|
@@ -165,7 +84,7 @@ function contentTypeMatches(expected, actual) {
|
|
|
165
84
|
* without parameter stripping.
|
|
166
85
|
* - Invalid JSON propagates the underlying `JSON.parse` error.
|
|
167
86
|
*
|
|
168
|
-
* Used by `AppendService`, `CreateStreamService`, and `
|
|
87
|
+
* Used by `AppendService`, `CreateStreamService`, and `ForkPlanBuilder` before
|
|
169
88
|
* incoming request bodies are persisted as stored messages.
|
|
170
89
|
*/
|
|
171
90
|
function frameMessages(data, contentType) {
|
|
@@ -175,14 +94,100 @@ function frameMessages(data, contentType) {
|
|
|
175
94
|
return [new TextEncoder().encode(JSON.stringify(parsed))];
|
|
176
95
|
}
|
|
177
96
|
|
|
97
|
+
//#endregion
|
|
98
|
+
//#region src/protocol/helpers/offset-generator.ts
|
|
99
|
+
const ZERO_OFFSET = `${"0".repeat(16)}_${"0".repeat(16)}`;
|
|
100
|
+
const OFFSET_REGEX = /^\d{1,16}_\d{1,16}$/;
|
|
101
|
+
function isValidOffset(offset) {
|
|
102
|
+
return OFFSET_REGEX.test(offset);
|
|
103
|
+
}
|
|
104
|
+
function compareOffsets(a, b) {
|
|
105
|
+
return a === b ? 0 : a < b ? -1 : 1;
|
|
106
|
+
}
|
|
107
|
+
function formatCounter(counter) {
|
|
108
|
+
return `${String(counter).padStart(16, "0")}_${"0".repeat(16)}`;
|
|
109
|
+
}
|
|
110
|
+
function parseCounter(offset) {
|
|
111
|
+
return parseInt(offset.split("_")[0] ?? "0", 10);
|
|
112
|
+
}
|
|
113
|
+
function allocate(counter, count) {
|
|
114
|
+
const offsets = [];
|
|
115
|
+
for (let i = 1; i <= count; i++) offsets.push(formatCounter(counter + i));
|
|
116
|
+
const endCounter = counter + count;
|
|
117
|
+
return {
|
|
118
|
+
endCounter,
|
|
119
|
+
offsets,
|
|
120
|
+
nextOffset: count > 0 ? formatCounter(endCounter) : formatCounter(counter)
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/protocol/helpers/producer-idempotency-service.ts
|
|
126
|
+
function validateProducer(state, epoch, seq) {
|
|
127
|
+
if (!state) return seq === 0 ? {
|
|
128
|
+
kind: "accepted",
|
|
129
|
+
proposedState: {
|
|
130
|
+
epoch,
|
|
131
|
+
lastSeq: 0
|
|
132
|
+
}
|
|
133
|
+
} : {
|
|
134
|
+
kind: "gap",
|
|
135
|
+
expectedSeq: 0,
|
|
136
|
+
receivedSeq: seq
|
|
137
|
+
};
|
|
138
|
+
if (epoch < state.epoch) return {
|
|
139
|
+
kind: "stale-epoch",
|
|
140
|
+
currentEpoch: state.epoch
|
|
141
|
+
};
|
|
142
|
+
if (epoch > state.epoch) return seq === 0 ? {
|
|
143
|
+
kind: "accepted",
|
|
144
|
+
proposedState: {
|
|
145
|
+
epoch,
|
|
146
|
+
lastSeq: 0
|
|
147
|
+
}
|
|
148
|
+
} : { kind: "invalid-epoch-seq" };
|
|
149
|
+
if (seq <= state.lastSeq) return {
|
|
150
|
+
kind: "duplicate",
|
|
151
|
+
lastSeq: state.lastSeq,
|
|
152
|
+
epoch: state.epoch
|
|
153
|
+
};
|
|
154
|
+
if (seq === state.lastSeq + 1) return {
|
|
155
|
+
kind: "accepted",
|
|
156
|
+
proposedState: {
|
|
157
|
+
epoch,
|
|
158
|
+
lastSeq: seq
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
return {
|
|
162
|
+
kind: "gap",
|
|
163
|
+
expectedSeq: state.lastSeq + 1,
|
|
164
|
+
receivedSeq: seq
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function rejectionToAppendResult(rejection, currentOffset, isClosed) {
|
|
168
|
+
switch (rejection.kind) {
|
|
169
|
+
case "duplicate": return {
|
|
170
|
+
status: "duplicate",
|
|
171
|
+
offset: currentOffset,
|
|
172
|
+
producerEpoch: rejection.epoch,
|
|
173
|
+
producerSeq: rejection.lastSeq,
|
|
174
|
+
closed: isClosed
|
|
175
|
+
};
|
|
176
|
+
case "stale-epoch": return {
|
|
177
|
+
status: "stale-epoch",
|
|
178
|
+
currentEpoch: rejection.currentEpoch
|
|
179
|
+
};
|
|
180
|
+
case "gap": return {
|
|
181
|
+
status: "producer-gap",
|
|
182
|
+
expectedSeq: rejection.expectedSeq,
|
|
183
|
+
receivedSeq: rejection.receivedSeq
|
|
184
|
+
};
|
|
185
|
+
case "invalid-epoch-seq": return { status: "invalid-epoch-seq" };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
178
189
|
//#endregion
|
|
179
190
|
//#region src/protocol/append-service.ts
|
|
180
|
-
/**
|
|
181
|
-
* Mutators return the stream's post-mutation tail offset: the offset of the
|
|
182
|
-
* last message they wrote (or the unchanged tail for a body-less close). That
|
|
183
|
-
* value is both the exact appended offset and, because reads are
|
|
184
|
-
* after-exclusive, the read cursor.
|
|
185
|
-
*/
|
|
186
191
|
function appendedResult(offset, validation, closed) {
|
|
187
192
|
if (validation?.kind === "accepted") return {
|
|
188
193
|
status: "appended",
|
|
@@ -197,18 +202,6 @@ function appendedResult(offset, validation, closed) {
|
|
|
197
202
|
closed
|
|
198
203
|
};
|
|
199
204
|
}
|
|
200
|
-
/**
|
|
201
|
-
* Compare-and-swap precondition for optimistic concurrency: when
|
|
202
|
-
* `expectedOffset` is set, the append proceeds only if the stream's tail
|
|
203
|
-
* still equals it. Atomicity with the mutation is guaranteed because the
|
|
204
|
-
* protocol loads the record and runs this service inside the per-stream
|
|
205
|
-
* mutation lock.
|
|
206
|
-
*
|
|
207
|
-
* Pinned precedence: checked after the closed/content-type/sequence conflicts
|
|
208
|
-
* and before any mutation, so a CAS failure never advances producer state.
|
|
209
|
-
* A close-only append on an already-closed stream stays an idempotent
|
|
210
|
-
* success and skips the check (nothing is written, so no update can be lost).
|
|
211
|
-
*/
|
|
212
205
|
function expectedOffsetConflict(record, options) {
|
|
213
206
|
if (options.expectedOffset === void 0 || options.expectedOffset === record.currentOffset) return null;
|
|
214
207
|
return {
|
|
@@ -221,83 +214,116 @@ var AppendService = class {
|
|
|
221
214
|
constructor(deps) {
|
|
222
215
|
this.deps = deps;
|
|
223
216
|
}
|
|
224
|
-
|
|
225
|
-
if (!record) return {
|
|
226
|
-
|
|
217
|
+
plan(record, options, producerState) {
|
|
218
|
+
if (!record) return {
|
|
219
|
+
kind: "terminal",
|
|
220
|
+
result: { status: "not-found" }
|
|
221
|
+
};
|
|
222
|
+
if (record.lifecycle.softDeleted) return {
|
|
223
|
+
kind: "terminal",
|
|
224
|
+
result: { status: "gone" }
|
|
225
|
+
};
|
|
227
226
|
const isClosed = record.lifecycle.closed === true;
|
|
228
227
|
const wantClose = options.close === true;
|
|
229
228
|
const hasBody = options.data.byteLength > 0;
|
|
230
229
|
let producerValidation;
|
|
231
230
|
if (options.producer) {
|
|
232
|
-
|
|
233
|
-
if (
|
|
234
|
-
|
|
235
|
-
|
|
231
|
+
producerValidation = validateProducer(producerState, options.producer.producerEpoch, options.producer.producerSeq);
|
|
232
|
+
if (producerValidation.kind !== "accepted") return {
|
|
233
|
+
kind: "terminal",
|
|
234
|
+
result: rejectionToAppendResult(producerValidation, record.currentOffset, isClosed)
|
|
235
|
+
};
|
|
236
236
|
}
|
|
237
237
|
if (wantClose && !hasBody) {
|
|
238
238
|
if (isClosed) return {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
239
|
+
kind: "terminal",
|
|
240
|
+
result: {
|
|
241
|
+
status: "appended",
|
|
242
|
+
offset: record.currentOffset,
|
|
243
|
+
closed: true
|
|
244
|
+
}
|
|
242
245
|
};
|
|
243
246
|
const casConflict$1 = expectedOffsetConflict(record, options);
|
|
244
|
-
if (casConflict$1) return
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
return
|
|
247
|
+
if (casConflict$1) return {
|
|
248
|
+
kind: "terminal",
|
|
249
|
+
result: casConflict$1
|
|
250
|
+
};
|
|
251
|
+
return this.commitDecision(record, [], options, producerState, producerValidation, true);
|
|
249
252
|
}
|
|
250
253
|
if (isClosed) return {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
254
|
+
kind: "terminal",
|
|
255
|
+
result: {
|
|
256
|
+
status: "conflict",
|
|
257
|
+
conflictReason: "closed",
|
|
258
|
+
closed: true,
|
|
259
|
+
offset: record.currentOffset
|
|
260
|
+
}
|
|
255
261
|
};
|
|
256
262
|
if (!contentTypeMatches(record.config.contentType, options.contentType)) return {
|
|
257
|
-
|
|
258
|
-
|
|
263
|
+
kind: "terminal",
|
|
264
|
+
result: {
|
|
265
|
+
status: "conflict",
|
|
266
|
+
conflictReason: "content-type"
|
|
267
|
+
}
|
|
259
268
|
};
|
|
260
269
|
if (options.seq && record.lifecycle.lastSeq && options.seq <= record.lifecycle.lastSeq) return {
|
|
261
|
-
|
|
262
|
-
|
|
270
|
+
kind: "terminal",
|
|
271
|
+
result: {
|
|
272
|
+
status: "conflict",
|
|
273
|
+
conflictReason: "sequence"
|
|
274
|
+
}
|
|
263
275
|
};
|
|
264
276
|
const casConflict = expectedOffsetConflict(record, options);
|
|
265
|
-
if (casConflict) return
|
|
277
|
+
if (casConflict) return {
|
|
278
|
+
kind: "terminal",
|
|
279
|
+
result: casConflict
|
|
280
|
+
};
|
|
266
281
|
const processed = frameMessages(options.data, record.config.contentType);
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
282
|
+
return this.commitDecision(record, processed, options, producerState, producerValidation, wantClose);
|
|
283
|
+
}
|
|
284
|
+
commitDecision(record, data, options, producerState, producerValidation, wantClose) {
|
|
285
|
+
const allocation = allocate(record.counter, data.length);
|
|
286
|
+
const now = this.deps.clock.now();
|
|
287
|
+
const messages = data.map((bytes, i) => ({
|
|
288
|
+
data: bytes,
|
|
289
|
+
offset: allocation.offsets[i],
|
|
290
|
+
timestamp: now
|
|
291
|
+
}));
|
|
292
|
+
const expiresAtMs = record.config.ttlSeconds === void 0 ? void 0 : now + record.config.ttlSeconds * 1e3;
|
|
293
|
+
const lifecycle = {
|
|
294
|
+
...options.seq ? { lastSeq: options.seq } : {},
|
|
295
|
+
...wantClose ? {
|
|
296
|
+
closed: true,
|
|
297
|
+
closedAt: now
|
|
298
|
+
} : {},
|
|
299
|
+
...expiresAtMs !== void 0 ? { expiresAtMs } : {}
|
|
300
|
+
};
|
|
301
|
+
const plan = {
|
|
302
|
+
preconditions: {
|
|
303
|
+
expectedOffset: options.expectedOffset ?? record.currentOffset,
|
|
304
|
+
expectedClosed: false,
|
|
305
|
+
...options.producer && producerValidation?.kind === "accepted" ? { producer: {
|
|
306
|
+
producerId: options.producer.producerId,
|
|
307
|
+
expected: producerState,
|
|
308
|
+
next: producerValidation.proposedState
|
|
309
|
+
} } : {}
|
|
310
|
+
},
|
|
311
|
+
messages,
|
|
312
|
+
recordPatch: {
|
|
313
|
+
currentOffset: allocation.nextOffset,
|
|
314
|
+
counter: allocation.endCounter,
|
|
315
|
+
lifecycle
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
return {
|
|
319
|
+
kind: "append",
|
|
320
|
+
plan,
|
|
321
|
+
afterCommit: expiresAtMs !== void 0 ? { scheduleExpiryAt: expiresAtMs } : {},
|
|
322
|
+
toResult: () => appendedResult(allocation.nextOffset, producerValidation, wantClose)
|
|
323
|
+
};
|
|
271
324
|
}
|
|
272
325
|
};
|
|
273
326
|
|
|
274
|
-
//#endregion
|
|
275
|
-
//#region src/protocol/helpers/offset-generator.ts
|
|
276
|
-
const ZERO_OFFSET = `${"0".repeat(16)}_${"0".repeat(16)}`;
|
|
277
|
-
const OFFSET_REGEX = /^\d{1,16}_\d{1,16}$/;
|
|
278
|
-
function isValidOffset(offset) {
|
|
279
|
-
return OFFSET_REGEX.test(offset);
|
|
280
|
-
}
|
|
281
|
-
function compareOffsets(a, b) {
|
|
282
|
-
return a === b ? 0 : a < b ? -1 : 1;
|
|
283
|
-
}
|
|
284
|
-
function formatCounter(counter) {
|
|
285
|
-
return `${String(counter).padStart(16, "0")}_${"0".repeat(16)}`;
|
|
286
|
-
}
|
|
287
|
-
function parseCounter(offset) {
|
|
288
|
-
return parseInt(offset.split("_")[0] ?? "0", 10);
|
|
289
|
-
}
|
|
290
|
-
function allocate(counter, count) {
|
|
291
|
-
const offsets = [];
|
|
292
|
-
for (let i = 1; i <= count; i++) offsets.push(formatCounter(counter + i));
|
|
293
|
-
const endCounter = counter + count;
|
|
294
|
-
return {
|
|
295
|
-
endCounter,
|
|
296
|
-
offsets,
|
|
297
|
-
nextOffset: count > 0 ? formatCounter(endCounter) : formatCounter(counter)
|
|
298
|
-
};
|
|
299
|
-
}
|
|
300
|
-
|
|
301
327
|
//#endregion
|
|
302
328
|
//#region src/protocol/read-service.ts
|
|
303
329
|
function normalizeReadOffset(offset) {
|
|
@@ -336,6 +362,32 @@ function generateCursor(clock, previous, random = Math.random) {
|
|
|
336
362
|
return String(previousInterval + Math.max(1, Math.floor(random() * 180)));
|
|
337
363
|
}
|
|
338
364
|
|
|
365
|
+
//#endregion
|
|
366
|
+
//#region src/protocol/helpers/race-abort.ts
|
|
367
|
+
function raceAbortAwaitChange(wait, fallbackSnapshot, signal) {
|
|
368
|
+
if (!signal) return wait;
|
|
369
|
+
const timeoutResult = {
|
|
370
|
+
status: "timeout",
|
|
371
|
+
snapshot: fallbackSnapshot
|
|
372
|
+
};
|
|
373
|
+
if (signal.aborted) return Promise.resolve(timeoutResult);
|
|
374
|
+
return new Promise((resolve, reject) => {
|
|
375
|
+
const onAbort = () => {
|
|
376
|
+
cleanup();
|
|
377
|
+
resolve(timeoutResult);
|
|
378
|
+
};
|
|
379
|
+
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
380
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
381
|
+
wait.then((result) => {
|
|
382
|
+
cleanup();
|
|
383
|
+
resolve(result);
|
|
384
|
+
}, (error) => {
|
|
385
|
+
cleanup();
|
|
386
|
+
reject(error);
|
|
387
|
+
});
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
|
|
339
391
|
//#endregion
|
|
340
392
|
//#region src/protocol/live-read-service.ts
|
|
341
393
|
var LiveReadService = class {
|
|
@@ -381,18 +433,26 @@ var LiveReadService = class {
|
|
|
381
433
|
cursor: generateCursor(this.deps.clock, options.cursor)
|
|
382
434
|
};
|
|
383
435
|
}
|
|
384
|
-
|
|
385
|
-
const immediate = await this.deps.readOwn(
|
|
436
|
+
const fromOffset = isValidOffset(options.offset) ? options.offset : ZERO_OFFSET;
|
|
437
|
+
const immediate = await this.deps.readOwn(fromOffset);
|
|
386
438
|
if (immediate.messages.length > 0) return {
|
|
387
439
|
status: "ok",
|
|
388
440
|
...immediate,
|
|
389
441
|
upToDate: true,
|
|
390
442
|
cursor: generateCursor(this.deps.clock, options.cursor)
|
|
391
443
|
};
|
|
392
|
-
const
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
444
|
+
const observed = {
|
|
445
|
+
present: true,
|
|
446
|
+
currentOffset: record.currentOffset,
|
|
447
|
+
closed: false,
|
|
448
|
+
softDeleted: false
|
|
449
|
+
};
|
|
450
|
+
const wait = await raceAbortAwaitChange(this.deps.store.awaitChange({
|
|
451
|
+
fromOffset,
|
|
452
|
+
observedClosed: observed.closed,
|
|
453
|
+
observedSoftDeleted: observed.softDeleted,
|
|
454
|
+
timeoutMs: this.deps.longPollTimeoutMs
|
|
455
|
+
}), observed, options.signal);
|
|
396
456
|
const latest = await this.deps.store.getRecord();
|
|
397
457
|
if (!latest) return {
|
|
398
458
|
status: "not-found",
|
|
@@ -408,11 +468,11 @@ var LiveReadService = class {
|
|
|
408
468
|
upToDate: false,
|
|
409
469
|
cursor: ""
|
|
410
470
|
};
|
|
411
|
-
const r = await this.deps.readOwn(
|
|
471
|
+
const r = await this.deps.readOwn(fromOffset);
|
|
412
472
|
const reachedTail = r.nextOffset === latest.currentOffset;
|
|
413
473
|
const hasMessages = r.messages.length > 0;
|
|
414
474
|
return {
|
|
415
|
-
status: hasMessages ? "ok" : wait.status === "timeout"
|
|
475
|
+
status: hasMessages ? "ok" : wait.status === "timeout" ? "timeout" : "ok",
|
|
416
476
|
messages: r.messages,
|
|
417
477
|
nextOffset: r.nextOffset,
|
|
418
478
|
upToDate: true,
|
|
@@ -422,6 +482,39 @@ var LiveReadService = class {
|
|
|
422
482
|
}
|
|
423
483
|
};
|
|
424
484
|
|
|
485
|
+
//#endregion
|
|
486
|
+
//#region src/protocol/helpers/bind-stream.ts
|
|
487
|
+
function bindStream(adapter, id) {
|
|
488
|
+
return {
|
|
489
|
+
id,
|
|
490
|
+
getRecord: () => adapter.getRecord(id),
|
|
491
|
+
listMessages: (options) => adapter.listMessages(id, options),
|
|
492
|
+
getProducerState: (producerId) => adapter.getProducerState(id, producerId),
|
|
493
|
+
append: (plan) => adapter.append(id, plan),
|
|
494
|
+
awaitChange: (options) => adapter.awaitChange(id, options),
|
|
495
|
+
scheduleExpiry: (at) => adapter.scheduleExpiry(id, at),
|
|
496
|
+
cancelExpiry: () => adapter.cancelExpiry(id)
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
//#endregion
|
|
501
|
+
//#region src/protocol/helpers/after-commit-effects.ts
|
|
502
|
+
/**
|
|
503
|
+
* Runtime effects that are safe to fire only after the durable mutation has
|
|
504
|
+
* committed. Storage adapters persist each intent atomically; core owns expiry
|
|
505
|
+
* scheduling so failed preconditions never fire timers.
|
|
506
|
+
*
|
|
507
|
+
* Waking live readers is not an after-commit effect: the level-triggered
|
|
508
|
+
* `awaitChange` seam re-reads durable state, so an adapter wakes its own waiters
|
|
509
|
+
* from inside a successful mutation (a pure latency optimization). Correctness
|
|
510
|
+
* never depends on a notification crossing the seam.
|
|
511
|
+
*/
|
|
512
|
+
async function runAfterCommit(effects, storage) {
|
|
513
|
+
if (!effects) return;
|
|
514
|
+
if (effects.cancelExpiry) await storage.cancelExpiry();
|
|
515
|
+
else if (effects.scheduleExpiryAt !== void 0) await storage.scheduleExpiry(effects.scheduleExpiryAt);
|
|
516
|
+
}
|
|
517
|
+
|
|
425
518
|
//#endregion
|
|
426
519
|
//#region src/protocol/helpers/expiry-policy.ts
|
|
427
520
|
var ExpiryPolicy = class {
|
|
@@ -434,17 +527,22 @@ var ExpiryPolicy = class {
|
|
|
434
527
|
return void 0;
|
|
435
528
|
}
|
|
436
529
|
async touch(stream, record, reason) {
|
|
437
|
-
if (record.config.ttlSeconds === void 0) return;
|
|
438
|
-
if (reason === "live-read") return;
|
|
530
|
+
if (record.config.ttlSeconds === void 0) return record;
|
|
531
|
+
if (reason === "live-read") return record;
|
|
439
532
|
const expiresAtMs = this.deps.clock.now() + record.config.ttlSeconds * 1e3;
|
|
440
|
-
await stream.
|
|
441
|
-
|
|
533
|
+
const out = await stream.append({
|
|
534
|
+
preconditions: { expectedOffset: record.currentOffset },
|
|
535
|
+
recordPatch: { lifecycle: { expiresAtMs } }
|
|
536
|
+
});
|
|
537
|
+
if (out.status !== "appended") return record;
|
|
538
|
+
await runAfterCommit({ scheduleExpiryAt: expiresAtMs }, stream);
|
|
539
|
+
return out.record;
|
|
442
540
|
}
|
|
443
541
|
async scheduleExpiry(record) {
|
|
444
542
|
const at = record.lifecycle.expiresAtMs;
|
|
445
543
|
if (at !== void 0) {
|
|
446
544
|
const stream = await this.deps.resolve(record.id);
|
|
447
|
-
await stream.scheduleExpiry(at
|
|
545
|
+
await stream.scheduleExpiry(at);
|
|
448
546
|
}
|
|
449
547
|
}
|
|
450
548
|
/**
|
|
@@ -475,6 +573,7 @@ function configMatches(existing, options) {
|
|
|
475
573
|
if (!contentTypeMatches(existing.config.contentType, contentType)) return false;
|
|
476
574
|
if ((options.forkedFrom ?? void 0) !== existing.lifecycle.forkedFrom) return false;
|
|
477
575
|
if (options.forkOffset !== void 0 && options.forkOffset !== existing.lifecycle.forkOffset) return false;
|
|
576
|
+
if ((options.forkSubOffset ?? 0) !== (existing.lifecycle.forkSubOffset ?? 0)) return false;
|
|
478
577
|
const inheritedForkExpiry = options.forkedFrom && options.ttlSeconds === void 0 && options.expiresAt === void 0;
|
|
479
578
|
if (existing.config.ttlSeconds !== options.ttlSeconds && !inheritedForkExpiry) return false;
|
|
480
579
|
if (existing.config.expiresAt !== options.expiresAt && !inheritedForkExpiry) return false;
|
|
@@ -487,27 +586,31 @@ var CreateStreamService = class {
|
|
|
487
586
|
constructor(deps) {
|
|
488
587
|
this.deps = deps;
|
|
489
588
|
}
|
|
490
|
-
|
|
491
|
-
if (record) return
|
|
492
|
-
|
|
589
|
+
plan(record, options) {
|
|
590
|
+
if (record) return {
|
|
591
|
+
kind: "terminal",
|
|
592
|
+
result: this.resultForExisting(record, options)
|
|
593
|
+
};
|
|
594
|
+
if (options.forkedFrom) return { kind: "fork" };
|
|
493
595
|
const contentType = options.contentType ?? "application/octet-stream";
|
|
494
|
-
const initialMessages =
|
|
596
|
+
const initialMessages = this.initialMessages(options.initialData, contentType, 0);
|
|
495
597
|
const wantClosed = options.closed === true;
|
|
496
|
-
const newRecord = this.deps.
|
|
497
|
-
const
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
if (wantClosed) {
|
|
503
|
-
const latest = await this.deps.store.getRecord() ?? newRecord;
|
|
504
|
-
final = await this.deps.mutators.closeRecord(latest, []);
|
|
505
|
-
}
|
|
598
|
+
const newRecord$1 = this.deps.newRecord(contentType, options);
|
|
599
|
+
const finalRecord = this.withInitialTail(newRecord$1, initialMessages, wantClosed);
|
|
600
|
+
const plan = {
|
|
601
|
+
record: finalRecord,
|
|
602
|
+
initialMessages
|
|
603
|
+
};
|
|
506
604
|
return {
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
605
|
+
kind: "create",
|
|
606
|
+
plan,
|
|
607
|
+
afterCommit: finalRecord.lifecycle.expiresAtMs !== void 0 ? { scheduleExpiryAt: finalRecord.lifecycle.expiresAtMs } : {},
|
|
608
|
+
toResult: (created) => ({
|
|
609
|
+
status: "created",
|
|
610
|
+
nextOffset: created.currentOffset,
|
|
611
|
+
contentType,
|
|
612
|
+
closed: wantClosed
|
|
613
|
+
})
|
|
511
614
|
};
|
|
512
615
|
}
|
|
513
616
|
resultForExisting(existing, options) {
|
|
@@ -530,10 +633,35 @@ var CreateStreamService = class {
|
|
|
530
633
|
closed: existing.lifecycle.closed === true
|
|
531
634
|
};
|
|
532
635
|
}
|
|
636
|
+
initialMessages(initialData, contentType, startCounter) {
|
|
637
|
+
const framed = initialData ? frameMessages(initialData, contentType) : [];
|
|
638
|
+
const allocation = allocate(startCounter, framed.length);
|
|
639
|
+
const now = this.deps.clock.now();
|
|
640
|
+
return framed.map((data, i) => ({
|
|
641
|
+
data,
|
|
642
|
+
offset: allocation.offsets[i],
|
|
643
|
+
timestamp: now
|
|
644
|
+
}));
|
|
645
|
+
}
|
|
646
|
+
withInitialTail(record, initialMessages, closed) {
|
|
647
|
+
const allocation = allocate(record.counter, initialMessages.length);
|
|
648
|
+
return {
|
|
649
|
+
...record,
|
|
650
|
+
currentOffset: allocation.nextOffset,
|
|
651
|
+
counter: allocation.endCounter,
|
|
652
|
+
lifecycle: {
|
|
653
|
+
...record.lifecycle,
|
|
654
|
+
...closed ? {
|
|
655
|
+
closed: true,
|
|
656
|
+
closedAt: this.deps.clock.now()
|
|
657
|
+
} : {}
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
}
|
|
533
661
|
};
|
|
534
662
|
|
|
535
663
|
//#endregion
|
|
536
|
-
//#region src/protocol/helpers/fork-
|
|
664
|
+
//#region src/protocol/helpers/fork-plan-builder.ts
|
|
537
665
|
function resolveForkExpiry(opts, source) {
|
|
538
666
|
if (opts.ttlSeconds !== void 0) return { ttlSeconds: opts.ttlSeconds };
|
|
539
667
|
if (opts.expiresAt) return { expiresAt: opts.expiresAt };
|
|
@@ -541,121 +669,154 @@ function resolveForkExpiry(opts, source) {
|
|
|
541
669
|
if (source.config.expiresAt) return { expiresAt: source.config.expiresAt };
|
|
542
670
|
return {};
|
|
543
671
|
}
|
|
544
|
-
var
|
|
672
|
+
var ForkPlanBuilder = class {
|
|
545
673
|
constructor(deps) {
|
|
546
674
|
this.deps = deps;
|
|
547
675
|
}
|
|
548
|
-
|
|
549
|
-
const sourcePath = options.forkedFrom;
|
|
550
|
-
const sourceStream = await this.deps.resolve(sourcePath);
|
|
551
|
-
await this.deps.mutators.expireIfNeeded(sourceStream);
|
|
552
|
-
const source = await sourceStream.getRecord();
|
|
676
|
+
build(targetId, sourcePath, source, options, sourceTail) {
|
|
553
677
|
if (!source) return {
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
678
|
+
kind: "terminal",
|
|
679
|
+
result: {
|
|
680
|
+
status: "not-found",
|
|
681
|
+
nextOffset: "",
|
|
682
|
+
contentType: "",
|
|
683
|
+
errorMessage: `Source stream not found: ${sourcePath}`
|
|
684
|
+
}
|
|
558
685
|
};
|
|
559
686
|
if (source.lifecycle.softDeleted) return {
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
687
|
+
kind: "terminal",
|
|
688
|
+
result: {
|
|
689
|
+
status: "conflict",
|
|
690
|
+
nextOffset: "",
|
|
691
|
+
contentType: "",
|
|
692
|
+
conflictReason: "fork-source-soft-deleted",
|
|
693
|
+
errorMessage: `Source stream is soft-deleted: ${sourcePath}`
|
|
694
|
+
}
|
|
565
695
|
};
|
|
566
696
|
const forkOffset = options.forkOffset ?? source.currentOffset;
|
|
567
697
|
if (!isValidOffset(forkOffset)) return {
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
698
|
+
kind: "terminal",
|
|
699
|
+
result: {
|
|
700
|
+
status: "bad-request",
|
|
701
|
+
nextOffset: "",
|
|
702
|
+
contentType: "",
|
|
703
|
+
errorMessage: "Invalid Stream-Fork-Offset format"
|
|
704
|
+
}
|
|
572
705
|
};
|
|
573
706
|
if (compareOffsets(forkOffset, ZERO_OFFSET) < 0 || compareOffsets(forkOffset, source.currentOffset) > 0) return {
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
707
|
+
kind: "terminal",
|
|
708
|
+
result: {
|
|
709
|
+
status: "bad-request",
|
|
710
|
+
nextOffset: "",
|
|
711
|
+
contentType: "",
|
|
712
|
+
errorMessage: "Stream-Fork-Offset exceeds source tail"
|
|
713
|
+
}
|
|
578
714
|
};
|
|
579
715
|
let contentType = options.contentType;
|
|
580
716
|
if (!contentType || contentType.trim() === "") contentType = source.config.contentType;
|
|
581
717
|
else if (!contentTypeMatches(contentType, source.config.contentType)) return {
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
718
|
+
kind: "terminal",
|
|
719
|
+
result: {
|
|
720
|
+
status: "conflict",
|
|
721
|
+
nextOffset: "",
|
|
722
|
+
contentType: "",
|
|
723
|
+
conflictReason: "fork-content-type",
|
|
724
|
+
errorMessage: "Fork Content-Type does not match source"
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
const subOffset = options.forkSubOffset;
|
|
728
|
+
const prefix = this.materializePrefix(subOffset, contentType, sourceTail);
|
|
729
|
+
if (!prefix.ok) return {
|
|
730
|
+
kind: "terminal",
|
|
731
|
+
result: {
|
|
732
|
+
status: "bad-request",
|
|
733
|
+
nextOffset: "",
|
|
734
|
+
contentType: "",
|
|
735
|
+
errorMessage: prefix.errorMessage
|
|
736
|
+
}
|
|
587
737
|
};
|
|
588
738
|
const expiry = resolveForkExpiry(options, source);
|
|
589
|
-
const
|
|
739
|
+
const baseRecord = this.deps.newRecord(targetId, contentType, {
|
|
590
740
|
...options,
|
|
591
741
|
...expiry
|
|
592
742
|
}, {
|
|
593
743
|
forkedFrom: sourcePath,
|
|
594
|
-
forkOffset
|
|
744
|
+
forkOffset,
|
|
745
|
+
...subOffset !== void 0 && subOffset > 0 ? { forkSubOffset: subOffset } : {}
|
|
595
746
|
});
|
|
596
|
-
const initialMessages =
|
|
597
|
-
const
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
conflictReason: "config-mismatch",
|
|
604
|
-
errorMessage: `Stream already exists: ${targetStream.id}`
|
|
747
|
+
const initialMessages = this.initialMessages(prefix.messages, options.initialData, contentType, baseRecord.counter);
|
|
748
|
+
const child = this.withInitialTail(baseRecord, initialMessages);
|
|
749
|
+
const plan = {
|
|
750
|
+
child,
|
|
751
|
+
sourceId: sourcePath,
|
|
752
|
+
initialMessages,
|
|
753
|
+
precondition: { sourceLiveAtOffset: forkOffset }
|
|
605
754
|
};
|
|
606
|
-
await this.deps.mutators.scheduleExpiry(record);
|
|
607
|
-
let final = record.currentOffset;
|
|
608
|
-
if (initialMessages.length > 0) final = await this.deps.mutators.appendMessages(record, initialMessages);
|
|
609
755
|
return {
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
756
|
+
kind: "fork",
|
|
757
|
+
plan,
|
|
758
|
+
afterCommit: child.lifecycle.expiresAtMs !== void 0 ? { scheduleExpiryAt: child.lifecycle.expiresAtMs } : {},
|
|
759
|
+
toResult: (record) => ({
|
|
760
|
+
status: "created",
|
|
761
|
+
nextOffset: record.currentOffset,
|
|
762
|
+
contentType
|
|
763
|
+
})
|
|
613
764
|
};
|
|
614
765
|
}
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
766
|
+
/**
|
|
767
|
+
* Materialize the partial-message prefix addressed by `forkSubOffset` from the
|
|
768
|
+
* source messages that follow `forkOffset`. `0`/absent yields no prefix. For
|
|
769
|
+
* JSON the sub-offset counts whole flattened messages; for binary/text it
|
|
770
|
+
* counts bytes within the single next source message. Overshoot or an empty
|
|
771
|
+
* source is a 400.
|
|
772
|
+
*/
|
|
773
|
+
materializePrefix(subOffset, contentType, sourceTail) {
|
|
774
|
+
if (subOffset === void 0 || subOffset === 0) return {
|
|
775
|
+
ok: true,
|
|
776
|
+
messages: []
|
|
777
|
+
};
|
|
778
|
+
const tail = sourceTail ?? [];
|
|
779
|
+
if (contentType.toLowerCase().startsWith("application/json")) {
|
|
780
|
+
if (subOffset > tail.length) return {
|
|
781
|
+
ok: false,
|
|
782
|
+
errorMessage: "Stream-Fork-Sub-Offset exceeds source message count"
|
|
783
|
+
};
|
|
784
|
+
return {
|
|
785
|
+
ok: true,
|
|
786
|
+
messages: tail.slice(0, subOffset).map((m) => m.data)
|
|
787
|
+
};
|
|
631
788
|
}
|
|
632
|
-
|
|
633
|
-
return {
|
|
789
|
+
const first = tail[0];
|
|
790
|
+
if (!first) return {
|
|
791
|
+
ok: false,
|
|
792
|
+
errorMessage: "Stream-Fork-Sub-Offset has no source message to fork"
|
|
793
|
+
};
|
|
794
|
+
if (subOffset > first.data.byteLength) return {
|
|
795
|
+
ok: false,
|
|
796
|
+
errorMessage: "Stream-Fork-Sub-Offset exceeds source message length"
|
|
797
|
+
};
|
|
798
|
+
return {
|
|
799
|
+
ok: true,
|
|
800
|
+
messages: [first.data.subarray(0, subOffset)]
|
|
801
|
+
};
|
|
634
802
|
}
|
|
635
|
-
|
|
636
|
-
const
|
|
637
|
-
const
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
await stream.notify("deleted");
|
|
653
|
-
const parentId = record.lifecycle.forkedFrom;
|
|
654
|
-
if (!parentId) return;
|
|
655
|
-
const parentStream = await this.deps.resolve(parentId);
|
|
656
|
-
const newRefCount = await parentStream.decrementChildRefCount();
|
|
657
|
-
const parent = await parentStream.getRecord();
|
|
658
|
-
if (parent && newRefCount === 0 && parent.lifecycle.softDeleted) await this.purgeWithCascade(parentStream, parent);
|
|
803
|
+
initialMessages(prefix, initialData, contentType, startCounter) {
|
|
804
|
+
const framed = [...prefix, ...initialData ? frameMessages(initialData, contentType) : []];
|
|
805
|
+
const allocation = allocate(startCounter, framed.length);
|
|
806
|
+
const now = this.deps.clock.now();
|
|
807
|
+
return framed.map((data, i) => ({
|
|
808
|
+
data,
|
|
809
|
+
offset: allocation.offsets[i],
|
|
810
|
+
timestamp: now
|
|
811
|
+
}));
|
|
812
|
+
}
|
|
813
|
+
withInitialTail(record, initialMessages) {
|
|
814
|
+
const allocation = allocate(record.counter, initialMessages.length);
|
|
815
|
+
return {
|
|
816
|
+
...record,
|
|
817
|
+
currentOffset: allocation.nextOffset,
|
|
818
|
+
counter: allocation.endCounter
|
|
819
|
+
};
|
|
659
820
|
}
|
|
660
821
|
};
|
|
661
822
|
|
|
@@ -670,16 +831,17 @@ var StreamMessageReader = class {
|
|
|
670
831
|
}
|
|
671
832
|
async readChainFor(stream, record, afterOffset, capOffset, touchOwnTtl = true) {
|
|
672
833
|
const out = [];
|
|
673
|
-
|
|
674
|
-
|
|
834
|
+
let current = record;
|
|
835
|
+
if (current.lifecycle.forkedFrom && current.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, current.lifecycle.forkOffset) < 0)) {
|
|
836
|
+
const sourceStream = await this.deps.resolve(current.lifecycle.forkedFrom);
|
|
675
837
|
const source = await sourceStream.getRecord();
|
|
676
838
|
if (source) {
|
|
677
|
-
const upstreamCap = capOffset && compareOffsets(capOffset,
|
|
839
|
+
const upstreamCap = capOffset && compareOffsets(capOffset, current.lifecycle.forkOffset) < 0 ? capOffset : current.lifecycle.forkOffset;
|
|
678
840
|
out.push(...await this.readChainFor(sourceStream, source, afterOffset, upstreamCap, false));
|
|
679
841
|
}
|
|
680
842
|
}
|
|
681
|
-
if (touchOwnTtl) await this.deps.expiryPolicy.touch(stream,
|
|
682
|
-
const ownStart =
|
|
843
|
+
if (touchOwnTtl) current = await this.deps.expiryPolicy.touch(stream, current, "read");
|
|
844
|
+
const ownStart = current.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, current.lifecycle.forkOffset) < 0) ? current.lifecycle.forkOffset : afterOffset;
|
|
683
845
|
const own = await stream.listMessages({
|
|
684
846
|
after: ownStart,
|
|
685
847
|
until: capOffset
|
|
@@ -695,58 +857,21 @@ var StreamMessageReader = class {
|
|
|
695
857
|
nextOffset: ""
|
|
696
858
|
};
|
|
697
859
|
const messages = await stream.listMessages({ after });
|
|
860
|
+
if (messages.length > 0) return {
|
|
861
|
+
messages,
|
|
862
|
+
nextOffset: messages[messages.length - 1].offset
|
|
863
|
+
};
|
|
864
|
+
if (after !== void 0 && compareOffsets(after, record.currentOffset) < 0) return {
|
|
865
|
+
messages,
|
|
866
|
+
nextOffset: after
|
|
867
|
+
};
|
|
698
868
|
return {
|
|
699
869
|
messages,
|
|
700
|
-
nextOffset:
|
|
870
|
+
nextOffset: record.currentOffset
|
|
701
871
|
};
|
|
702
872
|
}
|
|
703
873
|
};
|
|
704
874
|
|
|
705
|
-
//#endregion
|
|
706
|
-
//#region src/protocol/storage/stream-message-writer.ts
|
|
707
|
-
var StreamMessageWriter = class {
|
|
708
|
-
constructor(deps) {
|
|
709
|
-
this.deps = deps;
|
|
710
|
-
}
|
|
711
|
-
async appendMessages(record, data, seq) {
|
|
712
|
-
await this.deps.expiryPolicy.touch(this.deps.stream, record, "append");
|
|
713
|
-
const allocation = allocate(record.counter, data.length);
|
|
714
|
-
const now = this.deps.clock.now();
|
|
715
|
-
const messages = data.map((bytes, i) => ({
|
|
716
|
-
data: bytes,
|
|
717
|
-
offset: allocation.offsets[i],
|
|
718
|
-
timestamp: now
|
|
719
|
-
}));
|
|
720
|
-
if (messages.length > 0) await this.deps.stream.appendMessages(messages);
|
|
721
|
-
await this.deps.stream.updateRecord({
|
|
722
|
-
currentOffset: allocation.nextOffset,
|
|
723
|
-
counter: allocation.endCounter,
|
|
724
|
-
lifecycle: seq ? { lastSeq: seq } : void 0
|
|
725
|
-
});
|
|
726
|
-
await this.deps.stream.notify("message");
|
|
727
|
-
return allocation.nextOffset;
|
|
728
|
-
}
|
|
729
|
-
async closeRecord(record, data, seq) {
|
|
730
|
-
let latest = record;
|
|
731
|
-
let nextOffset = record.currentOffset;
|
|
732
|
-
if (data.length > 0) {
|
|
733
|
-
nextOffset = await this.appendMessages(record, data, seq);
|
|
734
|
-
latest = await this.deps.stream.getRecord() ?? record;
|
|
735
|
-
} else await this.deps.expiryPolicy.touch(this.deps.stream, record, "close");
|
|
736
|
-
await this.deps.stream.updateRecord({
|
|
737
|
-
lifecycle: {
|
|
738
|
-
closed: true,
|
|
739
|
-
closedAt: this.deps.clock.now(),
|
|
740
|
-
...seq ? { lastSeq: seq } : {}
|
|
741
|
-
},
|
|
742
|
-
currentOffset: nextOffset,
|
|
743
|
-
counter: latest.counter
|
|
744
|
-
});
|
|
745
|
-
await this.deps.stream.notify("closed");
|
|
746
|
-
return nextOffset;
|
|
747
|
-
}
|
|
748
|
-
};
|
|
749
|
-
|
|
750
875
|
//#endregion
|
|
751
876
|
//#region src/protocol/storage/stream-record-factory.ts
|
|
752
877
|
var StreamRecordFactory = class {
|
|
@@ -765,9 +890,9 @@ var StreamRecordFactory = class {
|
|
|
765
890
|
id: streamId,
|
|
766
891
|
config,
|
|
767
892
|
lifecycle: {
|
|
768
|
-
childRefCount: 0,
|
|
769
893
|
forkedFrom: fork?.forkedFrom,
|
|
770
894
|
forkOffset,
|
|
895
|
+
...fork?.forkSubOffset !== void 0 && fork.forkSubOffset > 0 ? { forkSubOffset: fork.forkSubOffset } : {},
|
|
771
896
|
expiresAtMs: this.deps.expiryPolicy.computeExpiresAtMs(config)
|
|
772
897
|
},
|
|
773
898
|
currentOffset: forkOffset ?? ZERO_OFFSET,
|
|
@@ -779,78 +904,104 @@ var StreamRecordFactory = class {
|
|
|
779
904
|
//#endregion
|
|
780
905
|
//#region src/protocol.ts
|
|
781
906
|
const LONG_POLL_TIMEOUT_MS = 1500;
|
|
907
|
+
const MAX_COMMIT_ATTEMPTS = 8;
|
|
908
|
+
const MAX_NO_PROGRESS_ATTEMPTS = 8;
|
|
782
909
|
function createStreamProtocol(deps) {
|
|
783
910
|
return new StreamProtocol(deps);
|
|
784
911
|
}
|
|
912
|
+
async function runDeleteEffects(status, storage) {
|
|
913
|
+
if (status === "purged") await runAfterCommit({ cancelExpiry: true }, storage);
|
|
914
|
+
}
|
|
915
|
+
function mapDelete(status) {
|
|
916
|
+
if (status === "not-found") return { status: "not-found" };
|
|
917
|
+
if (status === "gone") return { status: "gone" };
|
|
918
|
+
return { status: "ok" };
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Adapt a storage `Stream` to the live-read store. Every adapter implements
|
|
922
|
+
* `awaitChange` (a backend that cannot wake cheaply polls inside its own
|
|
923
|
+
* implementation), so core wires it straight through with no fallback.
|
|
924
|
+
*/
|
|
925
|
+
function liveReadStore(storage) {
|
|
926
|
+
return {
|
|
927
|
+
getRecord: () => storage.getRecord(),
|
|
928
|
+
awaitChange: (options) => storage.awaitChange(options)
|
|
929
|
+
};
|
|
930
|
+
}
|
|
785
931
|
var ProtocolStream = class {
|
|
786
932
|
id;
|
|
787
933
|
appendService;
|
|
788
934
|
readService;
|
|
789
935
|
liveReadService;
|
|
790
936
|
createService;
|
|
937
|
+
forkPlanBuilder;
|
|
791
938
|
constructor(deps) {
|
|
792
939
|
this.deps = deps;
|
|
793
940
|
this.id = deps.storage.id;
|
|
794
|
-
const producerIdempotency = new ProducerIdempotencyService({ store: deps.storage });
|
|
795
|
-
const messageWriter = new StreamMessageWriter({
|
|
796
|
-
stream: deps.storage,
|
|
797
|
-
clock: deps.clock,
|
|
798
|
-
expiryPolicy: deps.expiryPolicy
|
|
799
|
-
});
|
|
800
941
|
const messageReader = new StreamMessageReader({
|
|
801
942
|
stream: deps.storage,
|
|
802
943
|
resolve: deps.resolveStorageStream,
|
|
803
944
|
expiryPolicy: deps.expiryPolicy
|
|
804
945
|
});
|
|
805
|
-
this.appendService = new AppendService({
|
|
806
|
-
producerIdempotency,
|
|
807
|
-
mutators: {
|
|
808
|
-
appendMessages: (record, data, seq) => messageWriter.appendMessages(record, data, seq),
|
|
809
|
-
closeRecord: (record, data, seq) => messageWriter.closeRecord(record, data, seq)
|
|
810
|
-
}
|
|
811
|
-
});
|
|
946
|
+
this.appendService = new AppendService({ clock: deps.clock });
|
|
812
947
|
this.readService = new ReadService({ readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset) });
|
|
813
948
|
this.liveReadService = new LiveReadService({
|
|
814
|
-
store: deps.storage,
|
|
949
|
+
store: liveReadStore(deps.storage),
|
|
815
950
|
clock: deps.clock,
|
|
816
951
|
longPollTimeoutMs: deps.longPollTimeoutMs,
|
|
817
952
|
readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset),
|
|
818
|
-
readOwn: (after) => messageReader.readOwn(after)
|
|
819
|
-
touch: (record) => deps.expiryPolicy.touch(deps.storage, record, "live-read")
|
|
820
|
-
});
|
|
821
|
-
const forkService = new ForkService({
|
|
822
|
-
resolve: deps.resolveStorageStream,
|
|
823
|
-
mutators: {
|
|
824
|
-
expireIfNeeded: async (stream) => {
|
|
825
|
-
await deps.expiryPolicy.expireIfNeeded(stream);
|
|
826
|
-
},
|
|
827
|
-
newRecord: (stream, contentType, opts, fork) => deps.recordFactory.newRecord(stream.id, contentType, opts, fork),
|
|
828
|
-
scheduleExpiry: (record) => deps.expiryPolicy.scheduleExpiry(record),
|
|
829
|
-
appendMessages: (record, data) => messageWriter.appendMessages(record, data)
|
|
830
|
-
}
|
|
953
|
+
readOwn: (after) => messageReader.readOwn(after)
|
|
831
954
|
});
|
|
832
955
|
this.createService = new CreateStreamService({
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
createFork: (opts) => forkService.execute(deps.storage, opts)
|
|
840
|
-
}
|
|
956
|
+
clock: deps.clock,
|
|
957
|
+
newRecord: (contentType, opts) => deps.recordFactory.newRecord(deps.storage.id, contentType, opts, void 0)
|
|
958
|
+
});
|
|
959
|
+
this.forkPlanBuilder = new ForkPlanBuilder({
|
|
960
|
+
clock: deps.clock,
|
|
961
|
+
newRecord: (streamId, contentType, opts, fork) => deps.recordFactory.newRecord(streamId, contentType, opts, fork)
|
|
841
962
|
});
|
|
842
963
|
}
|
|
843
964
|
async create(options) {
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
965
|
+
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
966
|
+
const decision = this.createService.plan(record, options);
|
|
967
|
+
if (decision.kind === "terminal") return decision.result;
|
|
968
|
+
if (decision.kind === "fork") return this.createFork(options);
|
|
969
|
+
const commit = await this.deps.adapter.create(decision.plan);
|
|
970
|
+
if (commit.status === "exists") return this.createService.resultForExisting(commit.record, options);
|
|
971
|
+
await runAfterCommit(decision.afterCommit, this.deps.storage);
|
|
972
|
+
return decision.toResult(commit.record);
|
|
848
973
|
}
|
|
849
974
|
async append(options) {
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
975
|
+
let lastRecord = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
976
|
+
let noProgressAttempts = 0;
|
|
977
|
+
let attempt = 0;
|
|
978
|
+
const hasUserExpectedOffset = options.expectedOffset !== void 0;
|
|
979
|
+
while (true) {
|
|
980
|
+
const producerState = options.producer ? await this.deps.storage.getProducerState(options.producer.producerId) : void 0;
|
|
981
|
+
const decision = this.appendService.plan(lastRecord, options, producerState);
|
|
982
|
+
if (decision.kind === "terminal") return decision.result;
|
|
983
|
+
const out = await this.deps.storage.append(decision.plan);
|
|
984
|
+
if (out.status === "appended") {
|
|
985
|
+
await runAfterCommit(decision.afterCommit, this.deps.storage);
|
|
986
|
+
return decision.toResult(out.record);
|
|
987
|
+
}
|
|
988
|
+
lastRecord = out.record;
|
|
989
|
+
if (lastRecord === null) return { status: "not-found" };
|
|
990
|
+
if (hasUserExpectedOffset) {
|
|
991
|
+
attempt++;
|
|
992
|
+
if (attempt >= MAX_COMMIT_ATTEMPTS) return {
|
|
993
|
+
status: "conflict",
|
|
994
|
+
conflictReason: "expected-offset",
|
|
995
|
+
offset: lastRecord.currentOffset
|
|
996
|
+
};
|
|
997
|
+
} else {
|
|
998
|
+
const previousOffset = decision.plan.preconditions.expectedOffset ?? ZERO_OFFSET;
|
|
999
|
+
const madeProgress = compareOffsets(lastRecord.currentOffset, previousOffset) > 0;
|
|
1000
|
+
noProgressAttempts = madeProgress ? 0 : noProgressAttempts + 1;
|
|
1001
|
+
if (noProgressAttempts >= MAX_NO_PROGRESS_ATTEMPTS) return { status: "busy" };
|
|
1002
|
+
}
|
|
1003
|
+
await Promise.resolve();
|
|
1004
|
+
}
|
|
854
1005
|
}
|
|
855
1006
|
async read(options) {
|
|
856
1007
|
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
@@ -872,17 +1023,60 @@ var ProtocolStream = class {
|
|
|
872
1023
|
expiresAt: record.config.expiresAt,
|
|
873
1024
|
closed: record.lifecycle.closed === true
|
|
874
1025
|
};
|
|
875
|
-
}
|
|
876
|
-
async delete() {
|
|
877
|
-
await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
878
|
-
|
|
1026
|
+
}
|
|
1027
|
+
async delete() {
|
|
1028
|
+
await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1029
|
+
const commit = await this.deps.adapter.delete({
|
|
1030
|
+
streamId: this.id,
|
|
1031
|
+
reason: "delete"
|
|
1032
|
+
});
|
|
1033
|
+
await runDeleteEffects(commit.status, this.deps.storage);
|
|
1034
|
+
return mapDelete(commit.status);
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Read the source messages immediately after `forkOffset`, composed through
|
|
1038
|
+
* the source's own fork chain, so a sub-offset fork can materialize a
|
|
1039
|
+
* partial-message prefix (and chained forks compose). Only needed when a
|
|
1040
|
+
* positive `forkSubOffset` is requested; validation of the offset/sub-offset
|
|
1041
|
+
* combination stays in the fork plan builder.
|
|
1042
|
+
*/
|
|
1043
|
+
async readSourceTailForSubOffset(sourceStream, source, options) {
|
|
1044
|
+
const subOffset = options.forkSubOffset;
|
|
1045
|
+
if (subOffset === void 0 || subOffset <= 0 || !source) return void 0;
|
|
1046
|
+
const forkOffset = options.forkOffset ?? source.currentOffset;
|
|
1047
|
+
if (!isValidOffset(forkOffset)) return void 0;
|
|
1048
|
+
const reader = new StreamMessageReader({
|
|
1049
|
+
stream: sourceStream,
|
|
1050
|
+
resolve: this.deps.resolveStorageStream,
|
|
1051
|
+
expiryPolicy: this.deps.expiryPolicy
|
|
1052
|
+
});
|
|
1053
|
+
return reader.readChain(source, forkOffset, void 0, false);
|
|
1054
|
+
}
|
|
1055
|
+
async createFork(options) {
|
|
1056
|
+
const fork = this.deps.adapter.fork;
|
|
1057
|
+
if (!fork) return notSupported("fork");
|
|
1058
|
+
const sourceId = options.forkedFrom;
|
|
1059
|
+
const sourceStream = this.deps.resolveStorageStream(sourceId);
|
|
1060
|
+
const source = await this.deps.expiryPolicy.expireIfNeeded(sourceStream);
|
|
1061
|
+
const sourceTail = await this.readSourceTailForSubOffset(sourceStream, source, options);
|
|
1062
|
+
const decision = this.forkPlanBuilder.build(this.id, sourceId, source, options, sourceTail);
|
|
1063
|
+
if (decision.kind === "terminal") return decision.result;
|
|
1064
|
+
const commit = await fork.call(this.deps.adapter, decision.plan);
|
|
1065
|
+
if (commit.status === "exists") return this.createService.resultForExisting(commit.record, options);
|
|
1066
|
+
if (commit.status === "fork-source-gone") return {
|
|
1067
|
+
status: "not-found",
|
|
1068
|
+
nextOffset: "",
|
|
1069
|
+
contentType: "",
|
|
1070
|
+
errorMessage: `Source stream not found: ${sourceId}`
|
|
1071
|
+
};
|
|
1072
|
+
await runAfterCommit(decision.afterCommit, this.deps.storage);
|
|
1073
|
+
return decision.toResult(commit.record);
|
|
879
1074
|
}
|
|
880
1075
|
};
|
|
881
1076
|
var StreamProtocol = class {
|
|
882
1077
|
clock;
|
|
883
1078
|
longPollTimeoutMs;
|
|
884
1079
|
expiryPolicy;
|
|
885
|
-
gcService;
|
|
886
1080
|
recordFactory;
|
|
887
1081
|
constructor(deps) {
|
|
888
1082
|
this.deps = deps;
|
|
@@ -893,17 +1087,13 @@ var StreamProtocol = class {
|
|
|
893
1087
|
clock: this.clock,
|
|
894
1088
|
onScheduledExpiry: (id) => this.handleScheduledExpiry(id)
|
|
895
1089
|
});
|
|
896
|
-
this.gcService = new StreamGcService({
|
|
897
|
-
resolve: (id) => this.storageStream(id),
|
|
898
|
-
mutators: { isExpired: (record) => this.expiryPolicy.isExpired(record) }
|
|
899
|
-
});
|
|
900
1090
|
this.recordFactory = new StreamRecordFactory({
|
|
901
1091
|
clock: this.clock,
|
|
902
1092
|
expiryPolicy: this.expiryPolicy
|
|
903
1093
|
});
|
|
904
1094
|
}
|
|
905
1095
|
async create(streamId, options) {
|
|
906
|
-
const storage =
|
|
1096
|
+
const storage = this.storageStream(streamId);
|
|
907
1097
|
const stream = this.boundProtocolStream(storage);
|
|
908
1098
|
const result = await stream.create(options);
|
|
909
1099
|
if (result.status === "created" || result.status === "exists") return {
|
|
@@ -913,7 +1103,7 @@ var StreamProtocol = class {
|
|
|
913
1103
|
return result;
|
|
914
1104
|
}
|
|
915
1105
|
async get(streamId) {
|
|
916
|
-
const storage =
|
|
1106
|
+
const storage = this.storageStream(streamId);
|
|
917
1107
|
const record = await this.expiryPolicy.expireIfNeeded(storage);
|
|
918
1108
|
if (!record) return { status: "not-found" };
|
|
919
1109
|
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
@@ -922,33 +1112,210 @@ var StreamProtocol = class {
|
|
|
922
1112
|
stream: this.boundProtocolStream(storage)
|
|
923
1113
|
};
|
|
924
1114
|
}
|
|
925
|
-
/** Called by adapter schedulers/alarms; core decides
|
|
1115
|
+
/** Called by adapter schedulers/alarms; core decides whether expiry applies. */
|
|
926
1116
|
async handleScheduledExpiry(streamId) {
|
|
927
|
-
|
|
1117
|
+
const storage = this.storageStream(streamId);
|
|
1118
|
+
const record = await storage.getRecord();
|
|
1119
|
+
if (!record) return;
|
|
1120
|
+
if (!this.expiryPolicy.isExpired(record)) {
|
|
1121
|
+
await this.expiryPolicy.scheduleExpiry(record);
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
const commit = await this.deps.storage.adapter.delete({
|
|
1125
|
+
streamId,
|
|
1126
|
+
reason: "expiry"
|
|
1127
|
+
});
|
|
1128
|
+
await runDeleteEffects(commit.status, storage);
|
|
928
1129
|
}
|
|
929
1130
|
boundProtocolStream(storage) {
|
|
930
1131
|
return new ProtocolStream({
|
|
931
1132
|
storage,
|
|
1133
|
+
adapter: this.deps.storage.adapter,
|
|
932
1134
|
clock: this.clock,
|
|
933
1135
|
longPollTimeoutMs: this.longPollTimeoutMs,
|
|
934
1136
|
expiryPolicy: this.expiryPolicy,
|
|
935
|
-
gcService: this.gcService,
|
|
936
1137
|
recordFactory: this.recordFactory,
|
|
937
|
-
resolveStorageStream: (id) => this.storageStream(id)
|
|
938
|
-
withStreamMutationLock: (stream, fn) => this.withStreamMutationLock(stream, fn)
|
|
1138
|
+
resolveStorageStream: (id) => this.storageStream(id)
|
|
939
1139
|
});
|
|
940
1140
|
}
|
|
941
|
-
|
|
942
|
-
|
|
1141
|
+
/** Bind the flat adapter to one id for ergonomic core-side per-stream calls. */
|
|
1142
|
+
storageStream(streamId) {
|
|
1143
|
+
return bindStream(this.deps.storage.adapter, streamId);
|
|
1144
|
+
}
|
|
1145
|
+
};
|
|
1146
|
+
|
|
1147
|
+
//#endregion
|
|
1148
|
+
//#region src/storage/strategies/cascade-reclaim.ts
|
|
1149
|
+
async function cascadeReclaim(store, plan, lineage) {
|
|
1150
|
+
const record = await store.getRecord(plan.streamId);
|
|
1151
|
+
if (!record) return { status: "not-found" };
|
|
1152
|
+
if (plan.reason === "delete" && record.lifecycle.softDeleted) return { status: "gone" };
|
|
1153
|
+
const dependents = await lineage.countDependents(plan.streamId);
|
|
1154
|
+
if (dependents > 0) {
|
|
1155
|
+
await store.softDelete(plan.streamId);
|
|
1156
|
+
return { status: "retained-soft-deleted" };
|
|
1157
|
+
}
|
|
1158
|
+
await purgeAndCascade(store, lineage, record);
|
|
1159
|
+
return { status: "purged" };
|
|
1160
|
+
}
|
|
1161
|
+
async function plainPurge(store, plan) {
|
|
1162
|
+
const record = await store.getRecord(plan.streamId);
|
|
1163
|
+
if (!record) return { status: "not-found" };
|
|
1164
|
+
if (plan.reason === "delete" && record.lifecycle.softDeleted) return { status: "gone" };
|
|
1165
|
+
await store.purgeSelf(plan.streamId);
|
|
1166
|
+
return { status: "purged" };
|
|
1167
|
+
}
|
|
1168
|
+
async function purgeAndCascade(store, lineage, record) {
|
|
1169
|
+
await store.purgeSelf(record.id);
|
|
1170
|
+
let childId = record.id;
|
|
1171
|
+
let parentId = record.lifecycle.forkedFrom;
|
|
1172
|
+
while (parentId) {
|
|
1173
|
+
await lineage.dropEdge(parentId, childId);
|
|
1174
|
+
const parent = await store.getRecord(parentId);
|
|
1175
|
+
if (!parent || parent.lifecycle.softDeleted !== true) return;
|
|
1176
|
+
const dependents = await lineage.countDependents(parentId);
|
|
1177
|
+
if (dependents > 0) return;
|
|
1178
|
+
await store.purgeSelf(parentId);
|
|
1179
|
+
childId = parentId;
|
|
1180
|
+
parentId = parent.lifecycle.forkedFrom;
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
//#endregion
|
|
1185
|
+
//#region src/storage/strategies/ref-count-lineage.ts
|
|
1186
|
+
function refCountLineage(store) {
|
|
1187
|
+
return {
|
|
1188
|
+
async countDependents(parent) {
|
|
1189
|
+
return store.countDependents ? store.countDependents(parent) : 0;
|
|
1190
|
+
},
|
|
1191
|
+
async addEdge(parent, child) {
|
|
1192
|
+
await store.addEdge?.(parent, child);
|
|
1193
|
+
},
|
|
1194
|
+
async dropEdge(parent, child) {
|
|
1195
|
+
await store.dropEdge?.(parent, child);
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
//#endregion
|
|
1201
|
+
//#region src/storage/strategies/reverse-index-lineage.ts
|
|
1202
|
+
function reverseIndexLineage(query) {
|
|
1203
|
+
return {
|
|
1204
|
+
countDependents(parent) {
|
|
1205
|
+
return query(parent);
|
|
1206
|
+
},
|
|
1207
|
+
async addEdge() {},
|
|
1208
|
+
async dropEdge() {}
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
//#endregion
|
|
1213
|
+
//#region src/storage/strategies/copy-on-fork.ts
|
|
1214
|
+
function copyOnForkReclaim() {
|
|
1215
|
+
return {
|
|
1216
|
+
async countDependents() {
|
|
1217
|
+
return 0;
|
|
1218
|
+
},
|
|
1219
|
+
async addEdge() {},
|
|
1220
|
+
async dropEdge() {}
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
//#endregion
|
|
1225
|
+
//#region src/storage/strategies/ttl-only.ts
|
|
1226
|
+
function ttlOnlyReclaim() {
|
|
1227
|
+
return {
|
|
1228
|
+
async countDependents() {
|
|
1229
|
+
return 1;
|
|
1230
|
+
},
|
|
1231
|
+
async addEdge() {},
|
|
1232
|
+
async dropEdge() {}
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
//#endregion
|
|
1237
|
+
//#region src/storage/memory/lineage-store.ts
|
|
1238
|
+
var MemoryLineageStore = class {
|
|
1239
|
+
constructor(state) {
|
|
1240
|
+
this.state = state;
|
|
1241
|
+
}
|
|
1242
|
+
async getRecord(id) {
|
|
1243
|
+
return this.state.getExistingStream(id)?.getRecord() ?? null;
|
|
1244
|
+
}
|
|
1245
|
+
async purgeSelf(id) {
|
|
1246
|
+
this.state.getExistingStream(id)?.purgeSelf();
|
|
1247
|
+
}
|
|
1248
|
+
async softDelete(id) {
|
|
1249
|
+
this.state.getExistingStream(id)?.softDelete();
|
|
1250
|
+
}
|
|
1251
|
+
async addEdge(parent, child) {
|
|
1252
|
+
this.state.addEdge(parent, child);
|
|
1253
|
+
}
|
|
1254
|
+
async dropEdge(parent, child) {
|
|
1255
|
+
this.state.dropEdge(parent, child);
|
|
943
1256
|
}
|
|
944
|
-
async
|
|
945
|
-
return
|
|
1257
|
+
async countDependents(parent) {
|
|
1258
|
+
return this.state.countDependents(parent);
|
|
946
1259
|
}
|
|
947
1260
|
};
|
|
948
1261
|
|
|
1262
|
+
//#endregion
|
|
1263
|
+
//#region src/protocol/helpers/change-snapshot.ts
|
|
1264
|
+
/** Build the serializable, change-relevant snapshot of a (possibly absent) record. */
|
|
1265
|
+
function buildChangeSnapshot(record) {
|
|
1266
|
+
if (!record) return {
|
|
1267
|
+
present: false,
|
|
1268
|
+
currentOffset: ZERO_OFFSET,
|
|
1269
|
+
closed: false,
|
|
1270
|
+
softDeleted: false
|
|
1271
|
+
};
|
|
1272
|
+
return {
|
|
1273
|
+
present: true,
|
|
1274
|
+
currentOffset: record.currentOffset,
|
|
1275
|
+
closed: record.lifecycle.closed === true,
|
|
1276
|
+
softDeleted: record.lifecycle.softDeleted === true
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* The level-triggered "differs" predicate. A snapshot differs from what the
|
|
1281
|
+
* caller observed when the record was purged, transitioned to soft-deleted or
|
|
1282
|
+
* closed, or its offset is not the parked position. Offset **inequality** — not
|
|
1283
|
+
* just advance — is the trigger: within one incarnation an offset only ever
|
|
1284
|
+
* advances, so a *lower* offset means the stream was purged and re-created
|
|
1285
|
+
* while the waiter was parked, which is also "something happened".
|
|
1286
|
+
*/
|
|
1287
|
+
function changeSnapshotDiffers(snapshot, options) {
|
|
1288
|
+
if (!snapshot.present) return true;
|
|
1289
|
+
if (snapshot.softDeleted && options.observedSoftDeleted !== true) return true;
|
|
1290
|
+
if (snapshot.closed && options.observedClosed !== true) return true;
|
|
1291
|
+
return compareOffsets(snapshot.currentOffset, options.fromOffset) !== 0;
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
//#endregion
|
|
1295
|
+
//#region src/protocol/helpers/await-change-loop.ts
|
|
1296
|
+
async function runAwaitChangeLoop(deps, options) {
|
|
1297
|
+
const now = deps.now ?? (() => Date.now());
|
|
1298
|
+
const budget = deps.totalCapMs === void 0 ? options.timeoutMs : Math.min(options.timeoutMs, deps.totalCapMs);
|
|
1299
|
+
const start = now();
|
|
1300
|
+
while (true) {
|
|
1301
|
+
const snapshot = buildChangeSnapshot(await deps.readRecord());
|
|
1302
|
+
if (changeSnapshotDiffers(snapshot, options)) return {
|
|
1303
|
+
status: "changed",
|
|
1304
|
+
snapshot
|
|
1305
|
+
};
|
|
1306
|
+
const remaining = budget - (now() - start);
|
|
1307
|
+
if (remaining <= 0) return {
|
|
1308
|
+
status: "timeout",
|
|
1309
|
+
snapshot
|
|
1310
|
+
};
|
|
1311
|
+
const park = deps.parkCapMs === void 0 ? remaining : Math.min(remaining, deps.parkCapMs);
|
|
1312
|
+
await deps.waitForWake(park);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
|
|
949
1316
|
//#endregion
|
|
950
1317
|
//#region src/storage/memory/lib/clone.ts
|
|
951
|
-
function clone(value) {
|
|
1318
|
+
function clone$1(value) {
|
|
952
1319
|
if (value === null || value === void 0) return value;
|
|
953
1320
|
return structuredClone(value);
|
|
954
1321
|
}
|
|
@@ -960,18 +1327,18 @@ var MessageStore = class {
|
|
|
960
1327
|
constructor(records) {
|
|
961
1328
|
this.records = records;
|
|
962
1329
|
}
|
|
963
|
-
|
|
1330
|
+
appendMessages(messages) {
|
|
964
1331
|
this.records.requireRecord();
|
|
965
|
-
this.messages.push(...clone(messages));
|
|
1332
|
+
this.messages.push(...clone$1(messages));
|
|
966
1333
|
}
|
|
967
|
-
|
|
1334
|
+
listMessages(options = {}) {
|
|
968
1335
|
let out = this.messages;
|
|
969
1336
|
if (options.after) out = out.filter((m) => m.offset > options.after);
|
|
970
1337
|
if (options.until) out = out.filter((m) => m.offset <= options.until);
|
|
971
1338
|
if (options.limit !== void 0) out = out.slice(0, options.limit);
|
|
972
|
-
return clone(out);
|
|
1339
|
+
return clone$1(out);
|
|
973
1340
|
}
|
|
974
|
-
|
|
1341
|
+
deleteMessages() {
|
|
975
1342
|
this.messages = [];
|
|
976
1343
|
}
|
|
977
1344
|
};
|
|
@@ -983,14 +1350,14 @@ var ProducerStore = class {
|
|
|
983
1350
|
constructor(records) {
|
|
984
1351
|
this.records = records;
|
|
985
1352
|
}
|
|
986
|
-
|
|
987
|
-
return clone(this.producers.get(producerId));
|
|
1353
|
+
getProducerState(producerId) {
|
|
1354
|
+
return clone$1(this.producers.get(producerId));
|
|
988
1355
|
}
|
|
989
|
-
|
|
1356
|
+
setProducerState(producerId, producerState) {
|
|
990
1357
|
this.records.requireRecord();
|
|
991
|
-
this.producers.set(producerId, clone(producerState));
|
|
1358
|
+
this.producers.set(producerId, clone$1(producerState));
|
|
992
1359
|
}
|
|
993
|
-
|
|
1360
|
+
deleteProducerStates() {
|
|
994
1361
|
this.producers.clear();
|
|
995
1362
|
}
|
|
996
1363
|
};
|
|
@@ -1002,19 +1369,19 @@ var RecordStore = class {
|
|
|
1002
1369
|
constructor(id) {
|
|
1003
1370
|
this.id = id;
|
|
1004
1371
|
}
|
|
1005
|
-
|
|
1006
|
-
return clone(this.record ?? null);
|
|
1372
|
+
getRecord() {
|
|
1373
|
+
return clone$1(this.record ?? null);
|
|
1007
1374
|
}
|
|
1008
|
-
|
|
1375
|
+
createRecord(record) {
|
|
1009
1376
|
if (record.id !== this.id) throw new Error(`Record id ${record.id} does not match bound stream ${this.id}`);
|
|
1010
1377
|
if (this.record) return {
|
|
1011
1378
|
status: "exists",
|
|
1012
|
-
record: clone(this.record)
|
|
1379
|
+
record: clone$1(this.record)
|
|
1013
1380
|
};
|
|
1014
|
-
this.record = clone(record);
|
|
1381
|
+
this.record = clone$1(record);
|
|
1015
1382
|
return { status: "created" };
|
|
1016
1383
|
}
|
|
1017
|
-
|
|
1384
|
+
updateRecord(patch) {
|
|
1018
1385
|
const record = this.requireRecord();
|
|
1019
1386
|
this.record = {
|
|
1020
1387
|
...record,
|
|
@@ -1029,87 +1396,46 @@ var RecordStore = class {
|
|
|
1029
1396
|
currentOffset: patch.currentOffset ?? record.currentOffset,
|
|
1030
1397
|
counter: patch.counter ?? record.counter
|
|
1031
1398
|
};
|
|
1032
|
-
return clone(this.record);
|
|
1399
|
+
return clone$1(this.record);
|
|
1033
1400
|
}
|
|
1034
|
-
|
|
1401
|
+
deleteRecord() {
|
|
1035
1402
|
this.record = void 0;
|
|
1036
1403
|
}
|
|
1037
|
-
async incrementChildRefCount() {
|
|
1038
|
-
const updated = this.updateStoredRecord((record) => {
|
|
1039
|
-
const next = record.lifecycle.childRefCount + 1;
|
|
1040
|
-
return {
|
|
1041
|
-
...record,
|
|
1042
|
-
lifecycle: {
|
|
1043
|
-
...record.lifecycle,
|
|
1044
|
-
childRefCount: next
|
|
1045
|
-
}
|
|
1046
|
-
};
|
|
1047
|
-
});
|
|
1048
|
-
return updated.lifecycle.childRefCount;
|
|
1049
|
-
}
|
|
1050
|
-
async decrementChildRefCount() {
|
|
1051
|
-
const updated = this.updateStoredRecord((record) => {
|
|
1052
|
-
const next = Math.max(0, record.lifecycle.childRefCount - 1);
|
|
1053
|
-
return {
|
|
1054
|
-
...record,
|
|
1055
|
-
lifecycle: {
|
|
1056
|
-
...record.lifecycle,
|
|
1057
|
-
childRefCount: next
|
|
1058
|
-
}
|
|
1059
|
-
};
|
|
1060
|
-
});
|
|
1061
|
-
return updated.lifecycle.childRefCount;
|
|
1062
|
-
}
|
|
1063
1404
|
requireRecord() {
|
|
1064
1405
|
if (!this.record) throw new Error(`Stream not found: ${this.id}`);
|
|
1065
1406
|
return this.record;
|
|
1066
1407
|
}
|
|
1067
|
-
updateStoredRecord(update) {
|
|
1068
|
-
this.record = update(this.requireRecord());
|
|
1069
|
-
return this.record;
|
|
1070
|
-
}
|
|
1071
|
-
};
|
|
1072
|
-
|
|
1073
|
-
//#endregion
|
|
1074
|
-
//#region src/storage/memory/utils/lock.ts
|
|
1075
|
-
var MemoryLock = class {
|
|
1076
|
-
lock;
|
|
1077
|
-
async withLock(fn) {
|
|
1078
|
-
while (this.lock) await this.lock;
|
|
1079
|
-
let release;
|
|
1080
|
-
this.lock = new Promise((resolve) => release = resolve);
|
|
1081
|
-
try {
|
|
1082
|
-
return await fn();
|
|
1083
|
-
} finally {
|
|
1084
|
-
this.lock = void 0;
|
|
1085
|
-
release();
|
|
1086
|
-
}
|
|
1087
|
-
}
|
|
1088
1408
|
};
|
|
1089
1409
|
|
|
1090
1410
|
//#endregion
|
|
1091
1411
|
//#region src/storage/memory/utils/notifier.ts
|
|
1412
|
+
/**
|
|
1413
|
+
* In-process wake bus backing the memory adapter's level-triggered `awaitChange`.
|
|
1414
|
+
*
|
|
1415
|
+
* A parked waiter resolves either when a mutation calls {@link wake} or after its
|
|
1416
|
+
* timeout; the caller re-reads durable state to decide whether anything relevant
|
|
1417
|
+
* changed. Spurious wakes are safe — the caller simply re-checks and parks again
|
|
1418
|
+
* within its remaining budget.
|
|
1419
|
+
*/
|
|
1092
1420
|
var MemoryNotifier = class {
|
|
1093
|
-
|
|
1094
|
-
|
|
1421
|
+
wakeWaiters = new Set();
|
|
1422
|
+
waitForWake(timeoutMs) {
|
|
1095
1423
|
return new Promise((resolve) => {
|
|
1096
|
-
const
|
|
1097
|
-
const finish = (result) => {
|
|
1424
|
+
const finish = () => {
|
|
1098
1425
|
clearTimeout(timeout);
|
|
1099
|
-
this.
|
|
1100
|
-
resolve(
|
|
1426
|
+
this.wakeWaiters.delete(finish);
|
|
1427
|
+
resolve();
|
|
1101
1428
|
};
|
|
1102
|
-
|
|
1103
|
-
|
|
1429
|
+
const timeout = setTimeout(finish, timeoutMs);
|
|
1430
|
+
this.wakeWaiters.add(finish);
|
|
1104
1431
|
});
|
|
1105
1432
|
}
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
this.
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
});
|
|
1433
|
+
/** Wake every parked `awaitChange` waiter. Called from inside a mutation. */
|
|
1434
|
+
wake() {
|
|
1435
|
+
if (this.wakeWaiters.size === 0) return;
|
|
1436
|
+
const waiters = [...this.wakeWaiters];
|
|
1437
|
+
this.wakeWaiters.clear();
|
|
1438
|
+
for (const waiter of waiters) waiter();
|
|
1113
1439
|
}
|
|
1114
1440
|
};
|
|
1115
1441
|
|
|
@@ -1117,11 +1443,18 @@ var MemoryNotifier = class {
|
|
|
1117
1443
|
//#region src/storage/memory/utils/timeout-scheduler.ts
|
|
1118
1444
|
var TimeoutScheduler = class {
|
|
1119
1445
|
timer;
|
|
1120
|
-
|
|
1446
|
+
constructor(callback) {
|
|
1447
|
+
this.callback = callback;
|
|
1448
|
+
}
|
|
1449
|
+
schedule(at) {
|
|
1121
1450
|
this.cancel();
|
|
1122
|
-
if (!callback) return;
|
|
1123
|
-
const delay = Math.max(0, at - Date.now());
|
|
1124
|
-
this.timer = setTimeout(() =>
|
|
1451
|
+
if (!this.callback) return;
|
|
1452
|
+
const delay$1 = Math.max(0, at - Date.now());
|
|
1453
|
+
this.timer = setTimeout(() => {
|
|
1454
|
+
Promise.resolve(this.callback?.()).catch((error) => {
|
|
1455
|
+
console.error("memory expiry callback failed", error);
|
|
1456
|
+
});
|
|
1457
|
+
}, delay$1);
|
|
1125
1458
|
}
|
|
1126
1459
|
cancel() {
|
|
1127
1460
|
if (this.timer) clearTimeout(this.timer);
|
|
@@ -1131,105 +1464,232 @@ var TimeoutScheduler = class {
|
|
|
1131
1464
|
|
|
1132
1465
|
//#endregion
|
|
1133
1466
|
//#region src/storage/memory/stream.ts
|
|
1467
|
+
/** Adapter-private per-stream handle. Not on the seam — owned by the memory state. */
|
|
1134
1468
|
var MemoryStream = class {
|
|
1135
1469
|
records;
|
|
1136
1470
|
messages;
|
|
1137
1471
|
producers;
|
|
1138
|
-
lock;
|
|
1139
1472
|
notifier;
|
|
1140
1473
|
timeout;
|
|
1141
|
-
constructor(id, deleteFromState) {
|
|
1474
|
+
constructor(id, deleteFromState, onScheduledExpiry) {
|
|
1142
1475
|
this.id = id;
|
|
1143
1476
|
this.deleteFromState = deleteFromState;
|
|
1144
1477
|
this.records = new RecordStore(id);
|
|
1145
1478
|
this.messages = new MessageStore(this.records);
|
|
1146
1479
|
this.producers = new ProducerStore(this.records);
|
|
1147
|
-
this.lock = new MemoryLock();
|
|
1148
1480
|
this.notifier = new MemoryNotifier();
|
|
1149
|
-
this.timeout = new TimeoutScheduler();
|
|
1481
|
+
this.timeout = new TimeoutScheduler(onScheduledExpiry);
|
|
1150
1482
|
}
|
|
1151
1483
|
getRecord() {
|
|
1152
1484
|
return this.records.getRecord();
|
|
1153
1485
|
}
|
|
1154
|
-
createRecord
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1486
|
+
/** Public append intent (no `createRecord`). */
|
|
1487
|
+
append(plan) {
|
|
1488
|
+
const out = this.applyMutation({
|
|
1489
|
+
preconditions: plan.preconditions,
|
|
1490
|
+
messages: plan.messages,
|
|
1491
|
+
recordPatch: plan.recordPatch
|
|
1492
|
+
});
|
|
1493
|
+
if (out.status === "committed") return {
|
|
1494
|
+
status: "appended",
|
|
1495
|
+
record: out.record
|
|
1496
|
+
};
|
|
1497
|
+
return {
|
|
1498
|
+
status: "precondition-failed",
|
|
1499
|
+
record: out.record,
|
|
1500
|
+
reason: out.reason ?? "offset"
|
|
1501
|
+
};
|
|
1166
1502
|
}
|
|
1167
|
-
|
|
1168
|
-
|
|
1503
|
+
/**
|
|
1504
|
+
* Adapter-internal write engine shared by `append` (no `createRecord`) and the
|
|
1505
|
+
* `create`/`fork` intents (with `createRecord`).
|
|
1506
|
+
*/
|
|
1507
|
+
applyMutation(plan) {
|
|
1508
|
+
let record = this.records.getRecord();
|
|
1509
|
+
if (plan.createRecord) {
|
|
1510
|
+
if (record) return {
|
|
1511
|
+
status: "precondition-failed",
|
|
1512
|
+
record
|
|
1513
|
+
};
|
|
1514
|
+
const created = this.records.createRecord(plan.createRecord);
|
|
1515
|
+
if (created.status === "exists") return {
|
|
1516
|
+
status: "precondition-failed",
|
|
1517
|
+
record: created.record
|
|
1518
|
+
};
|
|
1519
|
+
record = this.records.getRecord();
|
|
1520
|
+
}
|
|
1521
|
+
if (!record) return {
|
|
1522
|
+
status: "precondition-failed",
|
|
1523
|
+
record: null
|
|
1524
|
+
};
|
|
1525
|
+
if (plan.preconditions.expectedOffset !== void 0 && plan.preconditions.expectedOffset !== record.currentOffset) return {
|
|
1526
|
+
status: "precondition-failed",
|
|
1527
|
+
record,
|
|
1528
|
+
reason: "offset"
|
|
1529
|
+
};
|
|
1530
|
+
if (plan.preconditions.expectedClosed !== void 0 && plan.preconditions.expectedClosed !== (record.lifecycle.closed === true)) return {
|
|
1531
|
+
status: "precondition-failed",
|
|
1532
|
+
record,
|
|
1533
|
+
reason: "closed"
|
|
1534
|
+
};
|
|
1535
|
+
const producer = plan.preconditions.producer;
|
|
1536
|
+
if (producer) {
|
|
1537
|
+
const current = this.producers.getProducerState(producer.producerId);
|
|
1538
|
+
if (!producerStatesEqual(current, producer.expected)) return {
|
|
1539
|
+
status: "precondition-failed",
|
|
1540
|
+
record,
|
|
1541
|
+
reason: "producer"
|
|
1542
|
+
};
|
|
1543
|
+
}
|
|
1544
|
+
if (plan.messages && plan.messages.length > 0) this.messages.appendMessages(plan.messages);
|
|
1545
|
+
if (plan.recordPatch) record = this.records.updateRecord(plan.recordPatch);
|
|
1546
|
+
if (producer) this.producers.setProducerState(producer.producerId, producer.next);
|
|
1547
|
+
this.notifier.wake();
|
|
1548
|
+
return {
|
|
1549
|
+
status: "committed",
|
|
1550
|
+
record: this.records.getRecord() ?? record
|
|
1551
|
+
};
|
|
1169
1552
|
}
|
|
1170
1553
|
listMessages(options) {
|
|
1171
1554
|
return this.messages.listMessages(options);
|
|
1172
1555
|
}
|
|
1173
|
-
deleteMessages() {
|
|
1174
|
-
return this.messages.deleteMessages();
|
|
1175
|
-
}
|
|
1176
1556
|
getProducerState(producerId) {
|
|
1177
1557
|
return this.producers.getProducerState(producerId);
|
|
1178
1558
|
}
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
return this.records.incrementChildRefCount();
|
|
1187
|
-
}
|
|
1188
|
-
decrementChildRefCount() {
|
|
1189
|
-
return this.records.decrementChildRefCount();
|
|
1190
|
-
}
|
|
1191
|
-
withMutationLock(fn) {
|
|
1192
|
-
return this.lock.withLock(fn);
|
|
1559
|
+
purgeSelf() {
|
|
1560
|
+
this.messages.deleteMessages();
|
|
1561
|
+
this.producers.deleteProducerStates();
|
|
1562
|
+
this.records.deleteRecord();
|
|
1563
|
+
this.timeout.cancel();
|
|
1564
|
+
this.deleteFromState();
|
|
1565
|
+
this.notifier.wake();
|
|
1193
1566
|
}
|
|
1194
|
-
|
|
1195
|
-
|
|
1567
|
+
softDelete() {
|
|
1568
|
+
this.records.updateRecord({ lifecycle: { softDeleted: true } });
|
|
1569
|
+
this.notifier.wake();
|
|
1196
1570
|
}
|
|
1197
|
-
|
|
1198
|
-
|
|
1571
|
+
/**
|
|
1572
|
+
* Level-triggered live wait via the shared exported loop: re-read durable
|
|
1573
|
+
* state first (so a mutation that landed between the caller's observation and
|
|
1574
|
+
* this call is never missed), then park on the wake bus until the state
|
|
1575
|
+
* advances or the budget expires. Read and park are synchronous with the wake
|
|
1576
|
+
* bus here, so no per-park cap is needed.
|
|
1577
|
+
*/
|
|
1578
|
+
awaitChange(options) {
|
|
1579
|
+
return runAwaitChangeLoop({
|
|
1580
|
+
readRecord: () => this.records.getRecord(),
|
|
1581
|
+
waitForWake: (timeoutMs) => this.notifier.waitForWake(timeoutMs)
|
|
1582
|
+
}, options);
|
|
1199
1583
|
}
|
|
1200
|
-
scheduleExpiry(at
|
|
1201
|
-
return this.timeout.schedule(at
|
|
1584
|
+
scheduleExpiry(at) {
|
|
1585
|
+
return this.timeout.schedule(at);
|
|
1202
1586
|
}
|
|
1203
1587
|
cancelExpiry() {
|
|
1204
1588
|
return this.timeout.cancel();
|
|
1205
1589
|
}
|
|
1206
1590
|
};
|
|
1591
|
+
function producerStatesEqual(left, right) {
|
|
1592
|
+
if (!left || !right) return left === right;
|
|
1593
|
+
return left.epoch === right.epoch && left.lastSeq === right.lastSeq;
|
|
1594
|
+
}
|
|
1207
1595
|
|
|
1208
1596
|
//#endregion
|
|
1209
1597
|
//#region src/storage/memory/state.ts
|
|
1210
1598
|
/** Shared in-memory stream registry. */
|
|
1211
1599
|
var MemoryStreamState = class {
|
|
1212
1600
|
streams = new Map();
|
|
1601
|
+
childEdges = new Map();
|
|
1602
|
+
constructor(onScheduledExpiry) {
|
|
1603
|
+
this.onScheduledExpiry = onScheduledExpiry;
|
|
1604
|
+
}
|
|
1213
1605
|
getStream(id) {
|
|
1214
1606
|
let stream = this.streams.get(id);
|
|
1215
1607
|
if (!stream) {
|
|
1216
|
-
stream = new MemoryStream(id, () => this.
|
|
1608
|
+
stream = new MemoryStream(id, () => this.deleteStream(id), () => this.onScheduledExpiry?.(id));
|
|
1217
1609
|
this.streams.set(id, stream);
|
|
1218
1610
|
}
|
|
1219
1611
|
return stream;
|
|
1220
1612
|
}
|
|
1221
|
-
|
|
1222
|
-
return this.
|
|
1613
|
+
getExistingStream(id) {
|
|
1614
|
+
return this.streams.get(id);
|
|
1615
|
+
}
|
|
1616
|
+
addEdge(parent, child) {
|
|
1617
|
+
const children = this.childEdges.get(parent) ?? new Set();
|
|
1618
|
+
children.add(child);
|
|
1619
|
+
this.childEdges.set(parent, children);
|
|
1620
|
+
}
|
|
1621
|
+
dropEdge(parent, child) {
|
|
1622
|
+
const children = this.childEdges.get(parent);
|
|
1623
|
+
if (!children) return;
|
|
1624
|
+
children.delete(child);
|
|
1625
|
+
if (children.size === 0) this.childEdges.delete(parent);
|
|
1626
|
+
}
|
|
1627
|
+
countDependents(parent) {
|
|
1628
|
+
return this.childEdges.get(parent)?.size ?? 0;
|
|
1629
|
+
}
|
|
1630
|
+
deleteStream(id) {
|
|
1631
|
+
this.streams.delete(id);
|
|
1632
|
+
this.childEdges.delete(id);
|
|
1223
1633
|
}
|
|
1224
1634
|
};
|
|
1225
1635
|
|
|
1226
1636
|
//#endregion
|
|
1227
|
-
//#region src/storage/memory/
|
|
1228
|
-
function
|
|
1229
|
-
const state = options.state ?? new MemoryStreamState();
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1637
|
+
//#region src/storage/memory/adapter.ts
|
|
1638
|
+
function createMemoryStorageAdapter(options = {}) {
|
|
1639
|
+
const state = options.state ?? new MemoryStreamState(options.onScheduledExpiry);
|
|
1640
|
+
const lineageStore = new MemoryLineageStore(state);
|
|
1641
|
+
const lineage = refCountLineage(lineageStore);
|
|
1642
|
+
return {
|
|
1643
|
+
getRecord: (streamId) => Promise.resolve(state.getStream(streamId).getRecord()),
|
|
1644
|
+
listMessages: (streamId, listOptions) => Promise.resolve(state.getStream(streamId).listMessages(listOptions)),
|
|
1645
|
+
getProducerState: (streamId, producerId) => Promise.resolve(state.getStream(streamId).getProducerState(producerId)),
|
|
1646
|
+
append: (streamId, plan) => Promise.resolve(state.getStream(streamId).append(plan)),
|
|
1647
|
+
awaitChange: (streamId, awaitOptions) => state.getStream(streamId).awaitChange(awaitOptions),
|
|
1648
|
+
scheduleExpiry: (streamId, at) => state.getStream(streamId).scheduleExpiry(at),
|
|
1649
|
+
cancelExpiry: (streamId) => state.getStream(streamId).cancelExpiry(),
|
|
1650
|
+
async create(plan) {
|
|
1651
|
+
const stream = state.getStream(plan.record.id);
|
|
1652
|
+
const result = stream.applyMutation({
|
|
1653
|
+
createRecord: plan.record,
|
|
1654
|
+
preconditions: {},
|
|
1655
|
+
messages: plan.initialMessages
|
|
1656
|
+
});
|
|
1657
|
+
if (result.status === "committed") return {
|
|
1658
|
+
status: "created",
|
|
1659
|
+
record: result.record
|
|
1660
|
+
};
|
|
1661
|
+
return {
|
|
1662
|
+
status: "exists",
|
|
1663
|
+
record: result.record ?? plan.record
|
|
1664
|
+
};
|
|
1665
|
+
},
|
|
1666
|
+
async fork(plan) {
|
|
1667
|
+
const source = state.getExistingStream(plan.sourceId)?.getRecord() ?? null;
|
|
1668
|
+
if (!source || source.lifecycle.softDeleted || compareOffsets(source.currentOffset, plan.precondition.sourceLiveAtOffset) < 0) return { status: "fork-source-gone" };
|
|
1669
|
+
const child = state.getStream(plan.child.id);
|
|
1670
|
+
const result = child.applyMutation({
|
|
1671
|
+
createRecord: plan.child,
|
|
1672
|
+
preconditions: {},
|
|
1673
|
+
messages: plan.initialMessages
|
|
1674
|
+
});
|
|
1675
|
+
if (result.status !== "committed") {
|
|
1676
|
+
const existing = result.record ?? child.getRecord() ?? plan.child;
|
|
1677
|
+
if (existing.lifecycle.forkedFrom === plan.sourceId) await lineage.addEdge(plan.sourceId, plan.child.id);
|
|
1678
|
+
return {
|
|
1679
|
+
status: "exists",
|
|
1680
|
+
record: existing
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
await lineage.addEdge(plan.sourceId, plan.child.id);
|
|
1684
|
+
return {
|
|
1685
|
+
status: "created",
|
|
1686
|
+
record: result.record
|
|
1687
|
+
};
|
|
1688
|
+
},
|
|
1689
|
+
delete(plan) {
|
|
1690
|
+
return cascadeReclaim(lineageStore, plan, lineage);
|
|
1691
|
+
}
|
|
1692
|
+
};
|
|
1233
1693
|
}
|
|
1234
1694
|
|
|
1235
1695
|
//#endregion
|
|
@@ -1275,6 +1735,7 @@ var HttpDispatchService = class {
|
|
|
1275
1735
|
default: return this.deps.responses.methodNotAllowed();
|
|
1276
1736
|
}
|
|
1277
1737
|
} catch (error) {
|
|
1738
|
+
if (isNotSupportedError(error)) return notSupportedResponse(notSupportedFromError(error), this.deps.responses);
|
|
1278
1739
|
console.error("Error handling request:", error);
|
|
1279
1740
|
return this.deps.responses.internalError();
|
|
1280
1741
|
}
|
|
@@ -1642,6 +2103,7 @@ var AppendHttpService = class {
|
|
|
1642
2103
|
if (result.conflictReason === "expected-offset") return this.deps.responses.conflict("Expected offset mismatch", { "stream-next-offset": result.offset });
|
|
1643
2104
|
return this.deps.responses.conflict(result.conflictReason === "content-type" ? "Content-Type mismatch" : "Sequence conflict");
|
|
1644
2105
|
}
|
|
2106
|
+
case "busy": return this.deps.responses.text("Stream busy, retry later", 503);
|
|
1645
2107
|
case "stale-epoch": return this.deps.responses.text("Stale producer epoch", 403, { "producer-epoch": String(result.currentEpoch) });
|
|
1646
2108
|
case "producer-gap": return this.deps.responses.conflict("Producer sequence gap", {
|
|
1647
2109
|
"producer-expected-seq": String(result.expectedSeq),
|
|
@@ -1687,7 +2149,8 @@ var CreateHttpService = class {
|
|
|
1687
2149
|
initialData: normalized.initialData,
|
|
1688
2150
|
closed: parsed.wantClosed,
|
|
1689
2151
|
forkedFrom: parsed.forkedFromStreamId,
|
|
1690
|
-
forkOffset: parsed.forkOffset
|
|
2152
|
+
forkOffset: parsed.forkOffset,
|
|
2153
|
+
forkSubOffset: parsed.forkSubOffset
|
|
1691
2154
|
});
|
|
1692
2155
|
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
1693
2156
|
return this.toResponse(result, ctx.request.url);
|
|
@@ -1698,6 +2161,7 @@ var CreateHttpService = class {
|
|
|
1698
2161
|
const expiresAtHeader = request.headers.get("stream-expires-at");
|
|
1699
2162
|
const forkedFromHeader = request.headers.get("stream-forked-from");
|
|
1700
2163
|
const forkOffsetHeader = request.headers.get("stream-fork-offset");
|
|
2164
|
+
const forkSubOffsetHeader = request.headers.get("stream-fork-sub-offset");
|
|
1701
2165
|
if (ttlHeader && !/^(0|[1-9]\d*)$/.test(ttlHeader)) return {
|
|
1702
2166
|
ok: false,
|
|
1703
2167
|
response: this.deps.responses.badRequest("Invalid Stream-TTL format")
|
|
@@ -1714,6 +2178,20 @@ var CreateHttpService = class {
|
|
|
1714
2178
|
ok: false,
|
|
1715
2179
|
response: this.deps.responses.badRequest("Stream-Fork-Offset requires Stream-Forked-From")
|
|
1716
2180
|
};
|
|
2181
|
+
if (forkSubOffsetHeader !== null) {
|
|
2182
|
+
if (!forkedFromHeader) return {
|
|
2183
|
+
ok: false,
|
|
2184
|
+
response: this.deps.responses.badRequest("Stream-Fork-Sub-Offset requires Stream-Forked-From")
|
|
2185
|
+
};
|
|
2186
|
+
if (!/^(0|[1-9]\d*)$/.test(forkSubOffsetHeader)) return {
|
|
2187
|
+
ok: false,
|
|
2188
|
+
response: this.deps.responses.badRequest("Invalid Stream-Fork-Sub-Offset format")
|
|
2189
|
+
};
|
|
2190
|
+
if (parseInt(forkSubOffsetHeader, 10) > 0 && !forkOffsetHeader) return {
|
|
2191
|
+
ok: false,
|
|
2192
|
+
response: this.deps.responses.badRequest("Stream-Fork-Sub-Offset greater than zero requires Stream-Fork-Offset")
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
1717
2195
|
const isFork = !!forkedFromHeader;
|
|
1718
2196
|
return {
|
|
1719
2197
|
ok: true,
|
|
@@ -1722,7 +2200,8 @@ var CreateHttpService = class {
|
|
|
1722
2200
|
expiresAt: expiresAtHeader ?? void 0,
|
|
1723
2201
|
wantClosed: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
1724
2202
|
forkedFromStreamId: forkedFromHeader ? this.deps.path.canonicalizeForkSource(forkedFromHeader) : void 0,
|
|
1725
|
-
forkOffset: forkOffsetHeader ?? void 0
|
|
2203
|
+
forkOffset: forkOffsetHeader ?? void 0,
|
|
2204
|
+
forkSubOffset: forkSubOffsetHeader !== null ? parseInt(forkSubOffsetHeader, 10) : void 0
|
|
1726
2205
|
};
|
|
1727
2206
|
}
|
|
1728
2207
|
normalizeInitialData(data, contentType) {
|
|
@@ -2128,6 +2607,7 @@ var ReadOnlyHttpDispatchService = class {
|
|
|
2128
2607
|
default: return this.deps.responses.methodNotAllowed();
|
|
2129
2608
|
}
|
|
2130
2609
|
} catch (error) {
|
|
2610
|
+
if (isNotSupportedError(error)) return notSupportedResponse(notSupportedFromError(error), this.deps.responses);
|
|
2131
2611
|
console.error("Error handling request:", error);
|
|
2132
2612
|
return this.deps.responses.internalError();
|
|
2133
2613
|
}
|
|
@@ -2188,4 +2668,680 @@ var ReadOnlyHttpHandler = class {
|
|
|
2188
2668
|
};
|
|
2189
2669
|
|
|
2190
2670
|
//#endregion
|
|
2191
|
-
|
|
2671
|
+
//#region src/testing/storage-adapter-contract.ts
|
|
2672
|
+
const TEXT_TYPE = "text/plain";
|
|
2673
|
+
const OFFSET_1 = formatCounter(1);
|
|
2674
|
+
/**
|
|
2675
|
+
* Mechanical enforcement of the seam invariant: every argument and result must
|
|
2676
|
+
* survive `structuredClone` (the Durable Object RPC boundary). The wrapper
|
|
2677
|
+
* clones on the way in AND on the way out, so a non-serializable value crossing
|
|
2678
|
+
* the seam throws on every backend — including in-process ones that would
|
|
2679
|
+
* otherwise pass by reference.
|
|
2680
|
+
*/
|
|
2681
|
+
const clone = (value) => structuredClone(value);
|
|
2682
|
+
function withSerializedSeam(adapter) {
|
|
2683
|
+
const wrapped = {
|
|
2684
|
+
getRecord: async (streamId) => clone(await adapter.getRecord(clone(streamId))),
|
|
2685
|
+
listMessages: async (streamId, options) => clone(await adapter.listMessages(clone(streamId), clone(options))),
|
|
2686
|
+
getProducerState: async (streamId, producerId) => clone(await adapter.getProducerState(clone(streamId), clone(producerId))),
|
|
2687
|
+
append: async (streamId, plan) => clone(await adapter.append(clone(streamId), clone(plan))),
|
|
2688
|
+
awaitChange: async (streamId, options) => clone(await adapter.awaitChange(clone(streamId), clone(options))),
|
|
2689
|
+
scheduleExpiry: (streamId, at) => adapter.scheduleExpiry(clone(streamId), clone(at)),
|
|
2690
|
+
cancelExpiry: (streamId) => adapter.cancelExpiry(clone(streamId)),
|
|
2691
|
+
create: async (plan) => clone(await adapter.create(clone(plan))),
|
|
2692
|
+
delete: async (plan) => clone(await adapter.delete(clone(plan)))
|
|
2693
|
+
};
|
|
2694
|
+
const fork = adapter.fork;
|
|
2695
|
+
if (fork) wrapped.fork = async (plan) => clone(await fork.call(adapter, clone(plan)));
|
|
2696
|
+
return wrapped;
|
|
2697
|
+
}
|
|
2698
|
+
/** Wrap `makeAdapter` so every case exercises the serializability wrapper. */
|
|
2699
|
+
function serialized(makeAdapter) {
|
|
2700
|
+
return async () => withSerializedSeam(await makeAdapter());
|
|
2701
|
+
}
|
|
2702
|
+
function encode(value) {
|
|
2703
|
+
return new TextEncoder().encode(value);
|
|
2704
|
+
}
|
|
2705
|
+
function assert(condition, message) {
|
|
2706
|
+
if (!condition) throw new Error(`storage-adapter-contract: ${message}`);
|
|
2707
|
+
}
|
|
2708
|
+
function assertStatus(result, expected, label) {
|
|
2709
|
+
if (result.status !== expected) throw new Error(`storage-adapter-contract: ${label} — expected status "${expected}", got "${result.status}"`);
|
|
2710
|
+
}
|
|
2711
|
+
function newRecord(id, forkedFrom) {
|
|
2712
|
+
return {
|
|
2713
|
+
id,
|
|
2714
|
+
config: {
|
|
2715
|
+
contentType: TEXT_TYPE,
|
|
2716
|
+
createdAt: 0
|
|
2717
|
+
},
|
|
2718
|
+
lifecycle: forkedFrom ? {
|
|
2719
|
+
forkedFrom,
|
|
2720
|
+
forkOffset: ZERO_OFFSET
|
|
2721
|
+
} : {},
|
|
2722
|
+
currentOffset: ZERO_OFFSET,
|
|
2723
|
+
counter: 0
|
|
2724
|
+
};
|
|
2725
|
+
}
|
|
2726
|
+
async function currentRecord(adapter, id) {
|
|
2727
|
+
const record = await adapter.getRecord(id);
|
|
2728
|
+
assert(record, `expected record for stream "${id}"`);
|
|
2729
|
+
return record;
|
|
2730
|
+
}
|
|
2731
|
+
/** Build an append plan that advances the tail by `texts.length` messages. */
|
|
2732
|
+
function advancePlan(record, texts) {
|
|
2733
|
+
const allocation = allocate(record.counter, texts.length);
|
|
2734
|
+
return {
|
|
2735
|
+
preconditions: {
|
|
2736
|
+
expectedOffset: record.currentOffset,
|
|
2737
|
+
expectedClosed: false
|
|
2738
|
+
},
|
|
2739
|
+
messages: texts.map((value, index) => ({
|
|
2740
|
+
data: encode(value),
|
|
2741
|
+
offset: allocation.offsets[index],
|
|
2742
|
+
timestamp: 0
|
|
2743
|
+
})),
|
|
2744
|
+
recordPatch: {
|
|
2745
|
+
currentOffset: allocation.nextOffset,
|
|
2746
|
+
counter: allocation.endCounter
|
|
2747
|
+
}
|
|
2748
|
+
};
|
|
2749
|
+
}
|
|
2750
|
+
async function appendTexts(adapter, id, texts) {
|
|
2751
|
+
const record = await currentRecord(adapter, id);
|
|
2752
|
+
return adapter.append(id, advancePlan(record, texts));
|
|
2753
|
+
}
|
|
2754
|
+
async function createStream(adapter, id) {
|
|
2755
|
+
const result = await adapter.create({ record: newRecord(id) });
|
|
2756
|
+
assertStatus(result, "created", `create("${id}")`);
|
|
2757
|
+
}
|
|
2758
|
+
/** Bind the adapter's required level-triggered `awaitChange` to a stream id. */
|
|
2759
|
+
function awaitChangeFor(adapter) {
|
|
2760
|
+
return (id, options) => adapter.awaitChange(id, options);
|
|
2761
|
+
}
|
|
2762
|
+
function delay(ms) {
|
|
2763
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2764
|
+
}
|
|
2765
|
+
/** Let a freshly-started `awaitChange` register its waiter before we mutate. */
|
|
2766
|
+
function tick() {
|
|
2767
|
+
return new Promise((resolve) => setTimeout(resolve, 0));
|
|
2768
|
+
}
|
|
2769
|
+
/** Resolves `true` if `promise` is still unsettled after `ms`. */
|
|
2770
|
+
function staysPending(promise, ms) {
|
|
2771
|
+
return Promise.race([promise.then(() => false, () => false), delay(ms).then(() => true)]);
|
|
2772
|
+
}
|
|
2773
|
+
function runAppendContract(makeAdapter, harness) {
|
|
2774
|
+
harness.it("append advances the tail and folds close", async () => {
|
|
2775
|
+
const adapter = await makeAdapter();
|
|
2776
|
+
await createStream(adapter, "s");
|
|
2777
|
+
const appended = await appendTexts(adapter, "s", ["a", "b"]);
|
|
2778
|
+
assertStatus(appended, "appended", "append");
|
|
2779
|
+
assert(appended.status === "appended", "append narrows");
|
|
2780
|
+
assert(appended.record.counter === 2, "counter advanced to 2");
|
|
2781
|
+
assert(appended.record.currentOffset === formatCounter(2), "offset advanced");
|
|
2782
|
+
assert((await adapter.listMessages("s")).length === 2, "two messages listable");
|
|
2783
|
+
const record = await currentRecord(adapter, "s");
|
|
2784
|
+
const closed = await adapter.append("s", {
|
|
2785
|
+
preconditions: {
|
|
2786
|
+
expectedOffset: record.currentOffset,
|
|
2787
|
+
expectedClosed: false
|
|
2788
|
+
},
|
|
2789
|
+
messages: [],
|
|
2790
|
+
recordPatch: { lifecycle: {
|
|
2791
|
+
closed: true,
|
|
2792
|
+
closedAt: 0
|
|
2793
|
+
} }
|
|
2794
|
+
});
|
|
2795
|
+
assertStatus(closed, "appended", "close append");
|
|
2796
|
+
assert(closed.status === "appended" && closed.record.lifecycle.closed === true, "closed folded");
|
|
2797
|
+
});
|
|
2798
|
+
harness.it("append rejects a stale expectedOffset with reason 'offset' and writes nothing", async () => {
|
|
2799
|
+
const adapter = await makeAdapter();
|
|
2800
|
+
await createStream(adapter, "s");
|
|
2801
|
+
await appendTexts(adapter, "s", ["a"]);
|
|
2802
|
+
const stale = await adapter.append("s", {
|
|
2803
|
+
preconditions: {
|
|
2804
|
+
expectedOffset: ZERO_OFFSET,
|
|
2805
|
+
expectedClosed: false
|
|
2806
|
+
},
|
|
2807
|
+
messages: [{
|
|
2808
|
+
data: encode("b"),
|
|
2809
|
+
offset: formatCounter(2),
|
|
2810
|
+
timestamp: 0
|
|
2811
|
+
}],
|
|
2812
|
+
recordPatch: {
|
|
2813
|
+
currentOffset: formatCounter(2),
|
|
2814
|
+
counter: 2
|
|
2815
|
+
}
|
|
2816
|
+
});
|
|
2817
|
+
assertStatus(stale, "precondition-failed", "stale offset");
|
|
2818
|
+
assert(stale.status === "precondition-failed" && stale.reason === "offset", "reason offset");
|
|
2819
|
+
const record = await currentRecord(adapter, "s");
|
|
2820
|
+
assert(record.currentOffset === OFFSET_1 && record.counter === 1, "tail unchanged");
|
|
2821
|
+
assert((await adapter.listMessages("s")).length === 1, "no extra message written");
|
|
2822
|
+
});
|
|
2823
|
+
harness.it("append rejects a violated expectedClosed with reason 'closed' and writes nothing", async () => {
|
|
2824
|
+
const adapter = await makeAdapter();
|
|
2825
|
+
await createStream(adapter, "s");
|
|
2826
|
+
const failed = await adapter.append("s", {
|
|
2827
|
+
preconditions: {
|
|
2828
|
+
expectedOffset: ZERO_OFFSET,
|
|
2829
|
+
expectedClosed: true
|
|
2830
|
+
},
|
|
2831
|
+
messages: [{
|
|
2832
|
+
data: encode("a"),
|
|
2833
|
+
offset: OFFSET_1,
|
|
2834
|
+
timestamp: 0
|
|
2835
|
+
}],
|
|
2836
|
+
recordPatch: {
|
|
2837
|
+
currentOffset: OFFSET_1,
|
|
2838
|
+
counter: 1
|
|
2839
|
+
}
|
|
2840
|
+
});
|
|
2841
|
+
assertStatus(failed, "precondition-failed", "closed precondition");
|
|
2842
|
+
assert(failed.status === "precondition-failed" && failed.reason === "closed", "reason closed");
|
|
2843
|
+
const record = await currentRecord(adapter, "s");
|
|
2844
|
+
assert(record.currentOffset === ZERO_OFFSET && record.counter === 0, "tail unchanged");
|
|
2845
|
+
assert((await adapter.listMessages("s")).length === 0, "no message written");
|
|
2846
|
+
});
|
|
2847
|
+
harness.it("append rejects a failed producer CAS with reason 'producer' and writes nothing", async () => {
|
|
2848
|
+
const adapter = await makeAdapter();
|
|
2849
|
+
await createStream(adapter, "s");
|
|
2850
|
+
const seeded = await adapter.append("s", {
|
|
2851
|
+
preconditions: {
|
|
2852
|
+
expectedOffset: ZERO_OFFSET,
|
|
2853
|
+
expectedClosed: false,
|
|
2854
|
+
producer: {
|
|
2855
|
+
producerId: "p",
|
|
2856
|
+
expected: void 0,
|
|
2857
|
+
next: {
|
|
2858
|
+
epoch: 1,
|
|
2859
|
+
lastSeq: 0
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2862
|
+
},
|
|
2863
|
+
messages: [{
|
|
2864
|
+
data: encode("a"),
|
|
2865
|
+
offset: OFFSET_1,
|
|
2866
|
+
timestamp: 0
|
|
2867
|
+
}],
|
|
2868
|
+
recordPatch: {
|
|
2869
|
+
currentOffset: OFFSET_1,
|
|
2870
|
+
counter: 1
|
|
2871
|
+
}
|
|
2872
|
+
});
|
|
2873
|
+
assertStatus(seeded, "appended", "seed producer");
|
|
2874
|
+
const record = await currentRecord(adapter, "s");
|
|
2875
|
+
const failed = await adapter.append("s", {
|
|
2876
|
+
preconditions: {
|
|
2877
|
+
expectedOffset: record.currentOffset,
|
|
2878
|
+
expectedClosed: false,
|
|
2879
|
+
producer: {
|
|
2880
|
+
producerId: "p",
|
|
2881
|
+
expected: {
|
|
2882
|
+
epoch: 9,
|
|
2883
|
+
lastSeq: 9
|
|
2884
|
+
},
|
|
2885
|
+
next: {
|
|
2886
|
+
epoch: 2,
|
|
2887
|
+
lastSeq: 0
|
|
2888
|
+
}
|
|
2889
|
+
}
|
|
2890
|
+
},
|
|
2891
|
+
messages: [{
|
|
2892
|
+
data: encode("b"),
|
|
2893
|
+
offset: formatCounter(2),
|
|
2894
|
+
timestamp: 0
|
|
2895
|
+
}],
|
|
2896
|
+
recordPatch: {
|
|
2897
|
+
currentOffset: formatCounter(2),
|
|
2898
|
+
counter: 2
|
|
2899
|
+
}
|
|
2900
|
+
});
|
|
2901
|
+
assertStatus(failed, "precondition-failed", "producer CAS");
|
|
2902
|
+
assert(failed.status === "precondition-failed" && failed.reason === "producer", "reason producer");
|
|
2903
|
+
const after = await currentRecord(adapter, "s");
|
|
2904
|
+
assert(after.currentOffset === OFFSET_1 && after.counter === 1, "tail unchanged on CAS failure");
|
|
2905
|
+
assert((await adapter.listMessages("s")).length === 1, "no message written on CAS failure");
|
|
2906
|
+
const producer = await adapter.getProducerState("s", "p");
|
|
2907
|
+
assert(producer?.epoch === 1 && producer.lastSeq === 0, "producer state unchanged");
|
|
2908
|
+
});
|
|
2909
|
+
harness.it("append rejects an absent-expected producer CAS when the producer already exists", async () => {
|
|
2910
|
+
const adapter = await makeAdapter();
|
|
2911
|
+
await createStream(adapter, "s");
|
|
2912
|
+
const seeded = await adapter.append("s", {
|
|
2913
|
+
preconditions: {
|
|
2914
|
+
expectedOffset: ZERO_OFFSET,
|
|
2915
|
+
expectedClosed: false,
|
|
2916
|
+
producer: {
|
|
2917
|
+
producerId: "p",
|
|
2918
|
+
next: {
|
|
2919
|
+
epoch: 1,
|
|
2920
|
+
lastSeq: 0
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
},
|
|
2924
|
+
messages: [{
|
|
2925
|
+
data: encode("a"),
|
|
2926
|
+
offset: OFFSET_1,
|
|
2927
|
+
timestamp: 0
|
|
2928
|
+
}],
|
|
2929
|
+
recordPatch: {
|
|
2930
|
+
currentOffset: OFFSET_1,
|
|
2931
|
+
counter: 1
|
|
2932
|
+
}
|
|
2933
|
+
});
|
|
2934
|
+
assertStatus(seeded, "appended", "seed producer");
|
|
2935
|
+
const record = await currentRecord(adapter, "s");
|
|
2936
|
+
const failed = await adapter.append("s", {
|
|
2937
|
+
preconditions: {
|
|
2938
|
+
expectedOffset: record.currentOffset,
|
|
2939
|
+
expectedClosed: false,
|
|
2940
|
+
producer: {
|
|
2941
|
+
producerId: "p",
|
|
2942
|
+
next: {
|
|
2943
|
+
epoch: 2,
|
|
2944
|
+
lastSeq: 0
|
|
2945
|
+
}
|
|
2946
|
+
}
|
|
2947
|
+
},
|
|
2948
|
+
messages: [{
|
|
2949
|
+
data: encode("b"),
|
|
2950
|
+
offset: formatCounter(2),
|
|
2951
|
+
timestamp: 0
|
|
2952
|
+
}],
|
|
2953
|
+
recordPatch: {
|
|
2954
|
+
currentOffset: formatCounter(2),
|
|
2955
|
+
counter: 2
|
|
2956
|
+
}
|
|
2957
|
+
});
|
|
2958
|
+
assertStatus(failed, "precondition-failed", "absent-expected CAS on existing producer");
|
|
2959
|
+
assert(failed.status === "precondition-failed" && failed.reason === "producer", "reason producer");
|
|
2960
|
+
const producer = await adapter.getProducerState("s", "p");
|
|
2961
|
+
assert(producer?.epoch === 1 && producer.lastSeq === 0, "producer state unchanged");
|
|
2962
|
+
assert((await adapter.listMessages("s")).length === 1, "no message written");
|
|
2963
|
+
});
|
|
2964
|
+
harness.it("append accepts a lifecycle-only TTL touch without advancing the tail", async () => {
|
|
2965
|
+
const adapter = await makeAdapter();
|
|
2966
|
+
await createStream(adapter, "s");
|
|
2967
|
+
const before = await currentRecord(adapter, "s");
|
|
2968
|
+
const touched = await adapter.append("s", {
|
|
2969
|
+
preconditions: {
|
|
2970
|
+
expectedOffset: before.currentOffset,
|
|
2971
|
+
expectedClosed: false
|
|
2972
|
+
},
|
|
2973
|
+
recordPatch: { lifecycle: { expiresAtMs: 1e6 } }
|
|
2974
|
+
});
|
|
2975
|
+
assertStatus(touched, "appended", "touch");
|
|
2976
|
+
assert(touched.status === "appended", "touch narrows");
|
|
2977
|
+
assert(touched.record.currentOffset === before.currentOffset, "touch keeps offset");
|
|
2978
|
+
assert(touched.record.counter === before.counter, "touch keeps counter");
|
|
2979
|
+
assert(touched.record.lifecycle.expiresAtMs === 1e6, "touch renewed deadline");
|
|
2980
|
+
assert((await adapter.listMessages("s")).length === 0, "touch wrote no messages");
|
|
2981
|
+
});
|
|
2982
|
+
}
|
|
2983
|
+
function runReadContract(makeAdapter, harness) {
|
|
2984
|
+
harness.it("listMessages windows by lexicographic offset order: exclusive after, inclusive until", async () => {
|
|
2985
|
+
const adapter = await makeAdapter();
|
|
2986
|
+
await createStream(adapter, "s");
|
|
2987
|
+
const appended = await appendTexts(adapter, "s", [
|
|
2988
|
+
"a",
|
|
2989
|
+
"b",
|
|
2990
|
+
"c",
|
|
2991
|
+
"d"
|
|
2992
|
+
]);
|
|
2993
|
+
assertStatus(appended, "appended", "seed messages");
|
|
2994
|
+
const all = await adapter.listMessages("s");
|
|
2995
|
+
assert(all.length === 4, "four messages listable");
|
|
2996
|
+
const sorted = all.map((m) => m.offset).toSorted();
|
|
2997
|
+
assert(all.every((m, i) => m.offset === sorted[i]), "messages returned in lexicographic offset order");
|
|
2998
|
+
const afterFirst = await adapter.listMessages("s", { after: formatCounter(1) });
|
|
2999
|
+
assert(afterFirst.length === 3, "after excludes the boundary message");
|
|
3000
|
+
assert(afterFirst[0].offset === formatCounter(2), "after starts past the boundary");
|
|
3001
|
+
const untilThird = await adapter.listMessages("s", { until: formatCounter(3) });
|
|
3002
|
+
assert(untilThird.length === 3, "until includes the boundary message");
|
|
3003
|
+
assert(untilThird[2].offset === formatCounter(3), "until ends at the boundary");
|
|
3004
|
+
const window = await adapter.listMessages("s", {
|
|
3005
|
+
after: formatCounter(1),
|
|
3006
|
+
until: formatCounter(3),
|
|
3007
|
+
limit: 1
|
|
3008
|
+
});
|
|
3009
|
+
assert(window.length === 1 && window[0].offset === formatCounter(2), "window + limit");
|
|
3010
|
+
});
|
|
3011
|
+
}
|
|
3012
|
+
function runAwaitChangeContract(makeAdapter, harness) {
|
|
3013
|
+
harness.it("awaitChange returns 'changed' immediately when the tail already advanced", async () => {
|
|
3014
|
+
const adapter = await makeAdapter();
|
|
3015
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3016
|
+
await createStream(adapter, "s");
|
|
3017
|
+
await appendTexts(adapter, "s", ["a"]);
|
|
3018
|
+
const result = await awaitChange("s", {
|
|
3019
|
+
fromOffset: ZERO_OFFSET,
|
|
3020
|
+
observedClosed: false,
|
|
3021
|
+
observedSoftDeleted: false,
|
|
3022
|
+
timeoutMs: 1e3
|
|
3023
|
+
});
|
|
3024
|
+
assertStatus(result, "changed", "immediate change");
|
|
3025
|
+
assert(result.snapshot.currentOffset === OFFSET_1, "snapshot reflects the new tail");
|
|
3026
|
+
});
|
|
3027
|
+
harness.it("awaitChange times out with a fresh snapshot when nothing changes", async () => {
|
|
3028
|
+
const adapter = await makeAdapter();
|
|
3029
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3030
|
+
await createStream(adapter, "s");
|
|
3031
|
+
const record = await currentRecord(adapter, "s");
|
|
3032
|
+
const result = await awaitChange("s", {
|
|
3033
|
+
fromOffset: record.currentOffset,
|
|
3034
|
+
observedClosed: false,
|
|
3035
|
+
observedSoftDeleted: false,
|
|
3036
|
+
timeoutMs: 80
|
|
3037
|
+
});
|
|
3038
|
+
assertStatus(result, "timeout", "timeout");
|
|
3039
|
+
assert(result.snapshot.present === true, "snapshot present");
|
|
3040
|
+
assert(result.snapshot.currentOffset === ZERO_OFFSET, "snapshot at the parked tail");
|
|
3041
|
+
});
|
|
3042
|
+
harness.it("awaitChange wakes a parked waiter on a committing append", async () => {
|
|
3043
|
+
const adapter = await makeAdapter();
|
|
3044
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3045
|
+
await createStream(adapter, "s");
|
|
3046
|
+
const record = await currentRecord(adapter, "s");
|
|
3047
|
+
const pending = awaitChange("s", {
|
|
3048
|
+
fromOffset: record.currentOffset,
|
|
3049
|
+
observedClosed: false,
|
|
3050
|
+
observedSoftDeleted: false,
|
|
3051
|
+
timeoutMs: 2e3
|
|
3052
|
+
});
|
|
3053
|
+
await tick();
|
|
3054
|
+
await appendTexts(adapter, "s", ["a"]);
|
|
3055
|
+
const result = await pending;
|
|
3056
|
+
assertStatus(result, "changed", "wake on append");
|
|
3057
|
+
assert(result.snapshot.currentOffset === OFFSET_1, "snapshot reflects the append");
|
|
3058
|
+
});
|
|
3059
|
+
harness.it("awaitChange wakes a parked waiter on a close transition", async () => {
|
|
3060
|
+
const adapter = await makeAdapter();
|
|
3061
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3062
|
+
await createStream(adapter, "s");
|
|
3063
|
+
const record = await currentRecord(adapter, "s");
|
|
3064
|
+
const pending = awaitChange("s", {
|
|
3065
|
+
fromOffset: record.currentOffset,
|
|
3066
|
+
observedClosed: false,
|
|
3067
|
+
observedSoftDeleted: false,
|
|
3068
|
+
timeoutMs: 2e3
|
|
3069
|
+
});
|
|
3070
|
+
await tick();
|
|
3071
|
+
const closed = await adapter.append("s", {
|
|
3072
|
+
preconditions: {
|
|
3073
|
+
expectedOffset: record.currentOffset,
|
|
3074
|
+
expectedClosed: false
|
|
3075
|
+
},
|
|
3076
|
+
messages: [],
|
|
3077
|
+
recordPatch: { lifecycle: {
|
|
3078
|
+
closed: true,
|
|
3079
|
+
closedAt: 0
|
|
3080
|
+
} }
|
|
3081
|
+
});
|
|
3082
|
+
assertStatus(closed, "appended", "close append");
|
|
3083
|
+
const result = await pending;
|
|
3084
|
+
assertStatus(result, "changed", "wake on close");
|
|
3085
|
+
assert(result.snapshot.closed === true, "snapshot reports closed");
|
|
3086
|
+
});
|
|
3087
|
+
harness.it("awaitChange wakes a parked waiter on a soft-delete transition", async () => {
|
|
3088
|
+
const adapter = await makeAdapter();
|
|
3089
|
+
if (!adapter.fork) return;
|
|
3090
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3091
|
+
await createStream(adapter, "parent");
|
|
3092
|
+
const forked = await adapter.fork({
|
|
3093
|
+
child: newRecord("child", "parent"),
|
|
3094
|
+
sourceId: "parent",
|
|
3095
|
+
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3096
|
+
});
|
|
3097
|
+
assertStatus(forked, "created", "fork child");
|
|
3098
|
+
const record = await currentRecord(adapter, "parent");
|
|
3099
|
+
const pending = awaitChange("parent", {
|
|
3100
|
+
fromOffset: record.currentOffset,
|
|
3101
|
+
observedClosed: false,
|
|
3102
|
+
observedSoftDeleted: false,
|
|
3103
|
+
timeoutMs: 2e3
|
|
3104
|
+
});
|
|
3105
|
+
await tick();
|
|
3106
|
+
const deleted = await adapter.delete({
|
|
3107
|
+
streamId: "parent",
|
|
3108
|
+
reason: "delete"
|
|
3109
|
+
});
|
|
3110
|
+
assertStatus(deleted, "retained-soft-deleted", "soft delete parent");
|
|
3111
|
+
const result = await pending;
|
|
3112
|
+
assertStatus(result, "changed", "wake on soft-delete");
|
|
3113
|
+
assert(result.snapshot.softDeleted === true, "snapshot reports soft-deleted");
|
|
3114
|
+
});
|
|
3115
|
+
harness.it("awaitChange wakes a parked waiter on a purge", async () => {
|
|
3116
|
+
const adapter = await makeAdapter();
|
|
3117
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3118
|
+
await createStream(adapter, "s");
|
|
3119
|
+
const record = await currentRecord(adapter, "s");
|
|
3120
|
+
const pending = awaitChange("s", {
|
|
3121
|
+
fromOffset: record.currentOffset,
|
|
3122
|
+
observedClosed: false,
|
|
3123
|
+
observedSoftDeleted: false,
|
|
3124
|
+
timeoutMs: 2e3
|
|
3125
|
+
});
|
|
3126
|
+
await tick();
|
|
3127
|
+
const deleted = await adapter.delete({
|
|
3128
|
+
streamId: "s",
|
|
3129
|
+
reason: "delete"
|
|
3130
|
+
});
|
|
3131
|
+
assertStatus(deleted, "purged", "purge");
|
|
3132
|
+
const result = await pending;
|
|
3133
|
+
assertStatus(result, "changed", "wake on purge");
|
|
3134
|
+
assert(result.snapshot.present === false, "snapshot reports the record gone");
|
|
3135
|
+
});
|
|
3136
|
+
harness.it("awaitChange treats an offset regression (purge then re-create) as changed", async () => {
|
|
3137
|
+
const adapter = await makeAdapter();
|
|
3138
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3139
|
+
await createStream(adapter, "s");
|
|
3140
|
+
await appendTexts(adapter, "s", ["a", "b"]);
|
|
3141
|
+
const parked = await currentRecord(adapter, "s");
|
|
3142
|
+
const deleted = await adapter.delete({
|
|
3143
|
+
streamId: "s",
|
|
3144
|
+
reason: "delete"
|
|
3145
|
+
});
|
|
3146
|
+
assertStatus(deleted, "purged", "purge");
|
|
3147
|
+
await createStream(adapter, "s");
|
|
3148
|
+
const result = await awaitChange("s", {
|
|
3149
|
+
fromOffset: parked.currentOffset,
|
|
3150
|
+
observedClosed: false,
|
|
3151
|
+
observedSoftDeleted: false,
|
|
3152
|
+
timeoutMs: 200
|
|
3153
|
+
});
|
|
3154
|
+
assertStatus(result, "changed", "offset regression detected");
|
|
3155
|
+
assert(result.snapshot.currentOffset === ZERO_OFFSET, "snapshot shows the new incarnation");
|
|
3156
|
+
});
|
|
3157
|
+
harness.it("awaitChange survives the lost-notify race (a commit before registration)", async () => {
|
|
3158
|
+
const adapter = await makeAdapter();
|
|
3159
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3160
|
+
await createStream(adapter, "s");
|
|
3161
|
+
await appendTexts(adapter, "s", ["a"]);
|
|
3162
|
+
const result = await awaitChange("s", {
|
|
3163
|
+
fromOffset: ZERO_OFFSET,
|
|
3164
|
+
observedClosed: false,
|
|
3165
|
+
observedSoftDeleted: false,
|
|
3166
|
+
timeoutMs: 200
|
|
3167
|
+
});
|
|
3168
|
+
assertStatus(result, "changed", "lost-notify re-check");
|
|
3169
|
+
assert(result.snapshot.currentOffset === OFFSET_1, "re-read caught the missed commit");
|
|
3170
|
+
});
|
|
3171
|
+
harness.it("awaitChange ignores a non-advancing wake and resolves on the real advance", async () => {
|
|
3172
|
+
const adapter = await makeAdapter();
|
|
3173
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3174
|
+
await createStream(adapter, "s");
|
|
3175
|
+
const parked = await currentRecord(adapter, "s");
|
|
3176
|
+
const pending = awaitChange("s", {
|
|
3177
|
+
fromOffset: parked.currentOffset,
|
|
3178
|
+
observedClosed: false,
|
|
3179
|
+
observedSoftDeleted: false,
|
|
3180
|
+
timeoutMs: 4e3
|
|
3181
|
+
});
|
|
3182
|
+
await tick();
|
|
3183
|
+
const touched = await adapter.append("s", {
|
|
3184
|
+
preconditions: {
|
|
3185
|
+
expectedOffset: parked.currentOffset,
|
|
3186
|
+
expectedClosed: false
|
|
3187
|
+
},
|
|
3188
|
+
recordPatch: { lifecycle: { expiresAtMs: 1e6 } }
|
|
3189
|
+
});
|
|
3190
|
+
assertStatus(touched, "appended", "touch");
|
|
3191
|
+
assert(await staysPending(pending, 60), "waiter did not resolve on a non-advancing wake");
|
|
3192
|
+
await appendTexts(adapter, "s", ["a"]);
|
|
3193
|
+
const result = await pending;
|
|
3194
|
+
assertStatus(result, "changed", "resolve on real advance");
|
|
3195
|
+
assert(result.snapshot.currentOffset === OFFSET_1, "snapshot reflects the advance");
|
|
3196
|
+
});
|
|
3197
|
+
}
|
|
3198
|
+
function runLifecycleContract(makeAdapter, harness) {
|
|
3199
|
+
harness.it("create is idempotent (second create returns 'exists')", async () => {
|
|
3200
|
+
const adapter = await makeAdapter();
|
|
3201
|
+
const created = await adapter.create({ record: newRecord("s") });
|
|
3202
|
+
assertStatus(created, "created", "first create");
|
|
3203
|
+
const again = await adapter.create({ record: newRecord("s") });
|
|
3204
|
+
assertStatus(again, "exists", "second create");
|
|
3205
|
+
assert(again.status === "exists" && again.record.id === "s", "exists returns the record");
|
|
3206
|
+
});
|
|
3207
|
+
harness.it("create persists a record that arrives already closed", async () => {
|
|
3208
|
+
const adapter = await makeAdapter();
|
|
3209
|
+
const closedRecord = {
|
|
3210
|
+
...newRecord("s"),
|
|
3211
|
+
lifecycle: {
|
|
3212
|
+
closed: true,
|
|
3213
|
+
closedAt: 0
|
|
3214
|
+
}
|
|
3215
|
+
};
|
|
3216
|
+
const created = await adapter.create({ record: closedRecord });
|
|
3217
|
+
assertStatus(created, "created", "create closed record");
|
|
3218
|
+
const record = await currentRecord(adapter, "s");
|
|
3219
|
+
assert(record.lifecycle.closed === true, "stream created closed");
|
|
3220
|
+
assert(record.lifecycle.closedAt === 0, "closedAt persisted");
|
|
3221
|
+
});
|
|
3222
|
+
harness.it("fork is capability-by-presence: omitting it is a valid, unsupported configuration", async () => {
|
|
3223
|
+
const adapter = await makeAdapter();
|
|
3224
|
+
if (adapter.fork === void 0) {
|
|
3225
|
+
assert(typeof adapter.create === "function" && typeof adapter.delete === "function", "a forkless adapter still provides the required create/delete intents");
|
|
3226
|
+
return;
|
|
3227
|
+
}
|
|
3228
|
+
assert(typeof adapter.fork === "function", "fork capability is a callable method when present");
|
|
3229
|
+
});
|
|
3230
|
+
harness.it("fork creates a child and is idempotent; a missing source is 'fork-source-gone'", async () => {
|
|
3231
|
+
const adapter = await makeAdapter();
|
|
3232
|
+
if (!adapter.fork) return;
|
|
3233
|
+
await createStream(adapter, "parent");
|
|
3234
|
+
const forked = await adapter.fork({
|
|
3235
|
+
child: newRecord("child", "parent"),
|
|
3236
|
+
sourceId: "parent",
|
|
3237
|
+
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3238
|
+
});
|
|
3239
|
+
assertStatus(forked, "created", "fork");
|
|
3240
|
+
assert(await adapter.getRecord("child") !== null, "child materialized");
|
|
3241
|
+
const again = await adapter.fork({
|
|
3242
|
+
child: newRecord("child", "parent"),
|
|
3243
|
+
sourceId: "parent",
|
|
3244
|
+
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3245
|
+
});
|
|
3246
|
+
assertStatus(again, "exists", "idempotent fork");
|
|
3247
|
+
assert(again.status === "exists" && again.record.id === "child", "fork exists returns the existing child record");
|
|
3248
|
+
assert(again.status === "exists" && again.record.lifecycle.forkedFrom === "parent", "existing child record carries its lineage");
|
|
3249
|
+
const gone = await adapter.fork({
|
|
3250
|
+
child: newRecord("orphan", "missing"),
|
|
3251
|
+
sourceId: "missing",
|
|
3252
|
+
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3253
|
+
});
|
|
3254
|
+
assertStatus(gone, "fork-source-gone", "missing source");
|
|
3255
|
+
});
|
|
3256
|
+
harness.it("delete purges a stream with no dependents", async () => {
|
|
3257
|
+
const adapter = await makeAdapter();
|
|
3258
|
+
await createStream(adapter, "s");
|
|
3259
|
+
const deleted = await adapter.delete({
|
|
3260
|
+
streamId: "s",
|
|
3261
|
+
reason: "delete"
|
|
3262
|
+
});
|
|
3263
|
+
assertStatus(deleted, "purged", "purge");
|
|
3264
|
+
assert(await adapter.getRecord("s") === null, "record gone after purge");
|
|
3265
|
+
});
|
|
3266
|
+
harness.it("delete is 'not-found' for an absent stream", async () => {
|
|
3267
|
+
const adapter = await makeAdapter();
|
|
3268
|
+
const deleted = await adapter.delete({
|
|
3269
|
+
streamId: "missing",
|
|
3270
|
+
reason: "delete"
|
|
3271
|
+
});
|
|
3272
|
+
assertStatus(deleted, "not-found", "not-found");
|
|
3273
|
+
});
|
|
3274
|
+
harness.it("delete soft-deletes an ancestor with dependents, then cascade-purges", async () => {
|
|
3275
|
+
const adapter = await makeAdapter();
|
|
3276
|
+
if (!adapter.fork) return;
|
|
3277
|
+
await createStream(adapter, "parent");
|
|
3278
|
+
const forked = await adapter.fork({
|
|
3279
|
+
child: newRecord("child", "parent"),
|
|
3280
|
+
sourceId: "parent",
|
|
3281
|
+
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3282
|
+
});
|
|
3283
|
+
assertStatus(forked, "created", "fork child");
|
|
3284
|
+
const retained = await adapter.delete({
|
|
3285
|
+
streamId: "parent",
|
|
3286
|
+
reason: "delete"
|
|
3287
|
+
});
|
|
3288
|
+
assertStatus(retained, "retained-soft-deleted", "soft delete parent");
|
|
3289
|
+
assert((await adapter.getRecord("parent"))?.lifecycle.softDeleted === true, "parent soft-deleted");
|
|
3290
|
+
const gone = await adapter.delete({
|
|
3291
|
+
streamId: "parent",
|
|
3292
|
+
reason: "delete"
|
|
3293
|
+
});
|
|
3294
|
+
assertStatus(gone, "gone", "re-delete soft-deleted ancestor");
|
|
3295
|
+
const purged = await adapter.delete({
|
|
3296
|
+
streamId: "child",
|
|
3297
|
+
reason: "delete"
|
|
3298
|
+
});
|
|
3299
|
+
assertStatus(purged, "purged", "purge child");
|
|
3300
|
+
assert(await adapter.getRecord("child") === null, "child gone");
|
|
3301
|
+
assert(await adapter.getRecord("parent") === null, "parent cascade-purged");
|
|
3302
|
+
});
|
|
3303
|
+
}
|
|
3304
|
+
function runCancellationContract(makeAdapter, harness) {
|
|
3305
|
+
harness.it("raceAbortAwaitChange resolves timeout-shaped on caller abort without rejecting", async () => {
|
|
3306
|
+
const adapter = await makeAdapter();
|
|
3307
|
+
const awaitChange = awaitChangeFor(adapter);
|
|
3308
|
+
await createStream(adapter, "s");
|
|
3309
|
+
const record = await currentRecord(adapter, "s");
|
|
3310
|
+
const fallback = buildChangeSnapshot(record);
|
|
3311
|
+
const controller = new AbortController();
|
|
3312
|
+
const wait = awaitChange("s", {
|
|
3313
|
+
fromOffset: record.currentOffset,
|
|
3314
|
+
observedClosed: false,
|
|
3315
|
+
observedSoftDeleted: false,
|
|
3316
|
+
timeoutMs: 150
|
|
3317
|
+
});
|
|
3318
|
+
const raced = raceAbortAwaitChange(wait, fallback, controller.signal);
|
|
3319
|
+
controller.abort();
|
|
3320
|
+
const result = await raced;
|
|
3321
|
+
assertStatus(result, "timeout", "aborted race");
|
|
3322
|
+
assert(result.snapshot === fallback, "abort surfaces the caller's fallback snapshot");
|
|
3323
|
+
await wait;
|
|
3324
|
+
});
|
|
3325
|
+
}
|
|
3326
|
+
/**
|
|
3327
|
+
* Register the full storage-adapter contract against `makeAdapter` using the
|
|
3328
|
+
* provided test harness. Wrap in the caller's own `describe` for grouping:
|
|
3329
|
+
*
|
|
3330
|
+
* ```ts
|
|
3331
|
+
* import { it } from "vitest";
|
|
3332
|
+
* describe("memory adapter contract", () => {
|
|
3333
|
+
* runStorageAdapterContract(() => createMemoryStorageAdapter(), { it });
|
|
3334
|
+
* });
|
|
3335
|
+
* ```
|
|
3336
|
+
*/
|
|
3337
|
+
function runStorageAdapterContract(makeAdapter, harness) {
|
|
3338
|
+
const make = serialized(makeAdapter);
|
|
3339
|
+
runAppendContract(make, harness);
|
|
3340
|
+
runReadContract(make, harness);
|
|
3341
|
+
runAwaitChangeContract(make, harness);
|
|
3342
|
+
runLifecycleContract(make, harness);
|
|
3343
|
+
runCancellationContract(make, harness);
|
|
3344
|
+
}
|
|
3345
|
+
|
|
3346
|
+
//#endregion
|
|
3347
|
+
export { HttpHandler, NotSupportedError, ReadOnlyHttpHandler, StreamProtocol, ZERO_OFFSET, bindStream, buildChangeSnapshot, cascadeReclaim, changeSnapshotDiffers, compareOffsets, copyOnForkReclaim, createHttpHandler, createMemoryStorageAdapter, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, plainPurge, refCountLineage, reverseIndexLineage, runAwaitChangeLoop, runStorageAdapterContract, ttlOnlyReclaim, unsupported };
|