@streamsy/core 0.0.2 → 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 +440 -69
- package/dist/index.js +2019 -503
- 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
|
-
nextOffset: 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,99 +94,236 @@ 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
|
-
function appendedResult(
|
|
191
|
+
function appendedResult(offset, validation, closed) {
|
|
181
192
|
if (validation?.kind === "accepted") return {
|
|
182
193
|
status: "appended",
|
|
183
|
-
|
|
194
|
+
offset,
|
|
184
195
|
producerEpoch: validation.proposedState.epoch,
|
|
185
196
|
producerSeq: validation.proposedState.lastSeq,
|
|
186
197
|
closed
|
|
187
198
|
};
|
|
188
199
|
return {
|
|
189
200
|
status: "appended",
|
|
190
|
-
|
|
201
|
+
offset,
|
|
191
202
|
closed
|
|
192
203
|
};
|
|
193
204
|
}
|
|
205
|
+
function expectedOffsetConflict(record, options) {
|
|
206
|
+
if (options.expectedOffset === void 0 || options.expectedOffset === record.currentOffset) return null;
|
|
207
|
+
return {
|
|
208
|
+
status: "conflict",
|
|
209
|
+
conflictReason: "expected-offset",
|
|
210
|
+
offset: record.currentOffset
|
|
211
|
+
};
|
|
212
|
+
}
|
|
194
213
|
var AppendService = class {
|
|
195
214
|
constructor(deps) {
|
|
196
215
|
this.deps = deps;
|
|
197
216
|
}
|
|
198
|
-
|
|
199
|
-
if (!record) return {
|
|
200
|
-
|
|
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
|
+
};
|
|
201
226
|
const isClosed = record.lifecycle.closed === true;
|
|
202
227
|
const wantClose = options.close === true;
|
|
203
228
|
const hasBody = options.data.byteLength > 0;
|
|
204
229
|
let producerValidation;
|
|
205
230
|
if (options.producer) {
|
|
206
|
-
|
|
207
|
-
if (
|
|
208
|
-
|
|
209
|
-
|
|
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
|
+
};
|
|
210
236
|
}
|
|
211
237
|
if (wantClose && !hasBody) {
|
|
212
238
|
if (isClosed) return {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
239
|
+
kind: "terminal",
|
|
240
|
+
result: {
|
|
241
|
+
status: "appended",
|
|
242
|
+
offset: record.currentOffset,
|
|
243
|
+
closed: true
|
|
244
|
+
}
|
|
216
245
|
};
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
246
|
+
const casConflict$1 = expectedOffsetConflict(record, options);
|
|
247
|
+
if (casConflict$1) return {
|
|
248
|
+
kind: "terminal",
|
|
249
|
+
result: casConflict$1
|
|
250
|
+
};
|
|
251
|
+
return this.commitDecision(record, [], options, producerState, producerValidation, true);
|
|
221
252
|
}
|
|
222
253
|
if (isClosed) return {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
254
|
+
kind: "terminal",
|
|
255
|
+
result: {
|
|
256
|
+
status: "conflict",
|
|
257
|
+
conflictReason: "closed",
|
|
258
|
+
closed: true,
|
|
259
|
+
offset: record.currentOffset
|
|
260
|
+
}
|
|
227
261
|
};
|
|
228
262
|
if (!contentTypeMatches(record.config.contentType, options.contentType)) return {
|
|
229
|
-
|
|
230
|
-
|
|
263
|
+
kind: "terminal",
|
|
264
|
+
result: {
|
|
265
|
+
status: "conflict",
|
|
266
|
+
conflictReason: "content-type"
|
|
267
|
+
}
|
|
231
268
|
};
|
|
232
269
|
if (options.seq && record.lifecycle.lastSeq && options.seq <= record.lifecycle.lastSeq) return {
|
|
233
|
-
|
|
234
|
-
|
|
270
|
+
kind: "terminal",
|
|
271
|
+
result: {
|
|
272
|
+
status: "conflict",
|
|
273
|
+
conflictReason: "sequence"
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
const casConflict = expectedOffsetConflict(record, options);
|
|
277
|
+
if (casConflict) return {
|
|
278
|
+
kind: "terminal",
|
|
279
|
+
result: casConflict
|
|
235
280
|
};
|
|
236
281
|
const processed = frameMessages(options.data, record.config.contentType);
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
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
|
+
};
|
|
241
324
|
}
|
|
242
325
|
};
|
|
243
326
|
|
|
244
|
-
//#endregion
|
|
245
|
-
//#region src/protocol/helpers/offset-generator.ts
|
|
246
|
-
const ZERO_OFFSET = `${"0".repeat(16)}_${"0".repeat(16)}`;
|
|
247
|
-
const OFFSET_REGEX = /^\d{1,16}_\d{1,16}$/;
|
|
248
|
-
function isValidOffset(offset) {
|
|
249
|
-
return OFFSET_REGEX.test(offset);
|
|
250
|
-
}
|
|
251
|
-
function compareOffsets(a, b) {
|
|
252
|
-
return a === b ? 0 : a < b ? -1 : 1;
|
|
253
|
-
}
|
|
254
|
-
function formatCounter(counter) {
|
|
255
|
-
return `${String(counter).padStart(16, "0")}_${"0".repeat(16)}`;
|
|
256
|
-
}
|
|
257
|
-
function parseCounter(offset) {
|
|
258
|
-
return parseInt(offset.split("_")[0] ?? "0", 10);
|
|
259
|
-
}
|
|
260
|
-
function allocate(counter, count) {
|
|
261
|
-
const offsets = [];
|
|
262
|
-
for (let i = 1; i <= count; i++) offsets.push(formatCounter(counter + i));
|
|
263
|
-
const endCounter = counter + count;
|
|
264
|
-
return {
|
|
265
|
-
endCounter,
|
|
266
|
-
offsets,
|
|
267
|
-
nextOffset: count > 0 ? formatCounter(endCounter) : formatCounter(counter)
|
|
268
|
-
};
|
|
269
|
-
}
|
|
270
|
-
|
|
271
327
|
//#endregion
|
|
272
328
|
//#region src/protocol/read-service.ts
|
|
273
329
|
function normalizeReadOffset(offset) {
|
|
@@ -306,6 +362,32 @@ function generateCursor(clock, previous, random = Math.random) {
|
|
|
306
362
|
return String(previousInterval + Math.max(1, Math.floor(random() * 180)));
|
|
307
363
|
}
|
|
308
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
|
+
|
|
309
391
|
//#endregion
|
|
310
392
|
//#region src/protocol/live-read-service.ts
|
|
311
393
|
var LiveReadService = class {
|
|
@@ -351,18 +433,26 @@ var LiveReadService = class {
|
|
|
351
433
|
cursor: generateCursor(this.deps.clock, options.cursor)
|
|
352
434
|
};
|
|
353
435
|
}
|
|
354
|
-
|
|
355
|
-
const immediate = await this.deps.readOwn(
|
|
436
|
+
const fromOffset = isValidOffset(options.offset) ? options.offset : ZERO_OFFSET;
|
|
437
|
+
const immediate = await this.deps.readOwn(fromOffset);
|
|
356
438
|
if (immediate.messages.length > 0) return {
|
|
357
439
|
status: "ok",
|
|
358
440
|
...immediate,
|
|
359
441
|
upToDate: true,
|
|
360
442
|
cursor: generateCursor(this.deps.clock, options.cursor)
|
|
361
443
|
};
|
|
362
|
-
const
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
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);
|
|
366
456
|
const latest = await this.deps.store.getRecord();
|
|
367
457
|
if (!latest) return {
|
|
368
458
|
status: "not-found",
|
|
@@ -378,11 +468,11 @@ var LiveReadService = class {
|
|
|
378
468
|
upToDate: false,
|
|
379
469
|
cursor: ""
|
|
380
470
|
};
|
|
381
|
-
const r = await this.deps.readOwn(
|
|
471
|
+
const r = await this.deps.readOwn(fromOffset);
|
|
382
472
|
const reachedTail = r.nextOffset === latest.currentOffset;
|
|
383
473
|
const hasMessages = r.messages.length > 0;
|
|
384
474
|
return {
|
|
385
|
-
status: hasMessages ? "ok" : wait.status === "timeout"
|
|
475
|
+
status: hasMessages ? "ok" : wait.status === "timeout" ? "timeout" : "ok",
|
|
386
476
|
messages: r.messages,
|
|
387
477
|
nextOffset: r.nextOffset,
|
|
388
478
|
upToDate: true,
|
|
@@ -393,28 +483,66 @@ var LiveReadService = class {
|
|
|
393
483
|
};
|
|
394
484
|
|
|
395
485
|
//#endregion
|
|
396
|
-
//#region src/protocol/helpers/
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
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
|
+
|
|
518
|
+
//#endregion
|
|
519
|
+
//#region src/protocol/helpers/expiry-policy.ts
|
|
520
|
+
var ExpiryPolicy = class {
|
|
521
|
+
constructor(deps) {
|
|
522
|
+
this.deps = deps;
|
|
523
|
+
}
|
|
401
524
|
computeExpiresAtMs(config) {
|
|
402
525
|
if (config.ttlSeconds !== void 0) return this.deps.clock.now() + config.ttlSeconds * 1e3;
|
|
403
526
|
if (config.expiresAt) return this.deps.clock.date(config.expiresAt).getTime();
|
|
404
527
|
return void 0;
|
|
405
528
|
}
|
|
406
529
|
async touch(stream, record, reason) {
|
|
407
|
-
if (record.config.ttlSeconds === void 0) return;
|
|
408
|
-
if (reason === "live-read") return;
|
|
530
|
+
if (record.config.ttlSeconds === void 0) return record;
|
|
531
|
+
if (reason === "live-read") return record;
|
|
409
532
|
const expiresAtMs = this.deps.clock.now() + record.config.ttlSeconds * 1e3;
|
|
410
|
-
await stream.
|
|
411
|
-
|
|
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;
|
|
412
540
|
}
|
|
413
541
|
async scheduleExpiry(record) {
|
|
414
542
|
const at = record.lifecycle.expiresAtMs;
|
|
415
543
|
if (at !== void 0) {
|
|
416
544
|
const stream = await this.deps.resolve(record.id);
|
|
417
|
-
await stream.scheduleExpiry(at
|
|
545
|
+
await stream.scheduleExpiry(at);
|
|
418
546
|
}
|
|
419
547
|
}
|
|
420
548
|
/**
|
|
@@ -445,6 +573,7 @@ function configMatches(existing, options) {
|
|
|
445
573
|
if (!contentTypeMatches(existing.config.contentType, contentType)) return false;
|
|
446
574
|
if ((options.forkedFrom ?? void 0) !== existing.lifecycle.forkedFrom) return false;
|
|
447
575
|
if (options.forkOffset !== void 0 && options.forkOffset !== existing.lifecycle.forkOffset) return false;
|
|
576
|
+
if ((options.forkSubOffset ?? 0) !== (existing.lifecycle.forkSubOffset ?? 0)) return false;
|
|
448
577
|
const inheritedForkExpiry = options.forkedFrom && options.ttlSeconds === void 0 && options.expiresAt === void 0;
|
|
449
578
|
if (existing.config.ttlSeconds !== options.ttlSeconds && !inheritedForkExpiry) return false;
|
|
450
579
|
if (existing.config.expiresAt !== options.expiresAt && !inheritedForkExpiry) return false;
|
|
@@ -457,27 +586,31 @@ var CreateStreamService = class {
|
|
|
457
586
|
constructor(deps) {
|
|
458
587
|
this.deps = deps;
|
|
459
588
|
}
|
|
460
|
-
|
|
461
|
-
if (record) return
|
|
462
|
-
|
|
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" };
|
|
463
595
|
const contentType = options.contentType ?? "application/octet-stream";
|
|
464
|
-
const initialMessages =
|
|
596
|
+
const initialMessages = this.initialMessages(options.initialData, contentType, 0);
|
|
465
597
|
const wantClosed = options.closed === true;
|
|
466
|
-
const newRecord = this.deps.
|
|
467
|
-
const
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
if (wantClosed) {
|
|
473
|
-
const latest = await this.deps.store.getRecord() ?? newRecord;
|
|
474
|
-
final = await this.deps.mutators.closeRecord(latest, []);
|
|
475
|
-
}
|
|
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
|
+
};
|
|
476
604
|
return {
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
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
|
+
})
|
|
481
614
|
};
|
|
482
615
|
}
|
|
483
616
|
resultForExisting(existing, options) {
|
|
@@ -500,10 +633,35 @@ var CreateStreamService = class {
|
|
|
500
633
|
closed: existing.lifecycle.closed === true
|
|
501
634
|
};
|
|
502
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
|
+
}
|
|
503
661
|
};
|
|
504
662
|
|
|
505
663
|
//#endregion
|
|
506
|
-
//#region src/protocol/helpers/fork-
|
|
664
|
+
//#region src/protocol/helpers/fork-plan-builder.ts
|
|
507
665
|
function resolveForkExpiry(opts, source) {
|
|
508
666
|
if (opts.ttlSeconds !== void 0) return { ttlSeconds: opts.ttlSeconds };
|
|
509
667
|
if (opts.expiresAt) return { expiresAt: opts.expiresAt };
|
|
@@ -511,121 +669,154 @@ function resolveForkExpiry(opts, source) {
|
|
|
511
669
|
if (source.config.expiresAt) return { expiresAt: source.config.expiresAt };
|
|
512
670
|
return {};
|
|
513
671
|
}
|
|
514
|
-
var
|
|
672
|
+
var ForkPlanBuilder = class {
|
|
515
673
|
constructor(deps) {
|
|
516
674
|
this.deps = deps;
|
|
517
675
|
}
|
|
518
|
-
|
|
519
|
-
const sourcePath = options.forkedFrom;
|
|
520
|
-
const sourceStream = await this.deps.resolve(sourcePath);
|
|
521
|
-
await this.deps.mutators.expireIfNeeded(sourceStream);
|
|
522
|
-
const source = await sourceStream.getRecord();
|
|
676
|
+
build(targetId, sourcePath, source, options, sourceTail) {
|
|
523
677
|
if (!source) return {
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
678
|
+
kind: "terminal",
|
|
679
|
+
result: {
|
|
680
|
+
status: "not-found",
|
|
681
|
+
nextOffset: "",
|
|
682
|
+
contentType: "",
|
|
683
|
+
errorMessage: `Source stream not found: ${sourcePath}`
|
|
684
|
+
}
|
|
528
685
|
};
|
|
529
686
|
if (source.lifecycle.softDeleted) return {
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
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
|
+
}
|
|
535
695
|
};
|
|
536
696
|
const forkOffset = options.forkOffset ?? source.currentOffset;
|
|
537
697
|
if (!isValidOffset(forkOffset)) return {
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
698
|
+
kind: "terminal",
|
|
699
|
+
result: {
|
|
700
|
+
status: "bad-request",
|
|
701
|
+
nextOffset: "",
|
|
702
|
+
contentType: "",
|
|
703
|
+
errorMessage: "Invalid Stream-Fork-Offset format"
|
|
704
|
+
}
|
|
542
705
|
};
|
|
543
706
|
if (compareOffsets(forkOffset, ZERO_OFFSET) < 0 || compareOffsets(forkOffset, source.currentOffset) > 0) return {
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
707
|
+
kind: "terminal",
|
|
708
|
+
result: {
|
|
709
|
+
status: "bad-request",
|
|
710
|
+
nextOffset: "",
|
|
711
|
+
contentType: "",
|
|
712
|
+
errorMessage: "Stream-Fork-Offset exceeds source tail"
|
|
713
|
+
}
|
|
548
714
|
};
|
|
549
715
|
let contentType = options.contentType;
|
|
550
716
|
if (!contentType || contentType.trim() === "") contentType = source.config.contentType;
|
|
551
717
|
else if (!contentTypeMatches(contentType, source.config.contentType)) return {
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
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
|
+
}
|
|
557
737
|
};
|
|
558
738
|
const expiry = resolveForkExpiry(options, source);
|
|
559
|
-
const
|
|
739
|
+
const baseRecord = this.deps.newRecord(targetId, contentType, {
|
|
560
740
|
...options,
|
|
561
741
|
...expiry
|
|
562
742
|
}, {
|
|
563
743
|
forkedFrom: sourcePath,
|
|
564
|
-
forkOffset
|
|
744
|
+
forkOffset,
|
|
745
|
+
...subOffset !== void 0 && subOffset > 0 ? { forkSubOffset: subOffset } : {}
|
|
565
746
|
});
|
|
566
|
-
const initialMessages =
|
|
567
|
-
const
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
conflictReason: "config-mismatch",
|
|
574
|
-
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 }
|
|
575
754
|
};
|
|
576
|
-
await this.deps.mutators.scheduleExpiry(record);
|
|
577
|
-
let final = record.currentOffset;
|
|
578
|
-
if (initialMessages.length > 0) final = await this.deps.mutators.appendMessages(record, initialMessages);
|
|
579
755
|
return {
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
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
|
+
})
|
|
583
764
|
};
|
|
584
765
|
}
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
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
|
+
};
|
|
601
788
|
}
|
|
602
|
-
|
|
603
|
-
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
|
+
};
|
|
604
802
|
}
|
|
605
|
-
|
|
606
|
-
const
|
|
607
|
-
const
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
await stream.notify("deleted");
|
|
623
|
-
const parentId = record.lifecycle.forkedFrom;
|
|
624
|
-
if (!parentId) return;
|
|
625
|
-
const parentStream = await this.deps.resolve(parentId);
|
|
626
|
-
const newRefCount = await parentStream.decrementChildRefCount();
|
|
627
|
-
const parent = await parentStream.getRecord();
|
|
628
|
-
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
|
+
};
|
|
629
820
|
}
|
|
630
821
|
};
|
|
631
822
|
|
|
@@ -640,16 +831,17 @@ var StreamMessageReader = class {
|
|
|
640
831
|
}
|
|
641
832
|
async readChainFor(stream, record, afterOffset, capOffset, touchOwnTtl = true) {
|
|
642
833
|
const out = [];
|
|
643
|
-
|
|
644
|
-
|
|
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);
|
|
645
837
|
const source = await sourceStream.getRecord();
|
|
646
838
|
if (source) {
|
|
647
|
-
const upstreamCap = capOffset && compareOffsets(capOffset,
|
|
839
|
+
const upstreamCap = capOffset && compareOffsets(capOffset, current.lifecycle.forkOffset) < 0 ? capOffset : current.lifecycle.forkOffset;
|
|
648
840
|
out.push(...await this.readChainFor(sourceStream, source, afterOffset, upstreamCap, false));
|
|
649
841
|
}
|
|
650
842
|
}
|
|
651
|
-
if (touchOwnTtl) await this.deps.expiryPolicy.touch(stream,
|
|
652
|
-
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;
|
|
653
845
|
const own = await stream.listMessages({
|
|
654
846
|
after: ownStart,
|
|
655
847
|
until: capOffset
|
|
@@ -665,58 +857,21 @@ var StreamMessageReader = class {
|
|
|
665
857
|
nextOffset: ""
|
|
666
858
|
};
|
|
667
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
|
+
};
|
|
668
868
|
return {
|
|
669
869
|
messages,
|
|
670
|
-
nextOffset:
|
|
870
|
+
nextOffset: record.currentOffset
|
|
671
871
|
};
|
|
672
872
|
}
|
|
673
873
|
};
|
|
674
874
|
|
|
675
|
-
//#endregion
|
|
676
|
-
//#region src/protocol/storage/stream-message-writer.ts
|
|
677
|
-
var StreamMessageWriter = class {
|
|
678
|
-
constructor(deps) {
|
|
679
|
-
this.deps = deps;
|
|
680
|
-
}
|
|
681
|
-
async appendMessages(record, data, seq) {
|
|
682
|
-
await this.deps.expiryPolicy.touch(this.deps.stream, record, "append");
|
|
683
|
-
const allocation = allocate(record.counter, data.length);
|
|
684
|
-
const now = this.deps.clock.now();
|
|
685
|
-
const messages = data.map((bytes, i) => ({
|
|
686
|
-
data: bytes,
|
|
687
|
-
offset: allocation.offsets[i],
|
|
688
|
-
timestamp: now
|
|
689
|
-
}));
|
|
690
|
-
if (messages.length > 0) await this.deps.stream.appendMessages(messages);
|
|
691
|
-
await this.deps.stream.updateRecord({
|
|
692
|
-
currentOffset: allocation.nextOffset,
|
|
693
|
-
counter: allocation.endCounter,
|
|
694
|
-
lifecycle: seq ? { lastSeq: seq } : void 0
|
|
695
|
-
});
|
|
696
|
-
await this.deps.stream.notify("message");
|
|
697
|
-
return allocation.nextOffset;
|
|
698
|
-
}
|
|
699
|
-
async closeRecord(record, data, seq) {
|
|
700
|
-
let latest = record;
|
|
701
|
-
let nextOffset = record.currentOffset;
|
|
702
|
-
if (data.length > 0) {
|
|
703
|
-
nextOffset = await this.appendMessages(record, data, seq);
|
|
704
|
-
latest = await this.deps.stream.getRecord() ?? record;
|
|
705
|
-
} else await this.deps.expiryPolicy.touch(this.deps.stream, record, "close");
|
|
706
|
-
await this.deps.stream.updateRecord({
|
|
707
|
-
lifecycle: {
|
|
708
|
-
closed: true,
|
|
709
|
-
closedAt: this.deps.clock.now(),
|
|
710
|
-
...seq ? { lastSeq: seq } : {}
|
|
711
|
-
},
|
|
712
|
-
currentOffset: nextOffset,
|
|
713
|
-
counter: latest.counter
|
|
714
|
-
});
|
|
715
|
-
await this.deps.stream.notify("closed");
|
|
716
|
-
return nextOffset;
|
|
717
|
-
}
|
|
718
|
-
};
|
|
719
|
-
|
|
720
875
|
//#endregion
|
|
721
876
|
//#region src/protocol/storage/stream-record-factory.ts
|
|
722
877
|
var StreamRecordFactory = class {
|
|
@@ -735,9 +890,9 @@ var StreamRecordFactory = class {
|
|
|
735
890
|
id: streamId,
|
|
736
891
|
config,
|
|
737
892
|
lifecycle: {
|
|
738
|
-
childRefCount: 0,
|
|
739
893
|
forkedFrom: fork?.forkedFrom,
|
|
740
894
|
forkOffset,
|
|
895
|
+
...fork?.forkSubOffset !== void 0 && fork.forkSubOffset > 0 ? { forkSubOffset: fork.forkSubOffset } : {},
|
|
741
896
|
expiresAtMs: this.deps.expiryPolicy.computeExpiresAtMs(config)
|
|
742
897
|
},
|
|
743
898
|
currentOffset: forkOffset ?? ZERO_OFFSET,
|
|
@@ -749,173 +904,794 @@ var StreamRecordFactory = class {
|
|
|
749
904
|
//#endregion
|
|
750
905
|
//#region src/protocol.ts
|
|
751
906
|
const LONG_POLL_TIMEOUT_MS = 1500;
|
|
907
|
+
const MAX_COMMIT_ATTEMPTS = 8;
|
|
908
|
+
const MAX_NO_PROGRESS_ATTEMPTS = 8;
|
|
752
909
|
function createStreamProtocol(deps) {
|
|
753
910
|
return new StreamProtocol(deps);
|
|
754
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
|
+
}
|
|
755
931
|
var ProtocolStream = class {
|
|
756
932
|
id;
|
|
757
933
|
appendService;
|
|
758
934
|
readService;
|
|
759
935
|
liveReadService;
|
|
760
936
|
createService;
|
|
937
|
+
forkPlanBuilder;
|
|
761
938
|
constructor(deps) {
|
|
762
939
|
this.deps = deps;
|
|
763
940
|
this.id = deps.storage.id;
|
|
764
|
-
const producerIdempotency = new ProducerIdempotencyService({ store: deps.storage });
|
|
765
|
-
const messageWriter = new StreamMessageWriter({
|
|
766
|
-
stream: deps.storage,
|
|
767
|
-
clock: deps.clock,
|
|
768
|
-
expiryPolicy: deps.expiryPolicy
|
|
769
|
-
});
|
|
770
941
|
const messageReader = new StreamMessageReader({
|
|
771
942
|
stream: deps.storage,
|
|
772
943
|
resolve: deps.resolveStorageStream,
|
|
773
944
|
expiryPolicy: deps.expiryPolicy
|
|
774
945
|
});
|
|
775
|
-
this.appendService = new AppendService({
|
|
776
|
-
producerIdempotency,
|
|
777
|
-
mutators: {
|
|
778
|
-
appendMessages: (record, data, seq) => messageWriter.appendMessages(record, data, seq),
|
|
779
|
-
closeRecord: (record, data, seq) => messageWriter.closeRecord(record, data, seq)
|
|
780
|
-
}
|
|
781
|
-
});
|
|
946
|
+
this.appendService = new AppendService({ clock: deps.clock });
|
|
782
947
|
this.readService = new ReadService({ readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset) });
|
|
783
948
|
this.liveReadService = new LiveReadService({
|
|
784
|
-
store: deps.storage,
|
|
949
|
+
store: liveReadStore(deps.storage),
|
|
785
950
|
clock: deps.clock,
|
|
786
951
|
longPollTimeoutMs: deps.longPollTimeoutMs,
|
|
787
952
|
readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset),
|
|
788
|
-
readOwn: (after) => messageReader.readOwn(after)
|
|
789
|
-
touch: (record) => deps.expiryPolicy.touch(deps.storage, record, "live-read")
|
|
790
|
-
});
|
|
791
|
-
const forkService = new ForkService({
|
|
792
|
-
resolve: deps.resolveStorageStream,
|
|
793
|
-
mutators: {
|
|
794
|
-
expireIfNeeded: async (stream) => {
|
|
795
|
-
await deps.expiryPolicy.expireIfNeeded(stream);
|
|
796
|
-
},
|
|
797
|
-
newRecord: (stream, contentType, opts, fork) => deps.recordFactory.newRecord(stream.id, contentType, opts, fork),
|
|
798
|
-
scheduleExpiry: (record) => deps.expiryPolicy.scheduleExpiry(record),
|
|
799
|
-
appendMessages: (record, data) => messageWriter.appendMessages(record, data)
|
|
800
|
-
}
|
|
953
|
+
readOwn: (after) => messageReader.readOwn(after)
|
|
801
954
|
});
|
|
802
955
|
this.createService = new CreateStreamService({
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
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)
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
async create(options) {
|
|
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);
|
|
973
|
+
}
|
|
974
|
+
async append(options) {
|
|
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" };
|
|
810
1002
|
}
|
|
1003
|
+
await Promise.resolve();
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
async read(options) {
|
|
1007
|
+
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1008
|
+
return this.readService.execute(record, options);
|
|
1009
|
+
}
|
|
1010
|
+
async readLive(options) {
|
|
1011
|
+
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1012
|
+
return this.liveReadService.execute(record, options);
|
|
1013
|
+
}
|
|
1014
|
+
async metadata() {
|
|
1015
|
+
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1016
|
+
if (!record) return { status: "not-found" };
|
|
1017
|
+
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
1018
|
+
return {
|
|
1019
|
+
status: "ok",
|
|
1020
|
+
contentType: record.config.contentType,
|
|
1021
|
+
nextOffset: record.currentOffset,
|
|
1022
|
+
ttlSeconds: record.config.ttlSeconds,
|
|
1023
|
+
expiresAt: record.config.expiresAt,
|
|
1024
|
+
closed: record.lifecycle.closed === true
|
|
1025
|
+
};
|
|
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"
|
|
811
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);
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
var StreamProtocol = class {
|
|
1077
|
+
clock;
|
|
1078
|
+
longPollTimeoutMs;
|
|
1079
|
+
expiryPolicy;
|
|
1080
|
+
recordFactory;
|
|
1081
|
+
constructor(deps) {
|
|
1082
|
+
this.deps = deps;
|
|
1083
|
+
this.clock = deps.clock ?? systemClock;
|
|
1084
|
+
this.longPollTimeoutMs = deps.longPollTimeoutMs ?? LONG_POLL_TIMEOUT_MS;
|
|
1085
|
+
this.expiryPolicy = new ExpiryPolicy({
|
|
1086
|
+
resolve: (id) => this.storageStream(id),
|
|
1087
|
+
clock: this.clock,
|
|
1088
|
+
onScheduledExpiry: (id) => this.handleScheduledExpiry(id)
|
|
1089
|
+
});
|
|
1090
|
+
this.recordFactory = new StreamRecordFactory({
|
|
1091
|
+
clock: this.clock,
|
|
1092
|
+
expiryPolicy: this.expiryPolicy
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
async create(streamId, options) {
|
|
1096
|
+
const storage = this.storageStream(streamId);
|
|
1097
|
+
const stream = this.boundProtocolStream(storage);
|
|
1098
|
+
const result = await stream.create(options);
|
|
1099
|
+
if (result.status === "created" || result.status === "exists") return {
|
|
1100
|
+
...result,
|
|
1101
|
+
stream
|
|
1102
|
+
};
|
|
1103
|
+
return result;
|
|
1104
|
+
}
|
|
1105
|
+
async get(streamId) {
|
|
1106
|
+
const storage = this.storageStream(streamId);
|
|
1107
|
+
const record = await this.expiryPolicy.expireIfNeeded(storage);
|
|
1108
|
+
if (!record) return { status: "not-found" };
|
|
1109
|
+
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
1110
|
+
return {
|
|
1111
|
+
status: "ok",
|
|
1112
|
+
stream: this.boundProtocolStream(storage)
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
/** Called by adapter schedulers/alarms; core decides whether expiry applies. */
|
|
1116
|
+
async handleScheduledExpiry(streamId) {
|
|
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);
|
|
1129
|
+
}
|
|
1130
|
+
boundProtocolStream(storage) {
|
|
1131
|
+
return new ProtocolStream({
|
|
1132
|
+
storage,
|
|
1133
|
+
adapter: this.deps.storage.adapter,
|
|
1134
|
+
clock: this.clock,
|
|
1135
|
+
longPollTimeoutMs: this.longPollTimeoutMs,
|
|
1136
|
+
expiryPolicy: this.expiryPolicy,
|
|
1137
|
+
recordFactory: this.recordFactory,
|
|
1138
|
+
resolveStorageStream: (id) => this.storageStream(id)
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
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);
|
|
1256
|
+
}
|
|
1257
|
+
async countDependents(parent) {
|
|
1258
|
+
return this.state.countDependents(parent);
|
|
1259
|
+
}
|
|
1260
|
+
};
|
|
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
|
+
|
|
1316
|
+
//#endregion
|
|
1317
|
+
//#region src/storage/memory/lib/clone.ts
|
|
1318
|
+
function clone$1(value) {
|
|
1319
|
+
if (value === null || value === void 0) return value;
|
|
1320
|
+
return structuredClone(value);
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
//#endregion
|
|
1324
|
+
//#region src/storage/memory/stores/message-store.ts
|
|
1325
|
+
var MessageStore = class {
|
|
1326
|
+
messages = [];
|
|
1327
|
+
constructor(records) {
|
|
1328
|
+
this.records = records;
|
|
1329
|
+
}
|
|
1330
|
+
appendMessages(messages) {
|
|
1331
|
+
this.records.requireRecord();
|
|
1332
|
+
this.messages.push(...clone$1(messages));
|
|
1333
|
+
}
|
|
1334
|
+
listMessages(options = {}) {
|
|
1335
|
+
let out = this.messages;
|
|
1336
|
+
if (options.after) out = out.filter((m) => m.offset > options.after);
|
|
1337
|
+
if (options.until) out = out.filter((m) => m.offset <= options.until);
|
|
1338
|
+
if (options.limit !== void 0) out = out.slice(0, options.limit);
|
|
1339
|
+
return clone$1(out);
|
|
1340
|
+
}
|
|
1341
|
+
deleteMessages() {
|
|
1342
|
+
this.messages = [];
|
|
1343
|
+
}
|
|
1344
|
+
};
|
|
1345
|
+
|
|
1346
|
+
//#endregion
|
|
1347
|
+
//#region src/storage/memory/stores/producer-store.ts
|
|
1348
|
+
var ProducerStore = class {
|
|
1349
|
+
producers = new Map();
|
|
1350
|
+
constructor(records) {
|
|
1351
|
+
this.records = records;
|
|
1352
|
+
}
|
|
1353
|
+
getProducerState(producerId) {
|
|
1354
|
+
return clone$1(this.producers.get(producerId));
|
|
1355
|
+
}
|
|
1356
|
+
setProducerState(producerId, producerState) {
|
|
1357
|
+
this.records.requireRecord();
|
|
1358
|
+
this.producers.set(producerId, clone$1(producerState));
|
|
1359
|
+
}
|
|
1360
|
+
deleteProducerStates() {
|
|
1361
|
+
this.producers.clear();
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
|
|
1365
|
+
//#endregion
|
|
1366
|
+
//#region src/storage/memory/stores/record-store.ts
|
|
1367
|
+
var RecordStore = class {
|
|
1368
|
+
record;
|
|
1369
|
+
constructor(id) {
|
|
1370
|
+
this.id = id;
|
|
1371
|
+
}
|
|
1372
|
+
getRecord() {
|
|
1373
|
+
return clone$1(this.record ?? null);
|
|
1374
|
+
}
|
|
1375
|
+
createRecord(record) {
|
|
1376
|
+
if (record.id !== this.id) throw new Error(`Record id ${record.id} does not match bound stream ${this.id}`);
|
|
1377
|
+
if (this.record) return {
|
|
1378
|
+
status: "exists",
|
|
1379
|
+
record: clone$1(this.record)
|
|
1380
|
+
};
|
|
1381
|
+
this.record = clone$1(record);
|
|
1382
|
+
return { status: "created" };
|
|
1383
|
+
}
|
|
1384
|
+
updateRecord(patch) {
|
|
1385
|
+
const record = this.requireRecord();
|
|
1386
|
+
this.record = {
|
|
1387
|
+
...record,
|
|
1388
|
+
config: {
|
|
1389
|
+
...record.config,
|
|
1390
|
+
...patch.config
|
|
1391
|
+
},
|
|
1392
|
+
lifecycle: {
|
|
1393
|
+
...record.lifecycle,
|
|
1394
|
+
...patch.lifecycle
|
|
1395
|
+
},
|
|
1396
|
+
currentOffset: patch.currentOffset ?? record.currentOffset,
|
|
1397
|
+
counter: patch.counter ?? record.counter
|
|
1398
|
+
};
|
|
1399
|
+
return clone$1(this.record);
|
|
812
1400
|
}
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
816
|
-
return this.createService.execute(record, options);
|
|
817
|
-
});
|
|
1401
|
+
deleteRecord() {
|
|
1402
|
+
this.record = void 0;
|
|
818
1403
|
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
return this.appendService.execute(record, options);
|
|
823
|
-
});
|
|
1404
|
+
requireRecord() {
|
|
1405
|
+
if (!this.record) throw new Error(`Stream not found: ${this.id}`);
|
|
1406
|
+
return this.record;
|
|
824
1407
|
}
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
1408
|
+
};
|
|
1409
|
+
|
|
1410
|
+
//#endregion
|
|
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
|
+
*/
|
|
1420
|
+
var MemoryNotifier = class {
|
|
1421
|
+
wakeWaiters = new Set();
|
|
1422
|
+
waitForWake(timeoutMs) {
|
|
1423
|
+
return new Promise((resolve) => {
|
|
1424
|
+
const finish = () => {
|
|
1425
|
+
clearTimeout(timeout);
|
|
1426
|
+
this.wakeWaiters.delete(finish);
|
|
1427
|
+
resolve();
|
|
1428
|
+
};
|
|
1429
|
+
const timeout = setTimeout(finish, timeoutMs);
|
|
1430
|
+
this.wakeWaiters.add(finish);
|
|
1431
|
+
});
|
|
828
1432
|
}
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
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();
|
|
832
1439
|
}
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
1440
|
+
};
|
|
1441
|
+
|
|
1442
|
+
//#endregion
|
|
1443
|
+
//#region src/storage/memory/utils/timeout-scheduler.ts
|
|
1444
|
+
var TimeoutScheduler = class {
|
|
1445
|
+
timer;
|
|
1446
|
+
constructor(callback) {
|
|
1447
|
+
this.callback = callback;
|
|
1448
|
+
}
|
|
1449
|
+
schedule(at) {
|
|
1450
|
+
this.cancel();
|
|
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);
|
|
845
1458
|
}
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
1459
|
+
cancel() {
|
|
1460
|
+
if (this.timer) clearTimeout(this.timer);
|
|
1461
|
+
this.timer = void 0;
|
|
849
1462
|
}
|
|
850
1463
|
};
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
this.
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
1464
|
+
|
|
1465
|
+
//#endregion
|
|
1466
|
+
//#region src/storage/memory/stream.ts
|
|
1467
|
+
/** Adapter-private per-stream handle. Not on the seam — owned by the memory state. */
|
|
1468
|
+
var MemoryStream = class {
|
|
1469
|
+
records;
|
|
1470
|
+
messages;
|
|
1471
|
+
producers;
|
|
1472
|
+
notifier;
|
|
1473
|
+
timeout;
|
|
1474
|
+
constructor(id, deleteFromState, onScheduledExpiry) {
|
|
1475
|
+
this.id = id;
|
|
1476
|
+
this.deleteFromState = deleteFromState;
|
|
1477
|
+
this.records = new RecordStore(id);
|
|
1478
|
+
this.messages = new MessageStore(this.records);
|
|
1479
|
+
this.producers = new ProducerStore(this.records);
|
|
1480
|
+
this.notifier = new MemoryNotifier();
|
|
1481
|
+
this.timeout = new TimeoutScheduler(onScheduledExpiry);
|
|
1482
|
+
}
|
|
1483
|
+
getRecord() {
|
|
1484
|
+
return this.records.getRecord();
|
|
1485
|
+
}
|
|
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
|
|
873
1492
|
});
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
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"
|
|
882
1501
|
};
|
|
883
|
-
return result;
|
|
884
1502
|
}
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
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();
|
|
890
1548
|
return {
|
|
891
|
-
status: "
|
|
892
|
-
|
|
1549
|
+
status: "committed",
|
|
1550
|
+
record: this.records.getRecord() ?? record
|
|
893
1551
|
};
|
|
894
1552
|
}
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
return this.gcService.handleScheduledExpiry(streamId);
|
|
1553
|
+
listMessages(options) {
|
|
1554
|
+
return this.messages.listMessages(options);
|
|
898
1555
|
}
|
|
899
|
-
|
|
900
|
-
return
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
1556
|
+
getProducerState(producerId) {
|
|
1557
|
+
return this.producers.getProducerState(producerId);
|
|
1558
|
+
}
|
|
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();
|
|
1566
|
+
}
|
|
1567
|
+
softDelete() {
|
|
1568
|
+
this.records.updateRecord({ lifecycle: { softDeleted: true } });
|
|
1569
|
+
this.notifier.wake();
|
|
1570
|
+
}
|
|
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);
|
|
1583
|
+
}
|
|
1584
|
+
scheduleExpiry(at) {
|
|
1585
|
+
return this.timeout.schedule(at);
|
|
1586
|
+
}
|
|
1587
|
+
cancelExpiry() {
|
|
1588
|
+
return this.timeout.cancel();
|
|
1589
|
+
}
|
|
1590
|
+
};
|
|
1591
|
+
function producerStatesEqual(left, right) {
|
|
1592
|
+
if (!left || !right) return left === right;
|
|
1593
|
+
return left.epoch === right.epoch && left.lastSeq === right.lastSeq;
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
//#endregion
|
|
1597
|
+
//#region src/storage/memory/state.ts
|
|
1598
|
+
/** Shared in-memory stream registry. */
|
|
1599
|
+
var MemoryStreamState = class {
|
|
1600
|
+
streams = new Map();
|
|
1601
|
+
childEdges = new Map();
|
|
1602
|
+
constructor(onScheduledExpiry) {
|
|
1603
|
+
this.onScheduledExpiry = onScheduledExpiry;
|
|
1604
|
+
}
|
|
1605
|
+
getStream(id) {
|
|
1606
|
+
let stream = this.streams.get(id);
|
|
1607
|
+
if (!stream) {
|
|
1608
|
+
stream = new MemoryStream(id, () => this.deleteStream(id), () => this.onScheduledExpiry?.(id));
|
|
1609
|
+
this.streams.set(id, stream);
|
|
1610
|
+
}
|
|
1611
|
+
return stream;
|
|
1612
|
+
}
|
|
1613
|
+
getExistingStream(id) {
|
|
1614
|
+
return this.streams.get(id);
|
|
910
1615
|
}
|
|
911
|
-
|
|
912
|
-
|
|
1616
|
+
addEdge(parent, child) {
|
|
1617
|
+
const children = this.childEdges.get(parent) ?? new Set();
|
|
1618
|
+
children.add(child);
|
|
1619
|
+
this.childEdges.set(parent, children);
|
|
913
1620
|
}
|
|
914
|
-
|
|
915
|
-
|
|
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);
|
|
916
1633
|
}
|
|
917
1634
|
};
|
|
918
1635
|
|
|
1636
|
+
//#endregion
|
|
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
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
|
|
919
1695
|
//#endregion
|
|
920
1696
|
//#region src/http/not-supported.ts
|
|
921
1697
|
function notSupportedResponse(result, responses) {
|
|
@@ -959,6 +1735,7 @@ var HttpDispatchService = class {
|
|
|
959
1735
|
default: return this.deps.responses.methodNotAllowed();
|
|
960
1736
|
}
|
|
961
1737
|
} catch (error) {
|
|
1738
|
+
if (isNotSupportedError(error)) return notSupportedResponse(notSupportedFromError(error), this.deps.responses);
|
|
962
1739
|
console.error("Error handling request:", error);
|
|
963
1740
|
return this.deps.responses.internalError();
|
|
964
1741
|
}
|
|
@@ -1257,7 +2034,8 @@ var AppendHttpService = class {
|
|
|
1257
2034
|
contentType: parsed.contentType ?? "application/octet-stream",
|
|
1258
2035
|
seq: parsed.seq,
|
|
1259
2036
|
producer: parsed.producerHeaders.kind === "ok" ? parsed.producerHeaders.producer : void 0,
|
|
1260
|
-
close: parsed.wantClose
|
|
2037
|
+
close: parsed.wantClose,
|
|
2038
|
+
expectedOffset: parsed.expectedOffset
|
|
1261
2039
|
});
|
|
1262
2040
|
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
1263
2041
|
return this.toResponse(result, parsed.producerHeaders, body.isEmpty);
|
|
@@ -1268,11 +2046,17 @@ var AppendHttpService = class {
|
|
|
1268
2046
|
ok: false,
|
|
1269
2047
|
response: this.deps.responses.badRequest("Invalid producer headers")
|
|
1270
2048
|
};
|
|
2049
|
+
const expectedOffset = request.headers.get("stream-expected-offset") ?? void 0;
|
|
2050
|
+
if (expectedOffset !== void 0 && !isValidOffset(expectedOffset)) return {
|
|
2051
|
+
ok: false,
|
|
2052
|
+
response: this.deps.responses.badRequest("Invalid expected offset")
|
|
2053
|
+
};
|
|
1271
2054
|
return {
|
|
1272
2055
|
ok: true,
|
|
1273
2056
|
contentType: request.headers.get("content-type"),
|
|
1274
2057
|
seq: request.headers.get("stream-seq") ?? void 0,
|
|
1275
2058
|
wantClose: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
2059
|
+
expectedOffset,
|
|
1276
2060
|
producerHeaders
|
|
1277
2061
|
};
|
|
1278
2062
|
}
|
|
@@ -1314,10 +2098,12 @@ var AppendHttpService = class {
|
|
|
1314
2098
|
case "conflict": {
|
|
1315
2099
|
if (result.conflictReason === "closed") return this.deps.responses.empty(409, {
|
|
1316
2100
|
"stream-closed": "true",
|
|
1317
|
-
"stream-next-offset": result.
|
|
2101
|
+
"stream-next-offset": result.offset
|
|
1318
2102
|
});
|
|
2103
|
+
if (result.conflictReason === "expected-offset") return this.deps.responses.conflict("Expected offset mismatch", { "stream-next-offset": result.offset });
|
|
1319
2104
|
return this.deps.responses.conflict(result.conflictReason === "content-type" ? "Content-Type mismatch" : "Sequence conflict");
|
|
1320
2105
|
}
|
|
2106
|
+
case "busy": return this.deps.responses.text("Stream busy, retry later", 503);
|
|
1321
2107
|
case "stale-epoch": return this.deps.responses.text("Stale producer epoch", 403, { "producer-epoch": String(result.currentEpoch) });
|
|
1322
2108
|
case "producer-gap": return this.deps.responses.conflict("Producer sequence gap", {
|
|
1323
2109
|
"producer-expected-seq": String(result.expectedSeq),
|
|
@@ -1325,14 +2111,14 @@ var AppendHttpService = class {
|
|
|
1325
2111
|
});
|
|
1326
2112
|
case "invalid-epoch-seq": return this.deps.responses.badRequest("New epoch must start at seq=0");
|
|
1327
2113
|
case "duplicate": return this.deps.responses.empty(204, {
|
|
1328
|
-
"stream-next-offset": result.
|
|
2114
|
+
"stream-next-offset": result.offset,
|
|
1329
2115
|
"producer-epoch": String(result.producerEpoch),
|
|
1330
2116
|
"producer-seq": String(result.producerSeq),
|
|
1331
2117
|
...result.closed ? { "stream-closed": "true" } : {}
|
|
1332
2118
|
});
|
|
1333
2119
|
case "appended": {
|
|
1334
2120
|
const headers = {
|
|
1335
|
-
"stream-next-offset": result.
|
|
2121
|
+
"stream-next-offset": result.offset,
|
|
1336
2122
|
...result.closed ? { "stream-closed": "true" } : {}
|
|
1337
2123
|
};
|
|
1338
2124
|
if (result.producerEpoch !== void 0) headers["producer-epoch"] = String(result.producerEpoch);
|
|
@@ -1363,7 +2149,8 @@ var CreateHttpService = class {
|
|
|
1363
2149
|
initialData: normalized.initialData,
|
|
1364
2150
|
closed: parsed.wantClosed,
|
|
1365
2151
|
forkedFrom: parsed.forkedFromStreamId,
|
|
1366
|
-
forkOffset: parsed.forkOffset
|
|
2152
|
+
forkOffset: parsed.forkOffset,
|
|
2153
|
+
forkSubOffset: parsed.forkSubOffset
|
|
1367
2154
|
});
|
|
1368
2155
|
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
1369
2156
|
return this.toResponse(result, ctx.request.url);
|
|
@@ -1374,6 +2161,7 @@ var CreateHttpService = class {
|
|
|
1374
2161
|
const expiresAtHeader = request.headers.get("stream-expires-at");
|
|
1375
2162
|
const forkedFromHeader = request.headers.get("stream-forked-from");
|
|
1376
2163
|
const forkOffsetHeader = request.headers.get("stream-fork-offset");
|
|
2164
|
+
const forkSubOffsetHeader = request.headers.get("stream-fork-sub-offset");
|
|
1377
2165
|
if (ttlHeader && !/^(0|[1-9]\d*)$/.test(ttlHeader)) return {
|
|
1378
2166
|
ok: false,
|
|
1379
2167
|
response: this.deps.responses.badRequest("Invalid Stream-TTL format")
|
|
@@ -1390,6 +2178,20 @@ var CreateHttpService = class {
|
|
|
1390
2178
|
ok: false,
|
|
1391
2179
|
response: this.deps.responses.badRequest("Stream-Fork-Offset requires Stream-Forked-From")
|
|
1392
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
|
+
}
|
|
1393
2195
|
const isFork = !!forkedFromHeader;
|
|
1394
2196
|
return {
|
|
1395
2197
|
ok: true,
|
|
@@ -1398,7 +2200,8 @@ var CreateHttpService = class {
|
|
|
1398
2200
|
expiresAt: expiresAtHeader ?? void 0,
|
|
1399
2201
|
wantClosed: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
1400
2202
|
forkedFromStreamId: forkedFromHeader ? this.deps.path.canonicalizeForkSource(forkedFromHeader) : void 0,
|
|
1401
|
-
forkOffset: forkOffsetHeader ?? void 0
|
|
2203
|
+
forkOffset: forkOffsetHeader ?? void 0,
|
|
2204
|
+
forkSubOffset: forkSubOffsetHeader !== null ? parseInt(forkSubOffsetHeader, 10) : void 0
|
|
1402
2205
|
};
|
|
1403
2206
|
}
|
|
1404
2207
|
normalizeInitialData(data, contentType) {
|
|
@@ -1612,62 +2415,102 @@ var SseHttpService = class {
|
|
|
1612
2415
|
const connectionStartTime = Date.now();
|
|
1613
2416
|
const sseEvents = this.deps.sseEvents;
|
|
1614
2417
|
const clock = this.deps.clock;
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
let
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
}
|
|
1625
|
-
|
|
1626
|
-
|
|
2418
|
+
let cancelActiveRead;
|
|
2419
|
+
return new ReadableStream({
|
|
2420
|
+
start: async (controller) => {
|
|
2421
|
+
const liveReadAbortController = new AbortController();
|
|
2422
|
+
let inactive = false;
|
|
2423
|
+
const shouldStop = () => inactive || liveReadAbortController.signal.aborted;
|
|
2424
|
+
const stop = () => {
|
|
2425
|
+
inactive = true;
|
|
2426
|
+
liveReadAbortController.abort();
|
|
2427
|
+
};
|
|
2428
|
+
cancelActiveRead = stop;
|
|
2429
|
+
const close = () => {
|
|
2430
|
+
if (inactive) return;
|
|
2431
|
+
inactive = true;
|
|
2432
|
+
liveReadAbortController.abort();
|
|
2433
|
+
try {
|
|
1627
2434
|
controller.close();
|
|
1628
|
-
|
|
2435
|
+
} catch {}
|
|
2436
|
+
};
|
|
2437
|
+
const enqueue = (chunk) => {
|
|
2438
|
+
if (shouldStop()) return false;
|
|
2439
|
+
try {
|
|
2440
|
+
controller.enqueue(chunk);
|
|
2441
|
+
return true;
|
|
2442
|
+
} catch {
|
|
2443
|
+
stop();
|
|
2444
|
+
return false;
|
|
1629
2445
|
}
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
2446
|
+
};
|
|
2447
|
+
const writeChunks = (chunks, enabled) => {
|
|
2448
|
+
if (!enabled) return true;
|
|
2449
|
+
for (const chunk of chunks) if (!enqueue(chunk)) return false;
|
|
2450
|
+
return true;
|
|
2451
|
+
};
|
|
2452
|
+
try {
|
|
2453
|
+
let initialNextOffset;
|
|
2454
|
+
let initialUpToDate;
|
|
2455
|
+
let initialClosed = false;
|
|
2456
|
+
if (currentOffset === "now") {
|
|
2457
|
+
initialNextOffset = metadataNextOffset;
|
|
2458
|
+
initialUpToDate = true;
|
|
2459
|
+
initialClosed = metadataClosed;
|
|
2460
|
+
} else {
|
|
2461
|
+
const initialResult = await stream.read({ offset: currentOffset === "-1" ? void 0 : currentOffset });
|
|
2462
|
+
if (shouldStop()) return;
|
|
2463
|
+
if (initialResult.status === "not-found" || initialResult.status === "gone") {
|
|
2464
|
+
close();
|
|
2465
|
+
return;
|
|
2466
|
+
}
|
|
2467
|
+
if (!writeChunks(sseEvents.dataEvent(initialResult.messages, encoding), initialResult.messages.length > 0)) return;
|
|
2468
|
+
initialNextOffset = initialResult.nextOffset;
|
|
2469
|
+
initialUpToDate = initialResult.upToDate;
|
|
2470
|
+
initialClosed = initialResult.closed === true;
|
|
1646
2471
|
}
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
});
|
|
1652
|
-
if (result.status === "not-found" || result.status === "not-supported") {
|
|
1653
|
-
controller.close();
|
|
2472
|
+
currentCursor = generateCursor(clock, currentCursor);
|
|
2473
|
+
if (!enqueue(sseEvents.controlEvent(this.buildControlData(initialNextOffset, currentCursor, initialUpToDate, initialClosed)))) return;
|
|
2474
|
+
if (initialClosed) {
|
|
2475
|
+
close();
|
|
1654
2476
|
return;
|
|
1655
2477
|
}
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
2478
|
+
currentOffset = initialNextOffset;
|
|
2479
|
+
while (!shouldStop()) {
|
|
2480
|
+
if (Date.now() - connectionStartTime >= CONNECTION_TIMEOUT_MS) {
|
|
2481
|
+
close();
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
const result = await stream.readLive({
|
|
2485
|
+
offset: currentOffset,
|
|
2486
|
+
mode: "sse",
|
|
2487
|
+
cursor: currentCursor,
|
|
2488
|
+
signal: liveReadAbortController.signal
|
|
2489
|
+
});
|
|
2490
|
+
if (shouldStop()) return;
|
|
2491
|
+
if (result.status === "not-found" || result.status === "gone" || result.status === "not-supported") {
|
|
2492
|
+
close();
|
|
2493
|
+
return;
|
|
2494
|
+
}
|
|
2495
|
+
if (!writeChunks(sseEvents.dataEvent(result.messages, encoding), result.messages.length > 0)) return;
|
|
2496
|
+
if (!enqueue(sseEvents.controlEvent(this.buildControlData(result.nextOffset, result.cursor, result.upToDate, result.closed === true)))) return;
|
|
2497
|
+
currentOffset = result.nextOffset;
|
|
2498
|
+
currentCursor = result.cursor;
|
|
2499
|
+
if (result.closed) {
|
|
2500
|
+
close();
|
|
2501
|
+
return;
|
|
2502
|
+
}
|
|
2503
|
+
if (result.status === "timeout") continue;
|
|
1663
2504
|
}
|
|
1664
|
-
|
|
2505
|
+
} catch (error) {
|
|
2506
|
+
if (!shouldStop()) console.error("SSE stream error:", error);
|
|
2507
|
+
close();
|
|
1665
2508
|
}
|
|
1666
|
-
}
|
|
1667
|
-
|
|
1668
|
-
|
|
2509
|
+
},
|
|
2510
|
+
cancel: () => {
|
|
2511
|
+
cancelActiveRead?.();
|
|
1669
2512
|
}
|
|
1670
|
-
}
|
|
2513
|
+
});
|
|
1671
2514
|
}
|
|
1672
2515
|
buildControlData(nextOffset, cursor, upToDate, closed) {
|
|
1673
2516
|
if (closed) return {
|
|
@@ -1680,10 +2523,6 @@ var SseHttpService = class {
|
|
|
1680
2523
|
...upToDate ? { upToDate: true } : {}
|
|
1681
2524
|
};
|
|
1682
2525
|
}
|
|
1683
|
-
writeChunks(controller, chunks, enabled) {
|
|
1684
|
-
if (!enabled) return;
|
|
1685
|
-
for (const chunk of chunks) controller.enqueue(chunk);
|
|
1686
|
-
}
|
|
1687
2526
|
};
|
|
1688
2527
|
|
|
1689
2528
|
//#endregion
|
|
@@ -1768,6 +2607,7 @@ var ReadOnlyHttpDispatchService = class {
|
|
|
1768
2607
|
default: return this.deps.responses.methodNotAllowed();
|
|
1769
2608
|
}
|
|
1770
2609
|
} catch (error) {
|
|
2610
|
+
if (isNotSupportedError(error)) return notSupportedResponse(notSupportedFromError(error), this.deps.responses);
|
|
1771
2611
|
console.error("Error handling request:", error);
|
|
1772
2612
|
return this.deps.responses.internalError();
|
|
1773
2613
|
}
|
|
@@ -1828,4 +2668,680 @@ var ReadOnlyHttpHandler = class {
|
|
|
1828
2668
|
};
|
|
1829
2669
|
|
|
1830
2670
|
//#endregion
|
|
1831
|
-
|
|
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 };
|