@streamsy/core 0.2.1 → 0.4.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/LICENSE +21 -0
- package/README.md +139 -0
- package/dist/cursor-generator-CGz1TO_N.js +13 -0
- package/dist/http/index.d.ts +2 -0
- package/dist/http/index.js +3 -0
- package/dist/http-EnNOUsIK.js +69 -0
- package/dist/index-CFv8vZvy.d.ts +513 -0
- package/dist/index.d.ts +3 -1054
- package/dist/index.js +107 -3865
- package/dist/internal/index.d.ts +22 -0
- package/dist/internal/index.js +3 -0
- package/dist/layer-D8ybaCL2.js +340 -0
- package/dist/layer-KvknRFUT.js +656 -0
- package/dist/owner-BQzMpfC1.js +36 -0
- package/dist/owner-records-CX6yU28i.js +5 -0
- package/dist/owner-records-QDlssl__.d.ts +2963 -0
- package/dist/program-DJ8NpHIf.js +814 -0
- package/dist/protocol/index.d.ts +8 -0
- package/dist/protocol/index.js +16 -0
- package/dist/remote/index.d.ts +23 -0
- package/dist/remote/index.js +428 -0
- package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
- package/dist/streamsy-OjRubIPC.js +829 -0
- package/dist/testing/index.d.ts +44 -0
- package/dist/testing/index.js +757 -0
- package/package.json +50 -13
package/dist/index.js
CHANGED
|
@@ -1,3878 +1,120 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
feature,
|
|
18
|
-
message
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
/** Convenience constructor for a storage-level unsupported-feature error. */
|
|
22
|
-
function unsupported(feature, message) {
|
|
23
|
-
return new NotSupportedError(feature, message);
|
|
24
|
-
}
|
|
25
|
-
/** Type guard for storage-level unsupported-feature errors. */
|
|
26
|
-
function isNotSupportedError(value) {
|
|
27
|
-
return value instanceof NotSupportedError;
|
|
28
|
-
}
|
|
29
|
-
/** Convert storage-level unsupported-feature errors to public protocol results. */
|
|
30
|
-
function notSupportedFromError(error) {
|
|
31
|
-
return notSupported(error.feature, error.message);
|
|
32
|
-
}
|
|
33
|
-
/** Type guard for protocol results that may be a {@link NotSupportedResult}. */
|
|
34
|
-
function isNotSupported(value) {
|
|
35
|
-
if (typeof value !== "object" || value === null) return false;
|
|
36
|
-
const status = value.status;
|
|
37
|
-
return status === "not-supported";
|
|
38
|
-
}
|
|
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
|
-
|
|
47
|
-
//#endregion
|
|
48
|
-
//#region src/protocol/helpers/content-type-matcher.ts
|
|
49
|
-
/**
|
|
50
|
-
* Content type normalization and matching for the durable streams protocol.
|
|
51
|
-
*
|
|
52
|
-
* Responsibilities:
|
|
53
|
-
*
|
|
54
|
-
* - `normalizeContentType` lowercases, strips RFC 7231 parameters (everything
|
|
55
|
-
* after the first `;`), and trims surrounding whitespace.
|
|
56
|
-
* - `contentTypeMatches` compares two content types by equality of their
|
|
57
|
-
* normalized forms.
|
|
58
|
-
*
|
|
59
|
-
* Used by `AppendService` for append content-type conflicts, by
|
|
60
|
-
* `CreateStreamService` via `configMatches` for idempotent create checks, and
|
|
61
|
-
* by `ForkPlanBuilder` for fork content-type compatibility.
|
|
62
|
-
*/
|
|
63
|
-
function normalizeContentType(ct) {
|
|
64
|
-
return ct.toLowerCase().split(";")[0].trim();
|
|
65
|
-
}
|
|
66
|
-
function contentTypeMatches(expected, actual) {
|
|
67
|
-
return normalizeContentType(expected) === normalizeContentType(actual);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
//#endregion
|
|
71
|
-
//#region src/protocol/helpers/message-framer.ts
|
|
72
|
-
/**
|
|
73
|
-
* Body framing for the durable streams protocol.
|
|
74
|
-
*
|
|
75
|
-
* Responsibilities:
|
|
76
|
-
*
|
|
77
|
-
* - Non-JSON content types pass the original bytes through as a single
|
|
78
|
-
* message.
|
|
79
|
-
* - JSON content types are decoded and re-encoded:
|
|
80
|
-
* - JSON object input becomes one canonical `JSON.stringify(parsed)` message.
|
|
81
|
-
* - JSON array input produces one message per item.
|
|
82
|
-
* - Empty JSON array produces zero messages.
|
|
83
|
-
* - The JSON branch is selected by `contentType.toLowerCase().startsWith("application/json")`,
|
|
84
|
-
* without parameter stripping.
|
|
85
|
-
* - Invalid JSON propagates the underlying `JSON.parse` error.
|
|
86
|
-
*
|
|
87
|
-
* Used by `AppendService`, `CreateStreamService`, and `ForkPlanBuilder` before
|
|
88
|
-
* incoming request bodies are persisted as stored messages.
|
|
89
|
-
*/
|
|
90
|
-
function frameMessages(data, contentType) {
|
|
91
|
-
if (!contentType.toLowerCase().startsWith("application/json")) return [data];
|
|
92
|
-
const parsed = JSON.parse(new TextDecoder().decode(data));
|
|
93
|
-
if (Array.isArray(parsed)) return parsed.length === 0 ? [] : parsed.map((item) => new TextEncoder().encode(JSON.stringify(item)));
|
|
94
|
-
return [new TextEncoder().encode(JSON.stringify(parsed))];
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
//#endregion
|
|
98
|
-
//#region src/protocol/helpers/offset-generator.ts
|
|
99
|
-
const ZERO_OFFSET = `${"0".repeat(16)}_${"0".repeat(16)}`;
|
|
100
|
-
const FIXED_WIDTH_OFFSET_REGEX = /^\d{16}_\d{16}$/;
|
|
101
|
-
const FORBIDDEN_OFFSET_CHARACTERS = /[,&=?/]/;
|
|
102
|
-
/** Protocol-level constraints that apply to every generated offset scheme. */
|
|
103
|
-
function isSafeOffsetToken(offset) {
|
|
104
|
-
return offset.length > 0 && offset.length < 256 && offset !== "-1" && offset !== "now" && !FORBIDDEN_OFFSET_CHARACTERS.test(offset);
|
|
105
|
-
}
|
|
106
|
-
function isValidOffset(generator, offset) {
|
|
107
|
-
return isSafeOffsetToken(offset) && generator.isValid(offset);
|
|
108
|
-
}
|
|
109
|
-
function compareOffsets(a, b) {
|
|
110
|
-
return a === b ? 0 : a < b ? -1 : 1;
|
|
111
|
-
}
|
|
112
|
-
function formatCounter(counter) {
|
|
113
|
-
return `${String(counter).padStart(16, "0")}_${"0".repeat(16)}`;
|
|
114
|
-
}
|
|
115
|
-
function parseCounter(offset) {
|
|
116
|
-
return parseInt(offset.split("_")[0] ?? "0", 10);
|
|
117
|
-
}
|
|
118
|
-
/** The backwards-compatible fixed-width counter generator used by default. */
|
|
119
|
-
const defaultOffsetGenerator = Object.freeze({
|
|
120
|
-
initialOffset: ZERO_OFFSET,
|
|
121
|
-
isValid(offset) {
|
|
122
|
-
return FIXED_WIDTH_OFFSET_REGEX.test(offset);
|
|
123
|
-
},
|
|
124
|
-
next(previous) {
|
|
125
|
-
return formatCounter(parseCounter(previous) + 1);
|
|
126
|
-
}
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
+
import { $ as StreamLifecycle, B as StreamsFault, C as ProducerGap, D as StreamGone, E as StreamClosed, G as MessageWindow, H as isRetryableFault, J as ProducerState, K as Offset, L as DecodeFault, M as Storage, N as ZERO_OFFSET, O as StreamNotFound, P as compare, Q as StreamId, R as EncodeFault, S as OffsetMismatch, T as StreamBusy, U as isStreamsFault, V as TransportFault, W as ChangeSnapshot, X as StoredMessage, Y as RecordPatch, Z as StreamConfig, _ as InvalidAppendRequest, a as custom, b as InvalidReadRequest, c as state, d as address_exports, et as StreamRecord, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, k as isProtocolError, m as AppendConflict, n as bind, o as group, p as CreateResult, q as ProducerId, r as bytes, s as json, t as Wildcard, v as InvalidEpochSeq, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest, z as StorageFault } from "./streamsy-OjRubIPC.js";
|
|
3
|
+
import { n as CommitBoundary, t as layer$1 } from "./layer-D8ybaCL2.js";
|
|
4
|
+
import { a as MutationRejected, c as OperationResult, d as ProducerPrecondition, i as MutationApplied, l as OperationResults, o as Mutations, r as Mutation, s as Operation, t as layer$2, u as Operations } from "./layer-KvknRFUT.js";
|
|
5
|
+
import { t as http_exports } from "./http-EnNOUsIK.js";
|
|
6
|
+
import { Data, Layer, Predicate, Schema } from "effect";
|
|
7
|
+
//#region src/storage/capabilities.ts
|
|
8
|
+
const StorageCapabilities = Schema.Struct({
|
|
9
|
+
fork: Schema.Literals([
|
|
10
|
+
"none",
|
|
11
|
+
"copy",
|
|
12
|
+
"chain"
|
|
13
|
+
]),
|
|
14
|
+
atomicScope: Schema.Literals(["stream", "store"]),
|
|
15
|
+
wake: Schema.Literals(["poll", "push"]),
|
|
16
|
+
expiryIndex: Schema.Literals(["lazy", "indexed"])
|
|
127
17
|
});
|
|
128
|
-
var InvalidGeneratedOffsetError = class extends Error {
|
|
129
|
-
constructor(message) {
|
|
130
|
-
super(message);
|
|
131
|
-
this.name = "InvalidGeneratedOffsetError";
|
|
132
|
-
}
|
|
133
|
-
};
|
|
134
|
-
/** Allocate a batch without interpreting the generator's opaque offset format. */
|
|
135
|
-
function allocate(generator, previousOffset, counter, count) {
|
|
136
|
-
const offsets = [];
|
|
137
|
-
let previous = previousOffset;
|
|
138
|
-
for (let i = 0; i < count; i++) {
|
|
139
|
-
const next = generator.next(previous);
|
|
140
|
-
if (!isValidOffset(generator, next)) throw new InvalidGeneratedOffsetError(`Offset generator returned an invalid token: ${next}`);
|
|
141
|
-
if (compareOffsets(next, previous) <= 0) throw new InvalidGeneratedOffsetError(`Offset generator did not advance lexicographically: ${previous} -> ${next}`);
|
|
142
|
-
offsets.push(next);
|
|
143
|
-
previous = next;
|
|
144
|
-
}
|
|
145
|
-
return {
|
|
146
|
-
endCounter: counter + count,
|
|
147
|
-
offsets,
|
|
148
|
-
nextOffset: previous
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
function assertValidOffsetGenerator(generator) {
|
|
152
|
-
if (!isValidOffset(generator, generator.initialOffset)) throw new InvalidGeneratedOffsetError("Offset generator has an invalid initialOffset");
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
//#endregion
|
|
156
|
-
//#region src/protocol/helpers/producer-idempotency-service.ts
|
|
157
|
-
function validateProducer(state, epoch, seq) {
|
|
158
|
-
if (!state) return seq === 0 ? {
|
|
159
|
-
kind: "accepted",
|
|
160
|
-
proposedState: {
|
|
161
|
-
epoch,
|
|
162
|
-
lastSeq: 0
|
|
163
|
-
}
|
|
164
|
-
} : {
|
|
165
|
-
kind: "gap",
|
|
166
|
-
expectedSeq: 0,
|
|
167
|
-
receivedSeq: seq
|
|
168
|
-
};
|
|
169
|
-
if (epoch < state.epoch) return {
|
|
170
|
-
kind: "stale-epoch",
|
|
171
|
-
currentEpoch: state.epoch
|
|
172
|
-
};
|
|
173
|
-
if (epoch > state.epoch) return seq === 0 ? {
|
|
174
|
-
kind: "accepted",
|
|
175
|
-
proposedState: {
|
|
176
|
-
epoch,
|
|
177
|
-
lastSeq: 0
|
|
178
|
-
}
|
|
179
|
-
} : { kind: "invalid-epoch-seq" };
|
|
180
|
-
if (seq <= state.lastSeq) return {
|
|
181
|
-
kind: "duplicate",
|
|
182
|
-
lastSeq: state.lastSeq,
|
|
183
|
-
epoch: state.epoch
|
|
184
|
-
};
|
|
185
|
-
if (seq === state.lastSeq + 1) return {
|
|
186
|
-
kind: "accepted",
|
|
187
|
-
proposedState: {
|
|
188
|
-
epoch,
|
|
189
|
-
lastSeq: seq
|
|
190
|
-
}
|
|
191
|
-
};
|
|
192
|
-
return {
|
|
193
|
-
kind: "gap",
|
|
194
|
-
expectedSeq: state.lastSeq + 1,
|
|
195
|
-
receivedSeq: seq
|
|
196
|
-
};
|
|
197
|
-
}
|
|
198
|
-
function rejectionToAppendResult(rejection, currentOffset, isClosed) {
|
|
199
|
-
switch (rejection.kind) {
|
|
200
|
-
case "duplicate": return {
|
|
201
|
-
status: "duplicate",
|
|
202
|
-
offset: currentOffset,
|
|
203
|
-
producerEpoch: rejection.epoch,
|
|
204
|
-
producerSeq: rejection.lastSeq,
|
|
205
|
-
closed: isClosed
|
|
206
|
-
};
|
|
207
|
-
case "stale-epoch": return {
|
|
208
|
-
status: "stale-epoch",
|
|
209
|
-
currentEpoch: rejection.currentEpoch
|
|
210
|
-
};
|
|
211
|
-
case "gap": return {
|
|
212
|
-
status: "producer-gap",
|
|
213
|
-
expectedSeq: rejection.expectedSeq,
|
|
214
|
-
receivedSeq: rejection.receivedSeq
|
|
215
|
-
};
|
|
216
|
-
case "invalid-epoch-seq": return { status: "invalid-epoch-seq" };
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
//#endregion
|
|
221
|
-
//#region src/protocol/append-service.ts
|
|
222
|
-
function appendedResult(offset, validation, closed) {
|
|
223
|
-
if (validation?.kind === "accepted") return {
|
|
224
|
-
status: "appended",
|
|
225
|
-
offset,
|
|
226
|
-
producerEpoch: validation.proposedState.epoch,
|
|
227
|
-
producerSeq: validation.proposedState.lastSeq,
|
|
228
|
-
closed
|
|
229
|
-
};
|
|
230
|
-
return {
|
|
231
|
-
status: "appended",
|
|
232
|
-
offset,
|
|
233
|
-
closed
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
function expectedOffsetConflict(record, options) {
|
|
237
|
-
if (options.expectedOffset === void 0 || options.expectedOffset === record.currentOffset) return null;
|
|
238
|
-
return {
|
|
239
|
-
status: "conflict",
|
|
240
|
-
conflictReason: "expected-offset",
|
|
241
|
-
offset: record.currentOffset
|
|
242
|
-
};
|
|
243
|
-
}
|
|
244
|
-
var AppendService = class {
|
|
245
|
-
constructor(deps) {
|
|
246
|
-
this.deps = deps;
|
|
247
|
-
}
|
|
248
|
-
plan(record, options, producerState) {
|
|
249
|
-
if (!record) return {
|
|
250
|
-
kind: "terminal",
|
|
251
|
-
result: { status: "not-found" }
|
|
252
|
-
};
|
|
253
|
-
if (record.lifecycle.softDeleted) return {
|
|
254
|
-
kind: "terminal",
|
|
255
|
-
result: { status: "gone" }
|
|
256
|
-
};
|
|
257
|
-
const isClosed = record.lifecycle.closed === true;
|
|
258
|
-
const wantClose = options.close === true;
|
|
259
|
-
const hasBody = options.data.byteLength > 0;
|
|
260
|
-
let producerValidation;
|
|
261
|
-
if (options.producer) {
|
|
262
|
-
producerValidation = validateProducer(producerState, options.producer.producerEpoch, options.producer.producerSeq);
|
|
263
|
-
if (producerValidation.kind !== "accepted") return {
|
|
264
|
-
kind: "terminal",
|
|
265
|
-
result: rejectionToAppendResult(producerValidation, record.currentOffset, isClosed)
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
if (wantClose && !hasBody) {
|
|
269
|
-
if (isClosed) return {
|
|
270
|
-
kind: "terminal",
|
|
271
|
-
result: {
|
|
272
|
-
status: "appended",
|
|
273
|
-
offset: record.currentOffset,
|
|
274
|
-
closed: true
|
|
275
|
-
}
|
|
276
|
-
};
|
|
277
|
-
const casConflict$1 = expectedOffsetConflict(record, options);
|
|
278
|
-
if (casConflict$1) return {
|
|
279
|
-
kind: "terminal",
|
|
280
|
-
result: casConflict$1
|
|
281
|
-
};
|
|
282
|
-
return this.commitDecision(record, [], options, producerState, producerValidation, true);
|
|
283
|
-
}
|
|
284
|
-
if (isClosed) return {
|
|
285
|
-
kind: "terminal",
|
|
286
|
-
result: {
|
|
287
|
-
status: "conflict",
|
|
288
|
-
conflictReason: "closed",
|
|
289
|
-
closed: true,
|
|
290
|
-
offset: record.currentOffset
|
|
291
|
-
}
|
|
292
|
-
};
|
|
293
|
-
if (!contentTypeMatches(record.config.contentType, options.contentType)) return {
|
|
294
|
-
kind: "terminal",
|
|
295
|
-
result: {
|
|
296
|
-
status: "conflict",
|
|
297
|
-
conflictReason: "content-type"
|
|
298
|
-
}
|
|
299
|
-
};
|
|
300
|
-
if (options.seq && record.lifecycle.lastSeq && options.seq <= record.lifecycle.lastSeq) return {
|
|
301
|
-
kind: "terminal",
|
|
302
|
-
result: {
|
|
303
|
-
status: "conflict",
|
|
304
|
-
conflictReason: "sequence"
|
|
305
|
-
}
|
|
306
|
-
};
|
|
307
|
-
const casConflict = expectedOffsetConflict(record, options);
|
|
308
|
-
if (casConflict) return {
|
|
309
|
-
kind: "terminal",
|
|
310
|
-
result: casConflict
|
|
311
|
-
};
|
|
312
|
-
const processed = frameMessages(options.data, record.config.contentType);
|
|
313
|
-
return this.commitDecision(record, processed, options, producerState, producerValidation, wantClose);
|
|
314
|
-
}
|
|
315
|
-
commitDecision(record, data, options, producerState, producerValidation, wantClose) {
|
|
316
|
-
const allocation = allocate(this.deps.offsets, record.currentOffset, record.counter, data.length);
|
|
317
|
-
const now = this.deps.clock.now();
|
|
318
|
-
const messages = data.map((bytes, i) => ({
|
|
319
|
-
data: bytes,
|
|
320
|
-
offset: allocation.offsets[i],
|
|
321
|
-
timestamp: now
|
|
322
|
-
}));
|
|
323
|
-
const expiresAtMs = record.config.ttlSeconds === void 0 ? void 0 : now + record.config.ttlSeconds * 1e3;
|
|
324
|
-
const lifecycle = {
|
|
325
|
-
...options.seq ? { lastSeq: options.seq } : {},
|
|
326
|
-
...wantClose ? {
|
|
327
|
-
closed: true,
|
|
328
|
-
closedAt: now
|
|
329
|
-
} : {},
|
|
330
|
-
...expiresAtMs !== void 0 ? { expiresAtMs } : {}
|
|
331
|
-
};
|
|
332
|
-
const plan = {
|
|
333
|
-
preconditions: {
|
|
334
|
-
expectedOffset: options.expectedOffset ?? record.currentOffset,
|
|
335
|
-
expectedClosed: false,
|
|
336
|
-
...options.producer && producerValidation?.kind === "accepted" ? { producer: {
|
|
337
|
-
producerId: options.producer.producerId,
|
|
338
|
-
expected: producerState,
|
|
339
|
-
next: producerValidation.proposedState
|
|
340
|
-
} } : {}
|
|
341
|
-
},
|
|
342
|
-
messages,
|
|
343
|
-
recordPatch: {
|
|
344
|
-
currentOffset: allocation.nextOffset,
|
|
345
|
-
counter: allocation.endCounter,
|
|
346
|
-
lifecycle
|
|
347
|
-
}
|
|
348
|
-
};
|
|
349
|
-
return {
|
|
350
|
-
kind: "append",
|
|
351
|
-
plan,
|
|
352
|
-
afterCommit: expiresAtMs !== void 0 ? { scheduleExpiryAt: expiresAtMs } : {},
|
|
353
|
-
toResult: () => appendedResult(allocation.nextOffset, producerValidation, wantClose)
|
|
354
|
-
};
|
|
355
|
-
}
|
|
356
|
-
};
|
|
357
|
-
|
|
358
|
-
//#endregion
|
|
359
|
-
//#region src/protocol/read-service.ts
|
|
360
|
-
function normalizeReadOffset(offset) {
|
|
361
|
-
return !offset || offset === "-1" ? void 0 : offset;
|
|
362
|
-
}
|
|
363
|
-
var ReadService = class {
|
|
364
|
-
constructor(deps) {
|
|
365
|
-
this.deps = deps;
|
|
366
|
-
}
|
|
367
|
-
async execute(record, options) {
|
|
368
|
-
if (!record) return { status: "not-found" };
|
|
369
|
-
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
370
|
-
const messages = await this.deps.readChain(record, normalizeReadOffset(options.offset));
|
|
371
|
-
const lastOffset = messages.length > 0 ? messages[messages.length - 1].offset : record.currentOffset;
|
|
372
|
-
const nextOffset = compareOffsets(lastOffset, record.currentOffset) > 0 ? lastOffset : record.currentOffset;
|
|
373
|
-
const upToDate = nextOffset === record.currentOffset;
|
|
374
|
-
return {
|
|
375
|
-
status: "ok",
|
|
376
|
-
messages,
|
|
377
|
-
nextOffset,
|
|
378
|
-
upToDate,
|
|
379
|
-
closed: record.lifecycle.closed === true && upToDate
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
};
|
|
383
|
-
|
|
384
|
-
//#endregion
|
|
385
|
-
//#region src/protocol/helpers/cursor-generator.ts
|
|
386
|
-
const CURSOR_EPOCH_MS = new Date("2024-10-09T00:00:00.000Z").getTime();
|
|
387
|
-
const CURSOR_INTERVAL_MS = 2e4;
|
|
388
|
-
function generateCursor(clock, previous, random = Math.random) {
|
|
389
|
-
const currentInterval = Math.floor((clock.now() - CURSOR_EPOCH_MS) / CURSOR_INTERVAL_MS);
|
|
390
|
-
if (!previous) return String(currentInterval);
|
|
391
|
-
const previousInterval = parseInt(previous, 10);
|
|
392
|
-
if (previousInterval < currentInterval) return String(currentInterval);
|
|
393
|
-
return String(previousInterval + Math.max(1, Math.floor(random() * 180)));
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
//#endregion
|
|
397
|
-
//#region src/protocol/helpers/race-abort.ts
|
|
398
|
-
function raceAbortAwaitChange(wait, fallbackSnapshot, signal) {
|
|
399
|
-
if (!signal) return wait;
|
|
400
|
-
const timeoutResult = {
|
|
401
|
-
status: "timeout",
|
|
402
|
-
snapshot: fallbackSnapshot
|
|
403
|
-
};
|
|
404
|
-
if (signal.aborted) return Promise.resolve(timeoutResult);
|
|
405
|
-
return new Promise((resolve, reject) => {
|
|
406
|
-
const onAbort = () => {
|
|
407
|
-
cleanup();
|
|
408
|
-
resolve(timeoutResult);
|
|
409
|
-
};
|
|
410
|
-
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
411
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
412
|
-
wait.then((result) => {
|
|
413
|
-
cleanup();
|
|
414
|
-
resolve(result);
|
|
415
|
-
}, (error) => {
|
|
416
|
-
cleanup();
|
|
417
|
-
reject(error);
|
|
418
|
-
});
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
//#endregion
|
|
423
|
-
//#region src/protocol/live-read-service.ts
|
|
424
|
-
var LiveReadService = class {
|
|
425
|
-
constructor(deps) {
|
|
426
|
-
this.deps = deps;
|
|
427
|
-
}
|
|
428
|
-
async execute(record, options) {
|
|
429
|
-
if (!record) return {
|
|
430
|
-
status: "not-found",
|
|
431
|
-
messages: [],
|
|
432
|
-
nextOffset: "",
|
|
433
|
-
upToDate: false,
|
|
434
|
-
cursor: ""
|
|
435
|
-
};
|
|
436
|
-
if (record.lifecycle.softDeleted) return {
|
|
437
|
-
status: "gone",
|
|
438
|
-
messages: [],
|
|
439
|
-
nextOffset: "",
|
|
440
|
-
upToDate: false,
|
|
441
|
-
cursor: ""
|
|
442
|
-
};
|
|
443
|
-
if (record.lifecycle.closed) {
|
|
444
|
-
const messages = await this.deps.readChain(record, options.offset);
|
|
445
|
-
const lastOffset = messages.length > 0 ? messages[messages.length - 1].offset : record.currentOffset;
|
|
446
|
-
const nextOffset = compareOffsets(lastOffset, record.currentOffset) > 0 ? lastOffset : record.currentOffset;
|
|
447
|
-
return {
|
|
448
|
-
status: messages.length > 0 ? "ok" : "timeout",
|
|
449
|
-
messages,
|
|
450
|
-
nextOffset,
|
|
451
|
-
upToDate: true,
|
|
452
|
-
cursor: generateCursor(this.deps.clock, options.cursor),
|
|
453
|
-
closed: nextOffset === record.currentOffset
|
|
454
|
-
};
|
|
455
|
-
}
|
|
456
|
-
if (record.lifecycle.forkedFrom && record.lifecycle.forkOffset && compareOffsets(options.offset, record.lifecycle.forkOffset) < 0) {
|
|
457
|
-
const messages = await this.deps.readChain(record, options.offset);
|
|
458
|
-
const lastOffset = messages.length > 0 ? messages[messages.length - 1].offset : record.currentOffset;
|
|
459
|
-
return {
|
|
460
|
-
status: "ok",
|
|
461
|
-
messages,
|
|
462
|
-
nextOffset: compareOffsets(lastOffset, record.currentOffset) > 0 ? lastOffset : record.currentOffset,
|
|
463
|
-
upToDate: true,
|
|
464
|
-
cursor: generateCursor(this.deps.clock, options.cursor)
|
|
465
|
-
};
|
|
466
|
-
}
|
|
467
|
-
const fromOffset = isValidOffset(this.deps.offsets, options.offset) ? options.offset : this.deps.offsets.initialOffset;
|
|
468
|
-
const immediate = await this.deps.readOwn(fromOffset);
|
|
469
|
-
if (immediate.messages.length > 0) return {
|
|
470
|
-
status: "ok",
|
|
471
|
-
...immediate,
|
|
472
|
-
upToDate: true,
|
|
473
|
-
cursor: generateCursor(this.deps.clock, options.cursor)
|
|
474
|
-
};
|
|
475
|
-
const observed = {
|
|
476
|
-
present: true,
|
|
477
|
-
currentOffset: record.currentOffset,
|
|
478
|
-
closed: false,
|
|
479
|
-
softDeleted: false
|
|
480
|
-
};
|
|
481
|
-
const wait = await raceAbortAwaitChange(this.deps.store.awaitChange({
|
|
482
|
-
fromOffset,
|
|
483
|
-
observedClosed: observed.closed,
|
|
484
|
-
observedSoftDeleted: observed.softDeleted,
|
|
485
|
-
timeoutMs: this.deps.longPollTimeoutMs
|
|
486
|
-
}), observed, options.signal);
|
|
487
|
-
const latest = await this.deps.store.getRecord();
|
|
488
|
-
if (!latest) return {
|
|
489
|
-
status: "not-found",
|
|
490
|
-
messages: [],
|
|
491
|
-
nextOffset: "",
|
|
492
|
-
upToDate: false,
|
|
493
|
-
cursor: ""
|
|
494
|
-
};
|
|
495
|
-
if (latest.lifecycle.softDeleted) return {
|
|
496
|
-
status: "gone",
|
|
497
|
-
messages: [],
|
|
498
|
-
nextOffset: "",
|
|
499
|
-
upToDate: false,
|
|
500
|
-
cursor: ""
|
|
501
|
-
};
|
|
502
|
-
const r = await this.deps.readOwn(fromOffset);
|
|
503
|
-
const reachedTail = r.nextOffset === latest.currentOffset;
|
|
504
|
-
const hasMessages = r.messages.length > 0;
|
|
505
|
-
return {
|
|
506
|
-
status: hasMessages ? "ok" : wait.status === "timeout" ? "timeout" : "ok",
|
|
507
|
-
messages: r.messages,
|
|
508
|
-
nextOffset: r.nextOffset,
|
|
509
|
-
upToDate: true,
|
|
510
|
-
cursor: generateCursor(this.deps.clock, options.cursor),
|
|
511
|
-
closed: latest.lifecycle.closed === true && reachedTail
|
|
512
|
-
};
|
|
513
|
-
}
|
|
514
|
-
};
|
|
515
|
-
|
|
516
|
-
//#endregion
|
|
517
|
-
//#region src/protocol/helpers/bind-stream.ts
|
|
518
|
-
function bindStream(adapter, id) {
|
|
519
|
-
return {
|
|
520
|
-
id,
|
|
521
|
-
getRecord: () => adapter.getRecord(id),
|
|
522
|
-
listMessages: (options) => adapter.listMessages(id, options),
|
|
523
|
-
getProducerState: (producerId) => adapter.getProducerState(id, producerId),
|
|
524
|
-
append: (plan) => adapter.append(id, plan),
|
|
525
|
-
awaitChange: (options) => adapter.awaitChange(id, options),
|
|
526
|
-
scheduleExpiry: (at) => adapter.scheduleExpiry(id, at),
|
|
527
|
-
cancelExpiry: () => adapter.cancelExpiry(id)
|
|
528
|
-
};
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
//#endregion
|
|
532
|
-
//#region src/protocol/helpers/after-commit-effects.ts
|
|
533
|
-
/**
|
|
534
|
-
* Runtime effects that are safe to fire only after the durable mutation has
|
|
535
|
-
* committed. Storage adapters persist each intent atomically; core owns expiry
|
|
536
|
-
* scheduling so failed preconditions never fire timers.
|
|
537
|
-
*
|
|
538
|
-
* Waking live readers is not an after-commit effect: the level-triggered
|
|
539
|
-
* `awaitChange` seam re-reads durable state, so an adapter wakes its own waiters
|
|
540
|
-
* from inside a successful mutation (a pure latency optimization). Correctness
|
|
541
|
-
* never depends on a notification crossing the seam.
|
|
542
|
-
*/
|
|
543
|
-
async function runAfterCommit(effects, storage) {
|
|
544
|
-
if (!effects) return;
|
|
545
|
-
if (effects.cancelExpiry) await storage.cancelExpiry();
|
|
546
|
-
else if (effects.scheduleExpiryAt !== void 0) await storage.scheduleExpiry(effects.scheduleExpiryAt);
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
//#endregion
|
|
550
|
-
//#region src/protocol/helpers/expiry-policy.ts
|
|
551
|
-
var ExpiryPolicy = class {
|
|
552
|
-
constructor(deps) {
|
|
553
|
-
this.deps = deps;
|
|
554
|
-
}
|
|
555
|
-
computeExpiresAtMs(config) {
|
|
556
|
-
if (config.ttlSeconds !== void 0) return this.deps.clock.now() + config.ttlSeconds * 1e3;
|
|
557
|
-
if (config.expiresAt) return this.deps.clock.date(config.expiresAt).getTime();
|
|
558
|
-
return void 0;
|
|
559
|
-
}
|
|
560
|
-
async touch(stream, record, reason) {
|
|
561
|
-
if (record.config.ttlSeconds === void 0) return record;
|
|
562
|
-
if (reason === "live-read") return record;
|
|
563
|
-
const expiresAtMs = this.deps.clock.now() + record.config.ttlSeconds * 1e3;
|
|
564
|
-
const out = await stream.append({
|
|
565
|
-
preconditions: { expectedOffset: record.currentOffset },
|
|
566
|
-
recordPatch: { lifecycle: { expiresAtMs } }
|
|
567
|
-
});
|
|
568
|
-
if (out.status !== "appended") return record;
|
|
569
|
-
await runAfterCommit({ scheduleExpiryAt: expiresAtMs }, stream);
|
|
570
|
-
return out.record;
|
|
571
|
-
}
|
|
572
|
-
async scheduleExpiry(record) {
|
|
573
|
-
const at = record.lifecycle.expiresAtMs;
|
|
574
|
-
if (at !== void 0) {
|
|
575
|
-
const stream = await this.deps.resolve(record.id);
|
|
576
|
-
await stream.scheduleExpiry(at);
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
/**
|
|
580
|
-
* Lazily expire the stream if its deadline has passed, returning the current
|
|
581
|
-
* record. The storage stream is already bound to an id, so callers should pass
|
|
582
|
-
* that stream instead of threading a duplicate stream id alongside it. When
|
|
583
|
-
* the stream expires the record is re-read so the returned value reflects the
|
|
584
|
-
* post-expiry state.
|
|
585
|
-
*/
|
|
586
|
-
async expireIfNeeded(stream) {
|
|
587
|
-
const record = await stream.getRecord();
|
|
588
|
-
if (record && this.isExpired(record)) {
|
|
589
|
-
await this.deps.onScheduledExpiry(stream.id);
|
|
590
|
-
return stream.getRecord();
|
|
591
|
-
}
|
|
592
|
-
return record;
|
|
593
|
-
}
|
|
594
|
-
isExpired(record) {
|
|
595
|
-
const at = record.lifecycle.expiresAtMs;
|
|
596
|
-
return at !== void 0 && at <= this.deps.clock.now();
|
|
597
|
-
}
|
|
598
|
-
};
|
|
599
|
-
|
|
600
|
-
//#endregion
|
|
601
|
-
//#region src/protocol/helpers/create-config-matcher.ts
|
|
602
|
-
function configMatches(existing, options) {
|
|
603
|
-
const contentType = options.contentType ?? existing.config.contentType ?? "application/octet-stream";
|
|
604
|
-
if (!contentTypeMatches(existing.config.contentType, contentType)) return false;
|
|
605
|
-
if ((options.forkedFrom ?? void 0) !== existing.lifecycle.forkedFrom) return false;
|
|
606
|
-
if (options.forkOffset !== void 0 && options.forkOffset !== existing.lifecycle.forkOffset) return false;
|
|
607
|
-
if ((options.forkSubOffset ?? 0) !== (existing.lifecycle.forkSubOffset ?? 0)) return false;
|
|
608
|
-
const inheritedForkExpiry = options.forkedFrom && options.ttlSeconds === void 0 && options.expiresAt === void 0;
|
|
609
|
-
if (existing.config.ttlSeconds !== options.ttlSeconds && !inheritedForkExpiry) return false;
|
|
610
|
-
if (existing.config.expiresAt !== options.expiresAt && !inheritedForkExpiry) return false;
|
|
611
|
-
return existing.lifecycle.closed === true === (options.closed === true);
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
//#endregion
|
|
615
|
-
//#region src/protocol/create-stream-service.ts
|
|
616
|
-
var CreateStreamService = class {
|
|
617
|
-
constructor(deps) {
|
|
618
|
-
this.deps = deps;
|
|
619
|
-
}
|
|
620
|
-
plan(record, options) {
|
|
621
|
-
if (record) return {
|
|
622
|
-
kind: "terminal",
|
|
623
|
-
result: this.resultForExisting(record, options)
|
|
624
|
-
};
|
|
625
|
-
if (options.forkedFrom) return { kind: "fork" };
|
|
626
|
-
const contentType = options.contentType ?? "application/octet-stream";
|
|
627
|
-
const initialMessages = this.initialMessages(options.initialData, contentType, this.deps.offsets.initialOffset, 0);
|
|
628
|
-
const wantClosed = options.closed === true;
|
|
629
|
-
const newRecord$1 = this.deps.newRecord(contentType, options);
|
|
630
|
-
const finalRecord = this.withInitialTail(newRecord$1, initialMessages, wantClosed);
|
|
631
|
-
const plan = {
|
|
632
|
-
record: finalRecord,
|
|
633
|
-
initialMessages
|
|
634
|
-
};
|
|
635
|
-
return {
|
|
636
|
-
kind: "create",
|
|
637
|
-
plan,
|
|
638
|
-
afterCommit: finalRecord.lifecycle.expiresAtMs !== void 0 ? { scheduleExpiryAt: finalRecord.lifecycle.expiresAtMs } : {},
|
|
639
|
-
toResult: (created) => ({
|
|
640
|
-
status: "created",
|
|
641
|
-
nextOffset: created.currentOffset,
|
|
642
|
-
contentType,
|
|
643
|
-
closed: wantClosed
|
|
644
|
-
})
|
|
645
|
-
};
|
|
646
|
-
}
|
|
647
|
-
resultForExisting(existing, options) {
|
|
648
|
-
if (existing.lifecycle.softDeleted) return {
|
|
649
|
-
status: "conflict",
|
|
650
|
-
nextOffset: "",
|
|
651
|
-
contentType: "",
|
|
652
|
-
conflictReason: "soft-deleted"
|
|
653
|
-
};
|
|
654
|
-
if (!configMatches(existing, options)) return {
|
|
655
|
-
status: "conflict",
|
|
656
|
-
nextOffset: "",
|
|
657
|
-
contentType: "",
|
|
658
|
-
conflictReason: "config-mismatch"
|
|
659
|
-
};
|
|
660
|
-
return {
|
|
661
|
-
status: "exists",
|
|
662
|
-
nextOffset: existing.currentOffset,
|
|
663
|
-
contentType: existing.config.contentType,
|
|
664
|
-
closed: existing.lifecycle.closed === true
|
|
665
|
-
};
|
|
666
|
-
}
|
|
667
|
-
initialMessages(initialData, contentType, previousOffset, startCounter) {
|
|
668
|
-
const framed = initialData ? frameMessages(initialData, contentType) : [];
|
|
669
|
-
const allocation = allocate(this.deps.offsets, previousOffset, startCounter, framed.length);
|
|
670
|
-
const now = this.deps.clock.now();
|
|
671
|
-
return framed.map((data, i) => ({
|
|
672
|
-
data,
|
|
673
|
-
offset: allocation.offsets[i],
|
|
674
|
-
timestamp: now
|
|
675
|
-
}));
|
|
676
|
-
}
|
|
677
|
-
withInitialTail(record, initialMessages, closed) {
|
|
678
|
-
const lastMessage = initialMessages[initialMessages.length - 1];
|
|
679
|
-
return {
|
|
680
|
-
...record,
|
|
681
|
-
currentOffset: lastMessage?.offset ?? record.currentOffset,
|
|
682
|
-
counter: record.counter + initialMessages.length,
|
|
683
|
-
lifecycle: {
|
|
684
|
-
...record.lifecycle,
|
|
685
|
-
...closed ? {
|
|
686
|
-
closed: true,
|
|
687
|
-
closedAt: this.deps.clock.now()
|
|
688
|
-
} : {}
|
|
689
|
-
}
|
|
690
|
-
};
|
|
691
|
-
}
|
|
692
|
-
};
|
|
693
|
-
|
|
694
|
-
//#endregion
|
|
695
|
-
//#region src/protocol/helpers/fork-plan-builder.ts
|
|
696
|
-
function resolveForkExpiry(opts, source) {
|
|
697
|
-
if (opts.ttlSeconds !== void 0) return { ttlSeconds: opts.ttlSeconds };
|
|
698
|
-
if (opts.expiresAt) return { expiresAt: opts.expiresAt };
|
|
699
|
-
if (source.config.ttlSeconds !== void 0) return { ttlSeconds: source.config.ttlSeconds };
|
|
700
|
-
if (source.config.expiresAt) return { expiresAt: source.config.expiresAt };
|
|
701
|
-
return {};
|
|
702
|
-
}
|
|
703
|
-
var ForkPlanBuilder = class {
|
|
704
|
-
constructor(deps) {
|
|
705
|
-
this.deps = deps;
|
|
706
|
-
}
|
|
707
|
-
build(targetId, sourcePath, source, options, sourceTail) {
|
|
708
|
-
if (!source) return {
|
|
709
|
-
kind: "terminal",
|
|
710
|
-
result: {
|
|
711
|
-
status: "not-found",
|
|
712
|
-
nextOffset: "",
|
|
713
|
-
contentType: "",
|
|
714
|
-
errorMessage: `Source stream not found: ${sourcePath}`
|
|
715
|
-
}
|
|
716
|
-
};
|
|
717
|
-
if (source.lifecycle.softDeleted) return {
|
|
718
|
-
kind: "terminal",
|
|
719
|
-
result: {
|
|
720
|
-
status: "conflict",
|
|
721
|
-
nextOffset: "",
|
|
722
|
-
contentType: "",
|
|
723
|
-
conflictReason: "fork-source-soft-deleted",
|
|
724
|
-
errorMessage: `Source stream is soft-deleted: ${sourcePath}`
|
|
725
|
-
}
|
|
726
|
-
};
|
|
727
|
-
const forkOffset = options.forkOffset ?? source.currentOffset;
|
|
728
|
-
if (!isValidOffset(this.deps.offsets, forkOffset)) return {
|
|
729
|
-
kind: "terminal",
|
|
730
|
-
result: {
|
|
731
|
-
status: "bad-request",
|
|
732
|
-
nextOffset: "",
|
|
733
|
-
contentType: "",
|
|
734
|
-
errorMessage: "Invalid Stream-Fork-Offset format"
|
|
735
|
-
}
|
|
736
|
-
};
|
|
737
|
-
if (compareOffsets(forkOffset, this.deps.offsets.initialOffset) < 0 || compareOffsets(forkOffset, source.currentOffset) > 0) return {
|
|
738
|
-
kind: "terminal",
|
|
739
|
-
result: {
|
|
740
|
-
status: "bad-request",
|
|
741
|
-
nextOffset: "",
|
|
742
|
-
contentType: "",
|
|
743
|
-
errorMessage: "Stream-Fork-Offset exceeds source tail"
|
|
744
|
-
}
|
|
745
|
-
};
|
|
746
|
-
let contentType = options.contentType;
|
|
747
|
-
if (!contentType || contentType.trim() === "") contentType = source.config.contentType;
|
|
748
|
-
else if (!contentTypeMatches(contentType, source.config.contentType)) return {
|
|
749
|
-
kind: "terminal",
|
|
750
|
-
result: {
|
|
751
|
-
status: "conflict",
|
|
752
|
-
nextOffset: "",
|
|
753
|
-
contentType: "",
|
|
754
|
-
conflictReason: "fork-content-type",
|
|
755
|
-
errorMessage: "Fork Content-Type does not match source"
|
|
756
|
-
}
|
|
757
|
-
};
|
|
758
|
-
const subOffset = options.forkSubOffset;
|
|
759
|
-
const prefix = this.materializePrefix(subOffset, contentType, sourceTail);
|
|
760
|
-
if (!prefix.ok) return {
|
|
761
|
-
kind: "terminal",
|
|
762
|
-
result: {
|
|
763
|
-
status: "bad-request",
|
|
764
|
-
nextOffset: "",
|
|
765
|
-
contentType: "",
|
|
766
|
-
errorMessage: prefix.errorMessage
|
|
767
|
-
}
|
|
768
|
-
};
|
|
769
|
-
const expiry = resolveForkExpiry(options, source);
|
|
770
|
-
const baseRecord = this.deps.newRecord(targetId, contentType, {
|
|
771
|
-
...options,
|
|
772
|
-
...expiry
|
|
773
|
-
}, {
|
|
774
|
-
forkedFrom: sourcePath,
|
|
775
|
-
forkOffset,
|
|
776
|
-
...subOffset !== void 0 && subOffset > 0 ? { forkSubOffset: subOffset } : {}
|
|
777
|
-
});
|
|
778
|
-
const initialMessages = this.initialMessages(prefix.messages, options.initialData, contentType, baseRecord.currentOffset, baseRecord.counter);
|
|
779
|
-
const child = this.withInitialTail(baseRecord, initialMessages);
|
|
780
|
-
const plan = {
|
|
781
|
-
child,
|
|
782
|
-
sourceId: sourcePath,
|
|
783
|
-
initialMessages,
|
|
784
|
-
precondition: { sourceLiveAtOffset: forkOffset }
|
|
785
|
-
};
|
|
786
|
-
return {
|
|
787
|
-
kind: "fork",
|
|
788
|
-
plan,
|
|
789
|
-
afterCommit: child.lifecycle.expiresAtMs !== void 0 ? { scheduleExpiryAt: child.lifecycle.expiresAtMs } : {},
|
|
790
|
-
toResult: (record) => ({
|
|
791
|
-
status: "created",
|
|
792
|
-
nextOffset: record.currentOffset,
|
|
793
|
-
contentType
|
|
794
|
-
})
|
|
795
|
-
};
|
|
796
|
-
}
|
|
797
|
-
/**
|
|
798
|
-
* Materialize the partial-message prefix addressed by `forkSubOffset` from the
|
|
799
|
-
* source messages that follow `forkOffset`. `0`/absent yields no prefix. For
|
|
800
|
-
* JSON the sub-offset counts whole flattened messages; for binary/text it
|
|
801
|
-
* counts bytes within the single next source message. Overshoot or an empty
|
|
802
|
-
* source is a 400.
|
|
803
|
-
*/
|
|
804
|
-
materializePrefix(subOffset, contentType, sourceTail) {
|
|
805
|
-
if (subOffset === void 0 || subOffset === 0) return {
|
|
806
|
-
ok: true,
|
|
807
|
-
messages: []
|
|
808
|
-
};
|
|
809
|
-
const tail = sourceTail ?? [];
|
|
810
|
-
if (contentType.toLowerCase().startsWith("application/json")) {
|
|
811
|
-
if (subOffset > tail.length) return {
|
|
812
|
-
ok: false,
|
|
813
|
-
errorMessage: "Stream-Fork-Sub-Offset exceeds source message count"
|
|
814
|
-
};
|
|
815
|
-
return {
|
|
816
|
-
ok: true,
|
|
817
|
-
messages: tail.slice(0, subOffset).map((m) => m.data)
|
|
818
|
-
};
|
|
819
|
-
}
|
|
820
|
-
const first = tail[0];
|
|
821
|
-
if (!first) return {
|
|
822
|
-
ok: false,
|
|
823
|
-
errorMessage: "Stream-Fork-Sub-Offset has no source message to fork"
|
|
824
|
-
};
|
|
825
|
-
if (subOffset > first.data.byteLength) return {
|
|
826
|
-
ok: false,
|
|
827
|
-
errorMessage: "Stream-Fork-Sub-Offset exceeds source message length"
|
|
828
|
-
};
|
|
829
|
-
return {
|
|
830
|
-
ok: true,
|
|
831
|
-
messages: [first.data.subarray(0, subOffset)]
|
|
832
|
-
};
|
|
833
|
-
}
|
|
834
|
-
initialMessages(prefix, initialData, contentType, previousOffset, startCounter) {
|
|
835
|
-
const framed = [...prefix, ...initialData ? frameMessages(initialData, contentType) : []];
|
|
836
|
-
const allocation = allocate(this.deps.offsets, previousOffset, startCounter, framed.length);
|
|
837
|
-
const now = this.deps.clock.now();
|
|
838
|
-
return framed.map((data, i) => ({
|
|
839
|
-
data,
|
|
840
|
-
offset: allocation.offsets[i],
|
|
841
|
-
timestamp: now
|
|
842
|
-
}));
|
|
843
|
-
}
|
|
844
|
-
withInitialTail(record, initialMessages) {
|
|
845
|
-
const lastMessage = initialMessages[initialMessages.length - 1];
|
|
846
|
-
return {
|
|
847
|
-
...record,
|
|
848
|
-
currentOffset: lastMessage?.offset ?? record.currentOffset,
|
|
849
|
-
counter: record.counter + initialMessages.length
|
|
850
|
-
};
|
|
851
|
-
}
|
|
852
|
-
};
|
|
853
|
-
|
|
854
|
-
//#endregion
|
|
855
|
-
//#region src/protocol/storage/stream-message-reader.ts
|
|
856
|
-
var StreamMessageReader = class {
|
|
857
|
-
constructor(deps) {
|
|
858
|
-
this.deps = deps;
|
|
859
|
-
}
|
|
860
|
-
async readChain(record, afterOffset, capOffset, touchOwnTtl = true) {
|
|
861
|
-
return this.readChainFor(this.deps.stream, record, afterOffset, capOffset, touchOwnTtl);
|
|
862
|
-
}
|
|
863
|
-
async readChainFor(stream, record, afterOffset, capOffset, touchOwnTtl = true) {
|
|
864
|
-
const out = [];
|
|
865
|
-
let current = record;
|
|
866
|
-
if (current.lifecycle.forkedFrom && current.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, current.lifecycle.forkOffset) < 0)) {
|
|
867
|
-
const sourceStream = await this.deps.resolve(current.lifecycle.forkedFrom);
|
|
868
|
-
const source = await sourceStream.getRecord();
|
|
869
|
-
if (source) {
|
|
870
|
-
const upstreamCap = capOffset && compareOffsets(capOffset, current.lifecycle.forkOffset) < 0 ? capOffset : current.lifecycle.forkOffset;
|
|
871
|
-
out.push(...await this.readChainFor(sourceStream, source, afterOffset, upstreamCap, false));
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
if (touchOwnTtl) current = await this.deps.expiryPolicy.touch(stream, current, "read");
|
|
875
|
-
const ownStart = current.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, current.lifecycle.forkOffset) < 0) ? current.lifecycle.forkOffset : afterOffset;
|
|
876
|
-
const own = await stream.listMessages({
|
|
877
|
-
after: ownStart,
|
|
878
|
-
until: capOffset
|
|
879
|
-
});
|
|
880
|
-
out.push(...own);
|
|
881
|
-
return out;
|
|
882
|
-
}
|
|
883
|
-
async readOwn(after) {
|
|
884
|
-
const stream = this.deps.stream;
|
|
885
|
-
const record = await stream.getRecord();
|
|
886
|
-
if (!record) return {
|
|
887
|
-
messages: [],
|
|
888
|
-
nextOffset: ""
|
|
889
|
-
};
|
|
890
|
-
const messages = await stream.listMessages({ after });
|
|
891
|
-
if (messages.length > 0) return {
|
|
892
|
-
messages,
|
|
893
|
-
nextOffset: messages[messages.length - 1].offset
|
|
894
|
-
};
|
|
895
|
-
if (after !== void 0 && compareOffsets(after, record.currentOffset) < 0) return {
|
|
896
|
-
messages,
|
|
897
|
-
nextOffset: after
|
|
898
|
-
};
|
|
899
|
-
return {
|
|
900
|
-
messages,
|
|
901
|
-
nextOffset: record.currentOffset
|
|
902
|
-
};
|
|
903
|
-
}
|
|
904
|
-
};
|
|
905
|
-
|
|
906
|
-
//#endregion
|
|
907
|
-
//#region src/protocol/storage/stream-record-factory.ts
|
|
908
|
-
var StreamRecordFactory = class {
|
|
909
|
-
constructor(deps) {
|
|
910
|
-
this.deps = deps;
|
|
911
|
-
}
|
|
912
|
-
newRecord(streamId, contentType, options, fork) {
|
|
913
|
-
const forkOffset = fork?.forkOffset;
|
|
914
|
-
const config = {
|
|
915
|
-
contentType,
|
|
916
|
-
ttlSeconds: options.ttlSeconds,
|
|
917
|
-
expiresAt: options.expiresAt,
|
|
918
|
-
createdAt: this.deps.clock.now()
|
|
919
|
-
};
|
|
920
|
-
return {
|
|
921
|
-
id: streamId,
|
|
922
|
-
config,
|
|
923
|
-
lifecycle: {
|
|
924
|
-
forkedFrom: fork?.forkedFrom,
|
|
925
|
-
forkOffset,
|
|
926
|
-
...fork?.forkSubOffset !== void 0 && fork.forkSubOffset > 0 ? { forkSubOffset: fork.forkSubOffset } : {},
|
|
927
|
-
expiresAtMs: this.deps.expiryPolicy.computeExpiresAtMs(config)
|
|
928
|
-
},
|
|
929
|
-
currentOffset: forkOffset ?? this.deps.offsets.initialOffset,
|
|
930
|
-
counter: 0
|
|
931
|
-
};
|
|
932
|
-
}
|
|
933
|
-
};
|
|
934
|
-
|
|
935
|
-
//#endregion
|
|
936
|
-
//#region src/protocol.ts
|
|
937
|
-
const LONG_POLL_TIMEOUT_MS = 3e4;
|
|
938
|
-
const MAX_COMMIT_ATTEMPTS = 8;
|
|
939
|
-
const MAX_NO_PROGRESS_ATTEMPTS = 8;
|
|
940
|
-
function createStreamProtocol(deps) {
|
|
941
|
-
return new StreamProtocol(deps);
|
|
942
|
-
}
|
|
943
|
-
async function runDeleteEffects(status, storage) {
|
|
944
|
-
if (status === "purged") await runAfterCommit({ cancelExpiry: true }, storage);
|
|
945
|
-
}
|
|
946
|
-
function mapDelete(status) {
|
|
947
|
-
if (status === "not-found") return { status: "not-found" };
|
|
948
|
-
if (status === "gone") return { status: "gone" };
|
|
949
|
-
return { status: "ok" };
|
|
950
|
-
}
|
|
951
|
-
/**
|
|
952
|
-
* Adapt a storage `Stream` to the live-read store. Every adapter implements
|
|
953
|
-
* `awaitChange` (a backend that cannot wake cheaply polls inside its own
|
|
954
|
-
* implementation), so core wires it straight through with no fallback.
|
|
955
|
-
*/
|
|
956
|
-
function liveReadStore(storage) {
|
|
957
|
-
return {
|
|
958
|
-
getRecord: () => storage.getRecord(),
|
|
959
|
-
awaitChange: (options) => storage.awaitChange(options)
|
|
960
|
-
};
|
|
961
|
-
}
|
|
962
|
-
var ProtocolStream = class {
|
|
963
|
-
id;
|
|
964
|
-
appendService;
|
|
965
|
-
readService;
|
|
966
|
-
liveReadService;
|
|
967
|
-
createService;
|
|
968
|
-
forkPlanBuilder;
|
|
969
|
-
constructor(deps) {
|
|
970
|
-
this.deps = deps;
|
|
971
|
-
this.id = deps.storage.id;
|
|
972
|
-
const messageReader = new StreamMessageReader({
|
|
973
|
-
stream: deps.storage,
|
|
974
|
-
resolve: deps.resolveStorageStream,
|
|
975
|
-
expiryPolicy: deps.expiryPolicy
|
|
976
|
-
});
|
|
977
|
-
this.appendService = new AppendService({
|
|
978
|
-
clock: deps.clock,
|
|
979
|
-
offsets: deps.offsets
|
|
980
|
-
});
|
|
981
|
-
this.readService = new ReadService({ readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset) });
|
|
982
|
-
this.liveReadService = new LiveReadService({
|
|
983
|
-
store: liveReadStore(deps.storage),
|
|
984
|
-
clock: deps.clock,
|
|
985
|
-
longPollTimeoutMs: deps.longPollTimeoutMs,
|
|
986
|
-
offsets: deps.offsets,
|
|
987
|
-
readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset),
|
|
988
|
-
readOwn: (after) => messageReader.readOwn(after)
|
|
989
|
-
});
|
|
990
|
-
this.createService = new CreateStreamService({
|
|
991
|
-
clock: deps.clock,
|
|
992
|
-
offsets: deps.offsets,
|
|
993
|
-
newRecord: (contentType, opts) => deps.recordFactory.newRecord(deps.storage.id, contentType, opts, void 0)
|
|
994
|
-
});
|
|
995
|
-
this.forkPlanBuilder = new ForkPlanBuilder({
|
|
996
|
-
clock: deps.clock,
|
|
997
|
-
offsets: deps.offsets,
|
|
998
|
-
newRecord: (streamId, contentType, opts, fork) => deps.recordFactory.newRecord(streamId, contentType, opts, fork)
|
|
999
|
-
});
|
|
1000
|
-
}
|
|
1001
|
-
async create(options) {
|
|
1002
|
-
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1003
|
-
const decision = this.createService.plan(record, options);
|
|
1004
|
-
if (decision.kind === "terminal") return decision.result;
|
|
1005
|
-
if (decision.kind === "fork") return this.createFork(options);
|
|
1006
|
-
const commit = await this.deps.adapter.create(decision.plan);
|
|
1007
|
-
if (commit.status === "exists") return this.createService.resultForExisting(commit.record, options);
|
|
1008
|
-
await runAfterCommit(decision.afterCommit, this.deps.storage);
|
|
1009
|
-
this.deps.emitAfterCommit(commit.record);
|
|
1010
|
-
return decision.toResult(commit.record);
|
|
1011
|
-
}
|
|
1012
|
-
async append(options) {
|
|
1013
|
-
let lastRecord = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1014
|
-
let noProgressAttempts = 0;
|
|
1015
|
-
let attempt = 0;
|
|
1016
|
-
const hasUserExpectedOffset = options.expectedOffset !== void 0;
|
|
1017
|
-
while (true) {
|
|
1018
|
-
const producerState = options.producer ? await this.deps.storage.getProducerState(options.producer.producerId) : void 0;
|
|
1019
|
-
const decision = this.appendService.plan(lastRecord, options, producerState);
|
|
1020
|
-
if (decision.kind === "terminal") return decision.result;
|
|
1021
|
-
const out = await this.deps.storage.append(decision.plan);
|
|
1022
|
-
if (out.status === "appended") {
|
|
1023
|
-
await runAfterCommit(decision.afterCommit, this.deps.storage);
|
|
1024
|
-
this.deps.emitAfterCommit(out.record);
|
|
1025
|
-
return decision.toResult(out.record);
|
|
1026
|
-
}
|
|
1027
|
-
lastRecord = out.record;
|
|
1028
|
-
if (lastRecord === null) return { status: "not-found" };
|
|
1029
|
-
if (hasUserExpectedOffset) {
|
|
1030
|
-
attempt++;
|
|
1031
|
-
if (attempt >= MAX_COMMIT_ATTEMPTS) return {
|
|
1032
|
-
status: "conflict",
|
|
1033
|
-
conflictReason: "expected-offset",
|
|
1034
|
-
offset: lastRecord.currentOffset
|
|
1035
|
-
};
|
|
1036
|
-
} else {
|
|
1037
|
-
const previousOffset = decision.plan.preconditions.expectedOffset ?? this.deps.offsets.initialOffset;
|
|
1038
|
-
const madeProgress = compareOffsets(lastRecord.currentOffset, previousOffset) > 0;
|
|
1039
|
-
noProgressAttempts = madeProgress ? 0 : noProgressAttempts + 1;
|
|
1040
|
-
if (noProgressAttempts >= MAX_NO_PROGRESS_ATTEMPTS) return { status: "busy" };
|
|
1041
|
-
}
|
|
1042
|
-
await Promise.resolve();
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
async read(options) {
|
|
1046
|
-
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1047
|
-
return this.readService.execute(record, options);
|
|
1048
|
-
}
|
|
1049
|
-
async readLive(options) {
|
|
1050
|
-
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1051
|
-
return this.liveReadService.execute(record, options);
|
|
1052
|
-
}
|
|
1053
|
-
async metadata() {
|
|
1054
|
-
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1055
|
-
if (!record) return { status: "not-found" };
|
|
1056
|
-
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
1057
|
-
return {
|
|
1058
|
-
status: "ok",
|
|
1059
|
-
contentType: record.config.contentType,
|
|
1060
|
-
nextOffset: record.currentOffset,
|
|
1061
|
-
ttlSeconds: record.config.ttlSeconds,
|
|
1062
|
-
expiresAt: record.config.expiresAt,
|
|
1063
|
-
closed: record.lifecycle.closed === true
|
|
1064
|
-
};
|
|
1065
|
-
}
|
|
1066
|
-
async delete() {
|
|
1067
|
-
await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
1068
|
-
const commit = await this.deps.adapter.delete({
|
|
1069
|
-
streamId: this.id,
|
|
1070
|
-
reason: "delete"
|
|
1071
|
-
});
|
|
1072
|
-
await runDeleteEffects(commit.status, this.deps.storage);
|
|
1073
|
-
return mapDelete(commit.status);
|
|
1074
|
-
}
|
|
1075
|
-
/**
|
|
1076
|
-
* Read the source messages immediately after `forkOffset`, composed through
|
|
1077
|
-
* the source's own fork chain, so a sub-offset fork can materialize a
|
|
1078
|
-
* partial-message prefix (and chained forks compose). Only needed when a
|
|
1079
|
-
* positive `forkSubOffset` is requested; validation of the offset/sub-offset
|
|
1080
|
-
* combination stays in the fork plan builder.
|
|
1081
|
-
*/
|
|
1082
|
-
async readSourceTailForSubOffset(sourceStream, source, options) {
|
|
1083
|
-
const subOffset = options.forkSubOffset;
|
|
1084
|
-
if (subOffset === void 0 || subOffset <= 0 || !source) return void 0;
|
|
1085
|
-
const forkOffset = options.forkOffset ?? source.currentOffset;
|
|
1086
|
-
if (!isValidOffset(this.deps.offsets, forkOffset)) return void 0;
|
|
1087
|
-
const reader = new StreamMessageReader({
|
|
1088
|
-
stream: sourceStream,
|
|
1089
|
-
resolve: this.deps.resolveStorageStream,
|
|
1090
|
-
expiryPolicy: this.deps.expiryPolicy
|
|
1091
|
-
});
|
|
1092
|
-
return reader.readChain(source, forkOffset, void 0, false);
|
|
1093
|
-
}
|
|
1094
|
-
async createFork(options) {
|
|
1095
|
-
const fork = this.deps.adapter.fork;
|
|
1096
|
-
if (!fork) return notSupported("fork");
|
|
1097
|
-
const sourceId = options.forkedFrom;
|
|
1098
|
-
const sourceStream = this.deps.resolveStorageStream(sourceId);
|
|
1099
|
-
const source = await this.deps.expiryPolicy.expireIfNeeded(sourceStream);
|
|
1100
|
-
const sourceTail = await this.readSourceTailForSubOffset(sourceStream, source, options);
|
|
1101
|
-
const decision = this.forkPlanBuilder.build(this.id, sourceId, source, options, sourceTail);
|
|
1102
|
-
if (decision.kind === "terminal") return decision.result;
|
|
1103
|
-
const commit = await fork.call(this.deps.adapter, decision.plan);
|
|
1104
|
-
if (commit.status === "exists") return this.createService.resultForExisting(commit.record, options);
|
|
1105
|
-
if (commit.status === "fork-source-gone") return {
|
|
1106
|
-
status: "not-found",
|
|
1107
|
-
nextOffset: "",
|
|
1108
|
-
contentType: "",
|
|
1109
|
-
errorMessage: `Source stream not found: ${sourceId}`
|
|
1110
|
-
};
|
|
1111
|
-
await runAfterCommit(decision.afterCommit, this.deps.storage);
|
|
1112
|
-
this.deps.emitAfterCommit(commit.record);
|
|
1113
|
-
return decision.toResult(commit.record);
|
|
1114
|
-
}
|
|
1115
|
-
};
|
|
1116
|
-
var StreamProtocol = class {
|
|
1117
|
-
clock;
|
|
1118
|
-
longPollTimeoutMs;
|
|
1119
|
-
expiryPolicy;
|
|
1120
|
-
recordFactory;
|
|
1121
|
-
offsetGenerator;
|
|
1122
|
-
hooks = new Set();
|
|
1123
|
-
constructor(deps) {
|
|
1124
|
-
this.deps = deps;
|
|
1125
|
-
this.clock = deps.clock ?? systemClock;
|
|
1126
|
-
this.offsetGenerator = deps.offsetGenerator ?? defaultOffsetGenerator;
|
|
1127
|
-
assertValidOffsetGenerator(this.offsetGenerator);
|
|
1128
|
-
this.longPollTimeoutMs = deps.longPollTimeoutMs ?? LONG_POLL_TIMEOUT_MS;
|
|
1129
|
-
this.expiryPolicy = new ExpiryPolicy({
|
|
1130
|
-
resolve: (id) => this.storageStream(id),
|
|
1131
|
-
clock: this.clock,
|
|
1132
|
-
onScheduledExpiry: (id) => this.handleScheduledExpiry(id)
|
|
1133
|
-
});
|
|
1134
|
-
this.recordFactory = new StreamRecordFactory({
|
|
1135
|
-
clock: this.clock,
|
|
1136
|
-
expiryPolicy: this.expiryPolicy,
|
|
1137
|
-
offsets: this.offsetGenerator
|
|
1138
|
-
});
|
|
1139
|
-
}
|
|
1140
|
-
isValidOffset(offset) {
|
|
1141
|
-
return isValidOffset(this.offsetGenerator, offset);
|
|
1142
|
-
}
|
|
1143
|
-
async create(streamId, options) {
|
|
1144
|
-
const storage = this.storageStream(streamId);
|
|
1145
|
-
const stream = this.boundProtocolStream(storage);
|
|
1146
|
-
const result = await stream.create(options);
|
|
1147
|
-
if (result.status === "created" || result.status === "exists") return {
|
|
1148
|
-
...result,
|
|
1149
|
-
stream
|
|
1150
|
-
};
|
|
1151
|
-
return result;
|
|
1152
|
-
}
|
|
1153
|
-
async get(streamId) {
|
|
1154
|
-
const storage = this.storageStream(streamId);
|
|
1155
|
-
const record = await this.expiryPolicy.expireIfNeeded(storage);
|
|
1156
|
-
if (!record) return { status: "not-found" };
|
|
1157
|
-
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
1158
|
-
return {
|
|
1159
|
-
status: "ok",
|
|
1160
|
-
stream: this.boundProtocolStream(storage)
|
|
1161
|
-
};
|
|
1162
|
-
}
|
|
1163
|
-
onAfterCommit(hook) {
|
|
1164
|
-
this.hooks.add(hook);
|
|
1165
|
-
return () => {
|
|
1166
|
-
this.hooks.delete(hook);
|
|
1167
|
-
};
|
|
1168
|
-
}
|
|
1169
|
-
/** Called by adapter schedulers/alarms; core decides whether expiry applies. */
|
|
1170
|
-
async handleScheduledExpiry(streamId) {
|
|
1171
|
-
const storage = this.storageStream(streamId);
|
|
1172
|
-
const record = await storage.getRecord();
|
|
1173
|
-
if (!record) return;
|
|
1174
|
-
if (!this.expiryPolicy.isExpired(record)) {
|
|
1175
|
-
await this.expiryPolicy.scheduleExpiry(record);
|
|
1176
|
-
return;
|
|
1177
|
-
}
|
|
1178
|
-
const commit = await this.deps.storage.adapter.delete({
|
|
1179
|
-
streamId,
|
|
1180
|
-
reason: "expiry"
|
|
1181
|
-
});
|
|
1182
|
-
await runDeleteEffects(commit.status, storage);
|
|
1183
|
-
}
|
|
1184
|
-
boundProtocolStream(storage) {
|
|
1185
|
-
return new ProtocolStream({
|
|
1186
|
-
storage,
|
|
1187
|
-
adapter: this.deps.storage.adapter,
|
|
1188
|
-
clock: this.clock,
|
|
1189
|
-
longPollTimeoutMs: this.longPollTimeoutMs,
|
|
1190
|
-
expiryPolicy: this.expiryPolicy,
|
|
1191
|
-
recordFactory: this.recordFactory,
|
|
1192
|
-
resolveStorageStream: (id) => this.storageStream(id),
|
|
1193
|
-
emitAfterCommit: (record) => this.emitAfterCommit(record),
|
|
1194
|
-
offsets: this.offsetGenerator
|
|
1195
|
-
});
|
|
1196
|
-
}
|
|
1197
|
-
/** Bind the flat adapter to one id for ergonomic core-side per-stream calls. */
|
|
1198
|
-
storageStream(streamId) {
|
|
1199
|
-
return bindStream(this.deps.storage.adapter, streamId);
|
|
1200
|
-
}
|
|
1201
|
-
emitAfterCommit(record) {
|
|
1202
|
-
const event = {
|
|
1203
|
-
streamId: record.id,
|
|
1204
|
-
offset: record.currentOffset,
|
|
1205
|
-
closed: record.lifecycle.closed === true,
|
|
1206
|
-
softDeleted: record.lifecycle.softDeleted === true
|
|
1207
|
-
};
|
|
1208
|
-
for (const hook of this.hooks) try {
|
|
1209
|
-
hook(event);
|
|
1210
|
-
} catch (error) {
|
|
1211
|
-
console.warn("after-commit hook failed", error);
|
|
1212
|
-
}
|
|
1213
|
-
}
|
|
1214
|
-
};
|
|
1215
|
-
|
|
1216
|
-
//#endregion
|
|
1217
|
-
//#region src/storage/strategies/cascade-reclaim.ts
|
|
1218
|
-
async function cascadeReclaim(store, plan, lineage) {
|
|
1219
|
-
const record = await store.getRecord(plan.streamId);
|
|
1220
|
-
if (!record) return { status: "not-found" };
|
|
1221
|
-
if (plan.reason === "delete" && record.lifecycle.softDeleted) return { status: "gone" };
|
|
1222
|
-
const dependents = await lineage.countDependents(plan.streamId);
|
|
1223
|
-
if (dependents > 0) {
|
|
1224
|
-
await store.softDelete(plan.streamId);
|
|
1225
|
-
return { status: "retained-soft-deleted" };
|
|
1226
|
-
}
|
|
1227
|
-
await purgeAndCascade(store, lineage, record);
|
|
1228
|
-
return { status: "purged" };
|
|
1229
|
-
}
|
|
1230
|
-
async function plainPurge(store, plan) {
|
|
1231
|
-
const record = await store.getRecord(plan.streamId);
|
|
1232
|
-
if (!record) return { status: "not-found" };
|
|
1233
|
-
if (plan.reason === "delete" && record.lifecycle.softDeleted) return { status: "gone" };
|
|
1234
|
-
await store.purgeSelf(plan.streamId);
|
|
1235
|
-
return { status: "purged" };
|
|
1236
|
-
}
|
|
1237
|
-
async function purgeAndCascade(store, lineage, record) {
|
|
1238
|
-
await store.purgeSelf(record.id);
|
|
1239
|
-
let childId = record.id;
|
|
1240
|
-
let parentId = record.lifecycle.forkedFrom;
|
|
1241
|
-
while (parentId) {
|
|
1242
|
-
await lineage.dropEdge(parentId, childId);
|
|
1243
|
-
const parent = await store.getRecord(parentId);
|
|
1244
|
-
if (!parent || parent.lifecycle.softDeleted !== true) return;
|
|
1245
|
-
const dependents = await lineage.countDependents(parentId);
|
|
1246
|
-
if (dependents > 0) return;
|
|
1247
|
-
await store.purgeSelf(parentId);
|
|
1248
|
-
childId = parentId;
|
|
1249
|
-
parentId = parent.lifecycle.forkedFrom;
|
|
1250
|
-
}
|
|
1251
|
-
}
|
|
1252
|
-
|
|
1253
|
-
//#endregion
|
|
1254
|
-
//#region src/storage/strategies/ref-count-lineage.ts
|
|
1255
|
-
function refCountLineage(store) {
|
|
1256
|
-
return {
|
|
1257
|
-
async countDependents(parent) {
|
|
1258
|
-
return store.countDependents ? store.countDependents(parent) : 0;
|
|
1259
|
-
},
|
|
1260
|
-
async addEdge(parent, child) {
|
|
1261
|
-
await store.addEdge?.(parent, child);
|
|
1262
|
-
},
|
|
1263
|
-
async dropEdge(parent, child) {
|
|
1264
|
-
await store.dropEdge?.(parent, child);
|
|
1265
|
-
}
|
|
1266
|
-
};
|
|
1267
|
-
}
|
|
1268
|
-
|
|
1269
|
-
//#endregion
|
|
1270
|
-
//#region src/storage/strategies/reverse-index-lineage.ts
|
|
1271
|
-
function reverseIndexLineage(query) {
|
|
1272
|
-
return {
|
|
1273
|
-
countDependents(parent) {
|
|
1274
|
-
return query(parent);
|
|
1275
|
-
},
|
|
1276
|
-
async addEdge() {},
|
|
1277
|
-
async dropEdge() {}
|
|
1278
|
-
};
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
|
-
//#endregion
|
|
1282
|
-
//#region src/storage/strategies/copy-on-fork.ts
|
|
1283
|
-
function copyOnForkReclaim() {
|
|
1284
|
-
return {
|
|
1285
|
-
async countDependents() {
|
|
1286
|
-
return 0;
|
|
1287
|
-
},
|
|
1288
|
-
async addEdge() {},
|
|
1289
|
-
async dropEdge() {}
|
|
1290
|
-
};
|
|
1291
|
-
}
|
|
1292
|
-
|
|
1293
|
-
//#endregion
|
|
1294
|
-
//#region src/storage/strategies/ttl-only.ts
|
|
1295
|
-
function ttlOnlyReclaim() {
|
|
1296
|
-
return {
|
|
1297
|
-
async countDependents() {
|
|
1298
|
-
return 1;
|
|
1299
|
-
},
|
|
1300
|
-
async addEdge() {},
|
|
1301
|
-
async dropEdge() {}
|
|
1302
|
-
};
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
|
-
//#endregion
|
|
1306
|
-
//#region src/storage/memory/lineage-store.ts
|
|
1307
|
-
var MemoryLineageStore = class {
|
|
1308
|
-
constructor(state) {
|
|
1309
|
-
this.state = state;
|
|
1310
|
-
}
|
|
1311
|
-
async getRecord(id) {
|
|
1312
|
-
return this.state.getExistingStream(id)?.getRecord() ?? null;
|
|
1313
|
-
}
|
|
1314
|
-
async purgeSelf(id) {
|
|
1315
|
-
this.state.getExistingStream(id)?.purgeSelf();
|
|
1316
|
-
}
|
|
1317
|
-
async softDelete(id) {
|
|
1318
|
-
this.state.getExistingStream(id)?.softDelete();
|
|
1319
|
-
}
|
|
1320
|
-
async addEdge(parent, child) {
|
|
1321
|
-
this.state.addEdge(parent, child);
|
|
1322
|
-
}
|
|
1323
|
-
async dropEdge(parent, child) {
|
|
1324
|
-
this.state.dropEdge(parent, child);
|
|
1325
|
-
}
|
|
1326
|
-
async countDependents(parent) {
|
|
1327
|
-
return this.state.countDependents(parent);
|
|
1328
|
-
}
|
|
1329
|
-
};
|
|
1330
|
-
|
|
1331
|
-
//#endregion
|
|
1332
|
-
//#region src/protocol/helpers/change-snapshot.ts
|
|
1333
|
-
/** Build the serializable, change-relevant snapshot of a (possibly absent) record. */
|
|
1334
|
-
function buildChangeSnapshot(record) {
|
|
1335
|
-
if (!record) return {
|
|
1336
|
-
present: false,
|
|
1337
|
-
currentOffset: ZERO_OFFSET,
|
|
1338
|
-
closed: false,
|
|
1339
|
-
softDeleted: false
|
|
1340
|
-
};
|
|
1341
|
-
return {
|
|
1342
|
-
present: true,
|
|
1343
|
-
currentOffset: record.currentOffset,
|
|
1344
|
-
closed: record.lifecycle.closed === true,
|
|
1345
|
-
softDeleted: record.lifecycle.softDeleted === true
|
|
1346
|
-
};
|
|
1347
|
-
}
|
|
1348
|
-
/**
|
|
1349
|
-
* The level-triggered "differs" predicate. A snapshot differs from what the
|
|
1350
|
-
* caller observed when the record was purged, transitioned to soft-deleted or
|
|
1351
|
-
* closed, or its offset is not the parked position. Offset **inequality** — not
|
|
1352
|
-
* just advance — is the trigger: within one incarnation an offset only ever
|
|
1353
|
-
* advances, so a *lower* offset means the stream was purged and re-created
|
|
1354
|
-
* while the waiter was parked, which is also "something happened".
|
|
1355
|
-
*/
|
|
1356
|
-
function changeSnapshotDiffers(snapshot, options) {
|
|
1357
|
-
if (!snapshot.present) return true;
|
|
1358
|
-
if (snapshot.softDeleted && options.observedSoftDeleted !== true) return true;
|
|
1359
|
-
if (snapshot.closed && options.observedClosed !== true) return true;
|
|
1360
|
-
return compareOffsets(snapshot.currentOffset, options.fromOffset) !== 0;
|
|
1361
|
-
}
|
|
1362
|
-
|
|
1363
|
-
//#endregion
|
|
1364
|
-
//#region src/protocol/helpers/await-change-loop.ts
|
|
1365
|
-
async function runAwaitChangeLoop(deps, options) {
|
|
1366
|
-
const now = deps.now ?? (() => Date.now());
|
|
1367
|
-
const budget = deps.totalCapMs === void 0 ? options.timeoutMs : Math.min(options.timeoutMs, deps.totalCapMs);
|
|
1368
|
-
const start = now();
|
|
1369
|
-
while (true) {
|
|
1370
|
-
const snapshot = buildChangeSnapshot(await deps.readRecord());
|
|
1371
|
-
if (changeSnapshotDiffers(snapshot, options)) return {
|
|
1372
|
-
status: "changed",
|
|
1373
|
-
snapshot
|
|
1374
|
-
};
|
|
1375
|
-
const remaining = budget - (now() - start);
|
|
1376
|
-
if (remaining <= 0) return {
|
|
1377
|
-
status: "timeout",
|
|
1378
|
-
snapshot
|
|
1379
|
-
};
|
|
1380
|
-
const park = deps.parkCapMs === void 0 ? remaining : Math.min(remaining, deps.parkCapMs);
|
|
1381
|
-
await deps.waitForWake(park);
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
|
|
1385
|
-
//#endregion
|
|
1386
|
-
//#region src/storage/memory/lib/clone.ts
|
|
1387
|
-
function clone$1(value) {
|
|
1388
|
-
if (value === null || value === void 0) return value;
|
|
1389
|
-
return structuredClone(value);
|
|
1390
|
-
}
|
|
1391
|
-
|
|
1392
|
-
//#endregion
|
|
1393
|
-
//#region src/storage/memory/stores/message-store.ts
|
|
1394
|
-
var MessageStore = class {
|
|
1395
|
-
messages = [];
|
|
1396
|
-
constructor(records) {
|
|
1397
|
-
this.records = records;
|
|
1398
|
-
}
|
|
1399
|
-
appendMessages(messages) {
|
|
1400
|
-
this.records.requireRecord();
|
|
1401
|
-
this.messages.push(...clone$1(messages));
|
|
1402
|
-
}
|
|
1403
|
-
listMessages(options = {}) {
|
|
1404
|
-
let out = this.messages;
|
|
1405
|
-
if (options.after) out = out.filter((m) => m.offset > options.after);
|
|
1406
|
-
if (options.until) out = out.filter((m) => m.offset <= options.until);
|
|
1407
|
-
if (options.limit !== void 0) out = out.slice(0, options.limit);
|
|
1408
|
-
return clone$1(out);
|
|
1409
|
-
}
|
|
1410
|
-
deleteMessages() {
|
|
1411
|
-
this.messages = [];
|
|
1412
|
-
}
|
|
1413
|
-
};
|
|
1414
|
-
|
|
1415
|
-
//#endregion
|
|
1416
|
-
//#region src/storage/memory/stores/producer-store.ts
|
|
1417
|
-
var ProducerStore = class {
|
|
1418
|
-
producers = new Map();
|
|
1419
|
-
constructor(records) {
|
|
1420
|
-
this.records = records;
|
|
1421
|
-
}
|
|
1422
|
-
getProducerState(producerId) {
|
|
1423
|
-
return clone$1(this.producers.get(producerId));
|
|
1424
|
-
}
|
|
1425
|
-
setProducerState(producerId, producerState) {
|
|
1426
|
-
this.records.requireRecord();
|
|
1427
|
-
this.producers.set(producerId, clone$1(producerState));
|
|
1428
|
-
}
|
|
1429
|
-
deleteProducerStates() {
|
|
1430
|
-
this.producers.clear();
|
|
1431
|
-
}
|
|
1432
|
-
};
|
|
1433
|
-
|
|
1434
|
-
//#endregion
|
|
1435
|
-
//#region src/storage/memory/stores/record-store.ts
|
|
1436
|
-
var RecordStore = class {
|
|
1437
|
-
record;
|
|
1438
|
-
constructor(id) {
|
|
1439
|
-
this.id = id;
|
|
1440
|
-
}
|
|
1441
|
-
getRecord() {
|
|
1442
|
-
return clone$1(this.record ?? null);
|
|
1443
|
-
}
|
|
1444
|
-
createRecord(record) {
|
|
1445
|
-
if (record.id !== this.id) throw new Error(`Record id ${record.id} does not match bound stream ${this.id}`);
|
|
1446
|
-
if (this.record) return {
|
|
1447
|
-
status: "exists",
|
|
1448
|
-
record: clone$1(this.record)
|
|
1449
|
-
};
|
|
1450
|
-
this.record = clone$1(record);
|
|
1451
|
-
return { status: "created" };
|
|
1452
|
-
}
|
|
1453
|
-
updateRecord(patch) {
|
|
1454
|
-
const record = this.requireRecord();
|
|
1455
|
-
this.record = {
|
|
1456
|
-
...record,
|
|
1457
|
-
config: {
|
|
1458
|
-
...record.config,
|
|
1459
|
-
...patch.config
|
|
1460
|
-
},
|
|
1461
|
-
lifecycle: {
|
|
1462
|
-
...record.lifecycle,
|
|
1463
|
-
...patch.lifecycle
|
|
1464
|
-
},
|
|
1465
|
-
currentOffset: patch.currentOffset ?? record.currentOffset,
|
|
1466
|
-
counter: patch.counter ?? record.counter
|
|
1467
|
-
};
|
|
1468
|
-
return clone$1(this.record);
|
|
1469
|
-
}
|
|
1470
|
-
deleteRecord() {
|
|
1471
|
-
this.record = void 0;
|
|
1472
|
-
}
|
|
1473
|
-
requireRecord() {
|
|
1474
|
-
if (!this.record) throw new Error(`Stream not found: ${this.id}`);
|
|
1475
|
-
return this.record;
|
|
1476
|
-
}
|
|
1477
|
-
};
|
|
1478
|
-
|
|
1479
|
-
//#endregion
|
|
1480
|
-
//#region src/storage/memory/utils/notifier.ts
|
|
1481
|
-
/**
|
|
1482
|
-
* In-process wake bus backing the memory adapter's level-triggered `awaitChange`.
|
|
1483
|
-
*
|
|
1484
|
-
* A parked waiter resolves either when a mutation calls {@link wake} or after its
|
|
1485
|
-
* timeout; the caller re-reads durable state to decide whether anything relevant
|
|
1486
|
-
* changed. Spurious wakes are safe — the caller simply re-checks and parks again
|
|
1487
|
-
* within its remaining budget.
|
|
1488
|
-
*/
|
|
1489
|
-
var MemoryNotifier = class {
|
|
1490
|
-
wakeWaiters = new Set();
|
|
1491
|
-
waitForWake(timeoutMs) {
|
|
1492
|
-
return new Promise((resolve) => {
|
|
1493
|
-
const finish = () => {
|
|
1494
|
-
clearTimeout(timeout);
|
|
1495
|
-
this.wakeWaiters.delete(finish);
|
|
1496
|
-
resolve();
|
|
1497
|
-
};
|
|
1498
|
-
const timeout = setTimeout(finish, timeoutMs);
|
|
1499
|
-
this.wakeWaiters.add(finish);
|
|
1500
|
-
});
|
|
1501
|
-
}
|
|
1502
|
-
/** Wake every parked `awaitChange` waiter. Called from inside a mutation. */
|
|
1503
|
-
wake() {
|
|
1504
|
-
if (this.wakeWaiters.size === 0) return;
|
|
1505
|
-
const waiters = [...this.wakeWaiters];
|
|
1506
|
-
this.wakeWaiters.clear();
|
|
1507
|
-
for (const waiter of waiters) waiter();
|
|
1508
|
-
}
|
|
1509
|
-
};
|
|
1510
|
-
|
|
1511
|
-
//#endregion
|
|
1512
|
-
//#region src/storage/memory/utils/timeout-scheduler.ts
|
|
1513
|
-
var TimeoutScheduler = class {
|
|
1514
|
-
timer;
|
|
1515
|
-
constructor(callback) {
|
|
1516
|
-
this.callback = callback;
|
|
1517
|
-
}
|
|
1518
|
-
schedule(at) {
|
|
1519
|
-
this.cancel();
|
|
1520
|
-
if (!this.callback) return;
|
|
1521
|
-
const delay$1 = Math.max(0, at - Date.now());
|
|
1522
|
-
this.timer = setTimeout(() => {
|
|
1523
|
-
Promise.resolve(this.callback?.()).catch((error) => {
|
|
1524
|
-
console.error("memory expiry callback failed", error);
|
|
1525
|
-
});
|
|
1526
|
-
}, delay$1);
|
|
1527
|
-
}
|
|
1528
|
-
cancel() {
|
|
1529
|
-
if (this.timer) clearTimeout(this.timer);
|
|
1530
|
-
this.timer = void 0;
|
|
1531
|
-
}
|
|
1532
|
-
};
|
|
1533
|
-
|
|
1534
|
-
//#endregion
|
|
1535
|
-
//#region src/storage/memory/stream.ts
|
|
1536
|
-
/** Adapter-private per-stream handle. Not on the seam — owned by the memory state. */
|
|
1537
|
-
var MemoryStream = class {
|
|
1538
|
-
records;
|
|
1539
|
-
messages;
|
|
1540
|
-
producers;
|
|
1541
|
-
notifier;
|
|
1542
|
-
timeout;
|
|
1543
|
-
constructor(id, deleteFromState, onScheduledExpiry) {
|
|
1544
|
-
this.id = id;
|
|
1545
|
-
this.deleteFromState = deleteFromState;
|
|
1546
|
-
this.records = new RecordStore(id);
|
|
1547
|
-
this.messages = new MessageStore(this.records);
|
|
1548
|
-
this.producers = new ProducerStore(this.records);
|
|
1549
|
-
this.notifier = new MemoryNotifier();
|
|
1550
|
-
this.timeout = new TimeoutScheduler(onScheduledExpiry);
|
|
1551
|
-
}
|
|
1552
|
-
getRecord() {
|
|
1553
|
-
return this.records.getRecord();
|
|
1554
|
-
}
|
|
1555
|
-
/** Public append intent (no `createRecord`). */
|
|
1556
|
-
append(plan) {
|
|
1557
|
-
const out = this.applyMutation({
|
|
1558
|
-
preconditions: plan.preconditions,
|
|
1559
|
-
messages: plan.messages,
|
|
1560
|
-
recordPatch: plan.recordPatch
|
|
1561
|
-
});
|
|
1562
|
-
if (out.status === "committed") return {
|
|
1563
|
-
status: "appended",
|
|
1564
|
-
record: out.record
|
|
1565
|
-
};
|
|
1566
|
-
return {
|
|
1567
|
-
status: "precondition-failed",
|
|
1568
|
-
record: out.record,
|
|
1569
|
-
reason: out.reason ?? "offset"
|
|
1570
|
-
};
|
|
1571
|
-
}
|
|
1572
|
-
/**
|
|
1573
|
-
* Adapter-internal write engine shared by `append` (no `createRecord`) and the
|
|
1574
|
-
* `create`/`fork` intents (with `createRecord`).
|
|
1575
|
-
*/
|
|
1576
|
-
applyMutation(plan) {
|
|
1577
|
-
let record = this.records.getRecord();
|
|
1578
|
-
if (plan.createRecord) {
|
|
1579
|
-
if (record) return {
|
|
1580
|
-
status: "precondition-failed",
|
|
1581
|
-
record
|
|
1582
|
-
};
|
|
1583
|
-
const created = this.records.createRecord(plan.createRecord);
|
|
1584
|
-
if (created.status === "exists") return {
|
|
1585
|
-
status: "precondition-failed",
|
|
1586
|
-
record: created.record
|
|
1587
|
-
};
|
|
1588
|
-
record = this.records.getRecord();
|
|
1589
|
-
}
|
|
1590
|
-
if (!record) return {
|
|
1591
|
-
status: "precondition-failed",
|
|
1592
|
-
record: null
|
|
1593
|
-
};
|
|
1594
|
-
if (plan.preconditions.expectedOffset !== void 0 && plan.preconditions.expectedOffset !== record.currentOffset) return {
|
|
1595
|
-
status: "precondition-failed",
|
|
1596
|
-
record,
|
|
1597
|
-
reason: "offset"
|
|
1598
|
-
};
|
|
1599
|
-
if (plan.preconditions.expectedClosed !== void 0 && plan.preconditions.expectedClosed !== (record.lifecycle.closed === true)) return {
|
|
1600
|
-
status: "precondition-failed",
|
|
1601
|
-
record,
|
|
1602
|
-
reason: "closed"
|
|
1603
|
-
};
|
|
1604
|
-
const producer = plan.preconditions.producer;
|
|
1605
|
-
if (producer) {
|
|
1606
|
-
const current = this.producers.getProducerState(producer.producerId);
|
|
1607
|
-
if (!producerStatesEqual(current, producer.expected)) return {
|
|
1608
|
-
status: "precondition-failed",
|
|
1609
|
-
record,
|
|
1610
|
-
reason: "producer"
|
|
1611
|
-
};
|
|
1612
|
-
}
|
|
1613
|
-
if (plan.messages && plan.messages.length > 0) this.messages.appendMessages(plan.messages);
|
|
1614
|
-
if (plan.recordPatch) record = this.records.updateRecord(plan.recordPatch);
|
|
1615
|
-
if (producer) this.producers.setProducerState(producer.producerId, producer.next);
|
|
1616
|
-
this.notifier.wake();
|
|
1617
|
-
return {
|
|
1618
|
-
status: "committed",
|
|
1619
|
-
record: this.records.getRecord() ?? record
|
|
1620
|
-
};
|
|
1621
|
-
}
|
|
1622
|
-
listMessages(options) {
|
|
1623
|
-
return this.messages.listMessages(options);
|
|
1624
|
-
}
|
|
1625
|
-
getProducerState(producerId) {
|
|
1626
|
-
return this.producers.getProducerState(producerId);
|
|
1627
|
-
}
|
|
1628
|
-
purgeSelf() {
|
|
1629
|
-
this.messages.deleteMessages();
|
|
1630
|
-
this.producers.deleteProducerStates();
|
|
1631
|
-
this.records.deleteRecord();
|
|
1632
|
-
this.timeout.cancel();
|
|
1633
|
-
this.deleteFromState();
|
|
1634
|
-
this.notifier.wake();
|
|
1635
|
-
}
|
|
1636
|
-
softDelete() {
|
|
1637
|
-
this.records.updateRecord({ lifecycle: { softDeleted: true } });
|
|
1638
|
-
this.notifier.wake();
|
|
1639
|
-
}
|
|
1640
|
-
/**
|
|
1641
|
-
* Level-triggered live wait via the shared exported loop: re-read durable
|
|
1642
|
-
* state first (so a mutation that landed between the caller's observation and
|
|
1643
|
-
* this call is never missed), then park on the wake bus until the state
|
|
1644
|
-
* advances or the budget expires. Read and park are synchronous with the wake
|
|
1645
|
-
* bus here, so no per-park cap is needed.
|
|
1646
|
-
*/
|
|
1647
|
-
awaitChange(options) {
|
|
1648
|
-
return runAwaitChangeLoop({
|
|
1649
|
-
readRecord: () => this.records.getRecord(),
|
|
1650
|
-
waitForWake: (timeoutMs) => this.notifier.waitForWake(timeoutMs)
|
|
1651
|
-
}, options);
|
|
1652
|
-
}
|
|
1653
|
-
scheduleExpiry(at) {
|
|
1654
|
-
return this.timeout.schedule(at);
|
|
1655
|
-
}
|
|
1656
|
-
cancelExpiry() {
|
|
1657
|
-
return this.timeout.cancel();
|
|
1658
|
-
}
|
|
1659
|
-
};
|
|
1660
|
-
function producerStatesEqual(left, right) {
|
|
1661
|
-
if (!left || !right) return left === right;
|
|
1662
|
-
return left.epoch === right.epoch && left.lastSeq === right.lastSeq;
|
|
1663
|
-
}
|
|
1664
|
-
|
|
1665
|
-
//#endregion
|
|
1666
|
-
//#region src/storage/memory/state.ts
|
|
1667
|
-
/** Shared in-memory stream registry. */
|
|
1668
|
-
var MemoryStreamState = class {
|
|
1669
|
-
streams = new Map();
|
|
1670
|
-
childEdges = new Map();
|
|
1671
|
-
constructor(onScheduledExpiry) {
|
|
1672
|
-
this.onScheduledExpiry = onScheduledExpiry;
|
|
1673
|
-
}
|
|
1674
|
-
getStream(id) {
|
|
1675
|
-
let stream = this.streams.get(id);
|
|
1676
|
-
if (!stream) {
|
|
1677
|
-
stream = new MemoryStream(id, () => this.deleteStream(id), () => this.onScheduledExpiry?.(id));
|
|
1678
|
-
this.streams.set(id, stream);
|
|
1679
|
-
}
|
|
1680
|
-
return stream;
|
|
1681
|
-
}
|
|
1682
|
-
getExistingStream(id) {
|
|
1683
|
-
return this.streams.get(id);
|
|
1684
|
-
}
|
|
1685
|
-
addEdge(parent, child) {
|
|
1686
|
-
const children = this.childEdges.get(parent) ?? new Set();
|
|
1687
|
-
children.add(child);
|
|
1688
|
-
this.childEdges.set(parent, children);
|
|
1689
|
-
}
|
|
1690
|
-
dropEdge(parent, child) {
|
|
1691
|
-
const children = this.childEdges.get(parent);
|
|
1692
|
-
if (!children) return;
|
|
1693
|
-
children.delete(child);
|
|
1694
|
-
if (children.size === 0) this.childEdges.delete(parent);
|
|
1695
|
-
}
|
|
1696
|
-
countDependents(parent) {
|
|
1697
|
-
return this.childEdges.get(parent)?.size ?? 0;
|
|
1698
|
-
}
|
|
1699
|
-
deleteStream(id) {
|
|
1700
|
-
this.streams.delete(id);
|
|
1701
|
-
this.childEdges.delete(id);
|
|
1702
|
-
}
|
|
1703
|
-
};
|
|
1704
|
-
|
|
1705
|
-
//#endregion
|
|
1706
|
-
//#region src/storage/memory/adapter.ts
|
|
1707
|
-
function createMemoryStorageAdapter(options = {}) {
|
|
1708
|
-
const state = options.state ?? new MemoryStreamState(options.onScheduledExpiry);
|
|
1709
|
-
const lineageStore = new MemoryLineageStore(state);
|
|
1710
|
-
const lineage = refCountLineage(lineageStore);
|
|
1711
|
-
return {
|
|
1712
|
-
getRecord: (streamId) => Promise.resolve(state.getStream(streamId).getRecord()),
|
|
1713
|
-
listMessages: (streamId, listOptions) => Promise.resolve(state.getStream(streamId).listMessages(listOptions)),
|
|
1714
|
-
getProducerState: (streamId, producerId) => Promise.resolve(state.getStream(streamId).getProducerState(producerId)),
|
|
1715
|
-
append: (streamId, plan) => Promise.resolve(state.getStream(streamId).append(plan)),
|
|
1716
|
-
awaitChange: (streamId, awaitOptions) => state.getStream(streamId).awaitChange(awaitOptions),
|
|
1717
|
-
scheduleExpiry: (streamId, at) => state.getStream(streamId).scheduleExpiry(at),
|
|
1718
|
-
cancelExpiry: (streamId) => state.getStream(streamId).cancelExpiry(),
|
|
1719
|
-
async create(plan) {
|
|
1720
|
-
const stream = state.getStream(plan.record.id);
|
|
1721
|
-
const result = stream.applyMutation({
|
|
1722
|
-
createRecord: plan.record,
|
|
1723
|
-
preconditions: {},
|
|
1724
|
-
messages: plan.initialMessages
|
|
1725
|
-
});
|
|
1726
|
-
if (result.status === "committed") return {
|
|
1727
|
-
status: "created",
|
|
1728
|
-
record: result.record
|
|
1729
|
-
};
|
|
1730
|
-
return {
|
|
1731
|
-
status: "exists",
|
|
1732
|
-
record: result.record ?? plan.record
|
|
1733
|
-
};
|
|
1734
|
-
},
|
|
1735
|
-
async fork(plan) {
|
|
1736
|
-
const source = state.getExistingStream(plan.sourceId)?.getRecord() ?? null;
|
|
1737
|
-
if (!source || source.lifecycle.softDeleted || compareOffsets(source.currentOffset, plan.precondition.sourceLiveAtOffset) < 0) return { status: "fork-source-gone" };
|
|
1738
|
-
const child = state.getStream(plan.child.id);
|
|
1739
|
-
const result = child.applyMutation({
|
|
1740
|
-
createRecord: plan.child,
|
|
1741
|
-
preconditions: {},
|
|
1742
|
-
messages: plan.initialMessages
|
|
1743
|
-
});
|
|
1744
|
-
if (result.status !== "committed") {
|
|
1745
|
-
const existing = result.record ?? child.getRecord() ?? plan.child;
|
|
1746
|
-
if (existing.lifecycle.forkedFrom === plan.sourceId) await lineage.addEdge(plan.sourceId, plan.child.id);
|
|
1747
|
-
return {
|
|
1748
|
-
status: "exists",
|
|
1749
|
-
record: existing
|
|
1750
|
-
};
|
|
1751
|
-
}
|
|
1752
|
-
await lineage.addEdge(plan.sourceId, plan.child.id);
|
|
1753
|
-
return {
|
|
1754
|
-
status: "created",
|
|
1755
|
-
record: result.record
|
|
1756
|
-
};
|
|
1757
|
-
},
|
|
1758
|
-
delete(plan) {
|
|
1759
|
-
return cascadeReclaim(lineageStore, plan, lineage);
|
|
1760
|
-
}
|
|
1761
|
-
};
|
|
1762
|
-
}
|
|
1763
|
-
|
|
1764
|
-
//#endregion
|
|
1765
|
-
//#region src/http/not-supported.ts
|
|
1766
|
-
function notSupportedResponse(result, responses) {
|
|
1767
|
-
const detail = result.message ?? `Feature not supported: ${result.feature}`;
|
|
1768
|
-
return responses.text(detail, 400, { "stream-not-supported": result.feature });
|
|
1769
|
-
}
|
|
1770
|
-
/**
|
|
1771
|
-
* Convenience for use in `case`-style handlers that may want to short
|
|
1772
|
-
* circuit on a `not-supported` result before pattern-matching the rest of a
|
|
1773
|
-
* union.
|
|
1774
|
-
*/
|
|
1775
|
-
function maybeNotSupportedResponse(result, responses) {
|
|
1776
|
-
return isNotSupported(result) ? notSupportedResponse(result, responses) : null;
|
|
1777
|
-
}
|
|
1778
|
-
|
|
1779
|
-
//#endregion
|
|
1780
|
-
//#region src/http/dispatch-service.ts
|
|
1781
|
-
var HttpDispatchService = class {
|
|
1782
|
-
constructor(deps) {
|
|
1783
|
-
this.deps = deps;
|
|
1784
|
-
}
|
|
1785
|
-
async fetch(request) {
|
|
1786
|
-
return this.deps.responses.secure(await this.execute(request));
|
|
1787
|
-
}
|
|
1788
|
-
async execute(request) {
|
|
1789
|
-
const url = new URL(request.url);
|
|
1790
|
-
const streamId = this.deps.path.strip(url.pathname);
|
|
1791
|
-
if (!streamId || streamId === url.pathname) return this.deps.responses.badRequest(`Stream path required: ${this.deps.path.requiredPathPattern()}`);
|
|
1792
|
-
const ctx = {
|
|
1793
|
-
request,
|
|
1794
|
-
url,
|
|
1795
|
-
streamId
|
|
1796
|
-
};
|
|
1797
|
-
try {
|
|
1798
|
-
switch (request.method) {
|
|
1799
|
-
case "PUT": return await this.deps.create.execute(ctx);
|
|
1800
|
-
case "POST": return await this.withBoundStream(ctx, (bound) => this.deps.append.execute(bound));
|
|
1801
|
-
case "GET": return await this.withBoundStream(ctx, (bound) => this.deps.read.execute(bound));
|
|
1802
|
-
case "HEAD": return await this.withBoundStream(ctx, (bound) => this.deps.metadata.execute(bound));
|
|
1803
|
-
case "DELETE": return await this.withBoundStream(ctx, (bound) => this.deps.delete.execute(bound));
|
|
1804
|
-
default: return this.deps.responses.methodNotAllowed();
|
|
1805
|
-
}
|
|
1806
|
-
} catch (error) {
|
|
1807
|
-
if (isNotSupportedError(error)) return notSupportedResponse(notSupportedFromError(error), this.deps.responses);
|
|
1808
|
-
console.error("Error handling request:", error);
|
|
1809
|
-
return this.deps.responses.internalError();
|
|
1810
|
-
}
|
|
1811
|
-
}
|
|
1812
|
-
async withBoundStream(ctx, fn) {
|
|
1813
|
-
const lookup = await this.deps.protocol.get(ctx.streamId);
|
|
1814
|
-
if (lookup.status === "not-found") return this.deps.responses.notFound();
|
|
1815
|
-
if (lookup.status === "gone") return this.deps.responses.gone();
|
|
1816
|
-
if (isNotSupported(lookup)) return notSupportedResponse(lookup, this.deps.responses);
|
|
1817
|
-
return fn({
|
|
1818
|
-
...ctx,
|
|
1819
|
-
stream: lookup.stream
|
|
1820
|
-
});
|
|
1821
|
-
}
|
|
1822
|
-
};
|
|
1823
|
-
|
|
1824
|
-
//#endregion
|
|
1825
|
-
//#region src/http/etag-builder.ts
|
|
1826
|
-
var EtagBuilder = class {
|
|
1827
|
-
forCatchUp(pathname, startOffset, nextOffset, closed) {
|
|
1828
|
-
const closedSuffix = closed ? ":c" : "";
|
|
1829
|
-
return `"${btoa(pathname)}:${startOffset}:${nextOffset}${closedSuffix}"`;
|
|
1830
|
-
}
|
|
1831
|
-
};
|
|
1832
|
-
|
|
1833
|
-
//#endregion
|
|
1834
|
-
//#region src/http/message-body-codec.ts
|
|
1835
|
-
var MessageBodyCodec = class {
|
|
1836
|
-
decoder = new TextDecoder();
|
|
1837
|
-
encodeHttpBody(messages, contentType) {
|
|
1838
|
-
const lower = contentType.toLowerCase();
|
|
1839
|
-
if (lower.startsWith("application/json")) {
|
|
1840
|
-
const items = messages.map((msg) => this.decoder.decode(msg.data));
|
|
1841
|
-
return `[${items.join(",")}]`;
|
|
1842
|
-
}
|
|
1843
|
-
if (lower.startsWith("text/")) return messages.map((msg) => this.decoder.decode(msg.data)).join("");
|
|
1844
|
-
return this.concatBytes(messages).buffer;
|
|
1845
|
-
}
|
|
1846
|
-
emptyBodyForContentType(contentType) {
|
|
1847
|
-
return contentType.toLowerCase().startsWith("application/json") ? "[]" : "";
|
|
1848
|
-
}
|
|
1849
|
-
concatBytes(messages) {
|
|
1850
|
-
const totalLength = messages.reduce((acc, msg) => acc + msg.data.length, 0);
|
|
1851
|
-
const combined = new Uint8Array(totalLength);
|
|
1852
|
-
let pos = 0;
|
|
1853
|
-
for (const msg of messages) {
|
|
1854
|
-
combined.set(msg.data, pos);
|
|
1855
|
-
pos += msg.data.length;
|
|
1856
|
-
}
|
|
1857
|
-
return combined;
|
|
1858
|
-
}
|
|
1859
|
-
bytesToBase64(bytes) {
|
|
1860
|
-
const BufferRef = globalThis.Buffer;
|
|
1861
|
-
if (BufferRef) return BufferRef.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
|
1862
|
-
let binary = "";
|
|
1863
|
-
const chunk = 32768;
|
|
1864
|
-
for (let i = 0; i < bytes.length; i += chunk) binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
1865
|
-
return btoa(binary);
|
|
1866
|
-
}
|
|
1867
|
-
};
|
|
1868
|
-
|
|
1869
|
-
//#endregion
|
|
1870
|
-
//#region src/http/producer-header-parser.ts
|
|
1871
|
-
const MAX_SAFE_PRODUCER_INT = Number.MAX_SAFE_INTEGER;
|
|
1872
|
-
const NON_NEGATIVE_INT_RE = /^(0|[1-9]\d*)$/;
|
|
1873
|
-
var ProducerHeaderParser = class {
|
|
1874
|
-
parse(request) {
|
|
1875
|
-
const id = request.headers.get("producer-id");
|
|
1876
|
-
const epoch = request.headers.get("producer-epoch");
|
|
1877
|
-
const seq = request.headers.get("producer-seq");
|
|
1878
|
-
const present = [
|
|
1879
|
-
id,
|
|
1880
|
-
epoch,
|
|
1881
|
-
seq
|
|
1882
|
-
].filter((v) => v !== null).length;
|
|
1883
|
-
if (present === 0) return { kind: "absent" };
|
|
1884
|
-
if (present !== 3) return { kind: "invalid" };
|
|
1885
|
-
if (id.length === 0) return { kind: "invalid" };
|
|
1886
|
-
const parsedEpoch = this.parseInt(epoch);
|
|
1887
|
-
const parsedSeq = this.parseInt(seq);
|
|
1888
|
-
if (parsedEpoch === null || parsedSeq === null) return { kind: "invalid" };
|
|
1889
|
-
return {
|
|
1890
|
-
kind: "ok",
|
|
1891
|
-
producer: {
|
|
1892
|
-
producerId: id,
|
|
1893
|
-
producerEpoch: parsedEpoch,
|
|
1894
|
-
producerSeq: parsedSeq
|
|
1895
|
-
}
|
|
1896
|
-
};
|
|
1897
|
-
}
|
|
1898
|
-
parseInt(raw) {
|
|
1899
|
-
if (!NON_NEGATIVE_INT_RE.test(raw)) return null;
|
|
1900
|
-
const n = Number(raw);
|
|
1901
|
-
if (!Number.isFinite(n) || n > MAX_SAFE_PRODUCER_INT) return null;
|
|
1902
|
-
return n;
|
|
1903
|
-
}
|
|
1904
|
-
};
|
|
1905
|
-
|
|
1906
|
-
//#endregion
|
|
1907
|
-
//#region src/http/read-query-parser.ts
|
|
1908
|
-
var ReadQueryParser = class {
|
|
1909
|
-
constructor(isValidOffset$1) {
|
|
1910
|
-
this.isValidOffset = isValidOffset$1;
|
|
1911
|
-
}
|
|
1912
|
-
parse(url) {
|
|
1913
|
-
const offset = url.searchParams.get("offset") ?? void 0;
|
|
1914
|
-
const liveParam = url.searchParams.get("live");
|
|
1915
|
-
const cursor = url.searchParams.get("cursor") ?? void 0;
|
|
1916
|
-
const live = liveParam === "long-poll" || liveParam === "sse" ? liveParam : void 0;
|
|
1917
|
-
if (offset !== void 0 && offset !== "-1" && offset !== "now" && !this.isValidOffset(offset)) return {
|
|
1918
|
-
ok: false,
|
|
1919
|
-
response: new Response("Invalid offset format", { status: 400 })
|
|
1920
|
-
};
|
|
1921
|
-
return {
|
|
1922
|
-
ok: true,
|
|
1923
|
-
offset,
|
|
1924
|
-
live,
|
|
1925
|
-
cursor
|
|
1926
|
-
};
|
|
1927
|
-
}
|
|
1928
|
-
};
|
|
1929
|
-
|
|
1930
18
|
//#endregion
|
|
1931
|
-
//#region src/
|
|
1932
|
-
var
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
19
|
+
//#region src/storage/memory/streams.ts
|
|
20
|
+
var streams_exports = /* @__PURE__ */ __exportAll({
|
|
21
|
+
layer: () => layer,
|
|
22
|
+
layerProtocol: () => layerProtocol
|
|
23
|
+
});
|
|
24
|
+
/** Generic reader and writer over memory storage, for protocol tools. */
|
|
25
|
+
const layerProtocol = (options = {}) => layer$2(options).pipe(Layer.provideMerge(layer$1(options)));
|
|
26
|
+
function layer(group, options = {}) {
|
|
27
|
+
const storage = layer$1(options);
|
|
28
|
+
const protocol = layer$2(options).pipe(Layer.provideMerge(storage));
|
|
29
|
+
return bind(protocol, group).pipe(Layer.provideMerge(storage));
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/toolkit/durable-state.ts
|
|
33
|
+
var durable_state_exports = /* @__PURE__ */ __exportAll({
|
|
34
|
+
changes: () => changes,
|
|
35
|
+
remove: () => remove,
|
|
36
|
+
upsert: () => upsert
|
|
37
|
+
});
|
|
38
|
+
const operations = Data.taggedEnum();
|
|
39
|
+
/** Describe an upsert into a collection. The key is read from the value. */
|
|
40
|
+
const upsert = (type, value, options = {}) => operations.Upsert({
|
|
41
|
+
type,
|
|
42
|
+
value,
|
|
43
|
+
...options
|
|
44
|
+
});
|
|
45
|
+
/** Describe a delete from a collection by key. An `oldValue` is written as `old_value`. */
|
|
46
|
+
const remove = (type, key, options = {}) => operations.Delete({
|
|
47
|
+
type,
|
|
48
|
+
key,
|
|
49
|
+
...options
|
|
50
|
+
});
|
|
51
|
+
/** Reject keys that Durable State clients cannot address. */
|
|
52
|
+
const checkKey = (type, source, raw) => {
|
|
53
|
+
if (raw === null || raw === void 0 || raw === "") throw new TypeError(`Invalid state key for type "${type}": ${source} must not be null, undefined, or empty`);
|
|
54
|
+
return String(raw);
|
|
55
|
+
};
|
|
56
|
+
/** Read the key field of a value. `StateKey` limits the field to strings and numbers. */
|
|
57
|
+
const readKey = (type, field, value) => checkKey(type, `field "${String(field)}"`, String(value[field] ?? ""));
|
|
58
|
+
function changes(address, options, entries) {
|
|
59
|
+
const { offset } = options;
|
|
60
|
+
return entries.map((entry, index) => {
|
|
61
|
+
const collection = Object.hasOwn(address.collections, entry.type) ? address.collections[entry.type] : void 0;
|
|
62
|
+
if (collection === void 0) throw new TypeError(`Unknown state collection "${entry.type}"`);
|
|
63
|
+
const override = entry.headers ?? {};
|
|
64
|
+
const txid = override.txid ?? (offset === void 0 ? void 0 : `${offset}:${index}`);
|
|
65
|
+
const headers = {};
|
|
66
|
+
if (offset !== void 0) headers.offset = offset;
|
|
67
|
+
if (txid !== void 0) headers.txid = txid;
|
|
68
|
+
if (override.timestamp !== void 0) headers.timestamp = override.timestamp;
|
|
69
|
+
if (override.from !== void 0) headers.from = override.from;
|
|
70
|
+
if (Predicate.isTagged(entry, "Upsert")) {
|
|
71
|
+
const key = readKey(entry.type, collection.key, entry.value);
|
|
1943
72
|
return {
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
};
|
|
1952
|
-
return {
|
|
1953
|
-
ok: true,
|
|
1954
|
-
data: new Uint8Array(data),
|
|
1955
|
-
byteLength: data.byteLength
|
|
1956
|
-
};
|
|
1957
|
-
}
|
|
1958
|
-
};
|
|
1959
|
-
|
|
1960
|
-
//#endregion
|
|
1961
|
-
//#region src/http/responses.ts
|
|
1962
|
-
/**
|
|
1963
|
-
* Response factory for the HTTP layer.
|
|
1964
|
-
*
|
|
1965
|
-
* Centralizes security headers and the small set of plain text/empty
|
|
1966
|
-
* responses that recur across handlers (400/404/410/413/etc.). Method-
|
|
1967
|
-
* specific result mapping (append producer-state shaping, create conflict
|
|
1968
|
-
* mapping, catch-up ETag responses) stays in the owning service.
|
|
1969
|
-
*/
|
|
1970
|
-
const CACHE_CONTROL_NO_STORE = "no-store";
|
|
1971
|
-
const CACHE_CONTROL_PUBLIC = "public, max-age=60, stale-while-revalidate=300";
|
|
1972
|
-
const CACHE_NO_STORE = CACHE_CONTROL_NO_STORE;
|
|
1973
|
-
const CACHE_REVALIDATE = CACHE_CONTROL_PUBLIC;
|
|
1974
|
-
var HttpResponseFactory = class {
|
|
1975
|
-
secure(response) {
|
|
1976
|
-
return this.withSecurityHeaders(response);
|
|
1977
|
-
}
|
|
1978
|
-
text(message, status, headers) {
|
|
1979
|
-
return new Response(message, {
|
|
1980
|
-
status,
|
|
1981
|
-
headers
|
|
1982
|
-
});
|
|
1983
|
-
}
|
|
1984
|
-
empty(status, headers) {
|
|
1985
|
-
return new Response(null, {
|
|
1986
|
-
status,
|
|
1987
|
-
headers
|
|
1988
|
-
});
|
|
1989
|
-
}
|
|
1990
|
-
badRequest(message) {
|
|
1991
|
-
return new Response(message, { status: 400 });
|
|
1992
|
-
}
|
|
1993
|
-
notFound(message = "Stream not found") {
|
|
1994
|
-
return new Response(message, { status: 404 });
|
|
1995
|
-
}
|
|
1996
|
-
gone(message = "Stream is soft-deleted") {
|
|
1997
|
-
return new Response(message, { status: 410 });
|
|
1998
|
-
}
|
|
1999
|
-
conflict(message, headers) {
|
|
2000
|
-
return new Response(message, {
|
|
2001
|
-
status: 409,
|
|
2002
|
-
headers
|
|
2003
|
-
});
|
|
2004
|
-
}
|
|
2005
|
-
payloadTooLarge() {
|
|
2006
|
-
return new Response("Payload too large", { status: 413 });
|
|
2007
|
-
}
|
|
2008
|
-
invalidJson() {
|
|
2009
|
-
return new Response("Invalid JSON", { status: 400 });
|
|
2010
|
-
}
|
|
2011
|
-
methodNotAllowed() {
|
|
2012
|
-
return new Response("Method not allowed", { status: 405 });
|
|
2013
|
-
}
|
|
2014
|
-
internalError() {
|
|
2015
|
-
return new Response("Internal server error", { status: 500 });
|
|
2016
|
-
}
|
|
2017
|
-
/**
|
|
2018
|
-
* Wrap a response with the standard security headers used across every
|
|
2019
|
-
* route. Existing values for the same header names are preserved.
|
|
2020
|
-
*/
|
|
2021
|
-
withSecurityHeaders(response) {
|
|
2022
|
-
const headers = new Headers(response.headers);
|
|
2023
|
-
if (!headers.has("x-content-type-options")) headers.set("x-content-type-options", "nosniff");
|
|
2024
|
-
if (!headers.has("cross-origin-resource-policy")) headers.set("cross-origin-resource-policy", "cross-origin");
|
|
2025
|
-
return new Response(response.body, {
|
|
2026
|
-
status: response.status,
|
|
2027
|
-
statusText: response.statusText,
|
|
2028
|
-
headers
|
|
2029
|
-
});
|
|
2030
|
-
}
|
|
2031
|
-
};
|
|
2032
|
-
|
|
2033
|
-
//#endregion
|
|
2034
|
-
//#region src/http/sse-event-encoder.ts
|
|
2035
|
-
var SseEventEncoder = class {
|
|
2036
|
-
encoder = new TextEncoder();
|
|
2037
|
-
decoder = new TextDecoder();
|
|
2038
|
-
constructor(bodyCodec) {
|
|
2039
|
-
this.bodyCodec = bodyCodec;
|
|
2040
|
-
}
|
|
2041
|
-
dataEvent(messages, options) {
|
|
2042
|
-
const chunks = [this.encode("event: data\n")];
|
|
2043
|
-
if (options.useBase64) {
|
|
2044
|
-
const combined = this.bodyCodec.concatBytes(messages);
|
|
2045
|
-
chunks.push(this.encode(`data:${this.bodyCodec.bytesToBase64(combined)}\n`));
|
|
2046
|
-
} else if (options.isJson) {
|
|
2047
|
-
const items = messages.map((msg) => this.decoder.decode(msg.data));
|
|
2048
|
-
chunks.push(this.encode("data:[\n"));
|
|
2049
|
-
for (let i = 0; i < items.length; i++) {
|
|
2050
|
-
const suffix = i < items.length - 1 ? "," : "";
|
|
2051
|
-
chunks.push(this.encode(`data:${items[i]}${suffix}\n`));
|
|
2052
|
-
}
|
|
2053
|
-
chunks.push(this.encode("data:]\n"));
|
|
2054
|
-
} else {
|
|
2055
|
-
const text = messages.map((msg) => this.decoder.decode(msg.data)).join("");
|
|
2056
|
-
for (const line of text.split(/\r\n|\r|\n/)) chunks.push(this.encode(`data:${line}\n`));
|
|
2057
|
-
}
|
|
2058
|
-
chunks.push(this.encode("\n"));
|
|
2059
|
-
return chunks;
|
|
2060
|
-
}
|
|
2061
|
-
controlEvent(data) {
|
|
2062
|
-
return this.encode(`event: control\ndata:${JSON.stringify(data)}\n\n`);
|
|
2063
|
-
}
|
|
2064
|
-
encode(value) {
|
|
2065
|
-
return this.encoder.encode(value);
|
|
2066
|
-
}
|
|
2067
|
-
};
|
|
2068
|
-
|
|
2069
|
-
//#endregion
|
|
2070
|
-
//#region src/http/stream-path-service.ts
|
|
2071
|
-
var StreamPathService = class {
|
|
2072
|
-
constructor(pathPrefix) {
|
|
2073
|
-
this.pathPrefix = pathPrefix;
|
|
2074
|
-
}
|
|
2075
|
-
requiredPathPattern() {
|
|
2076
|
-
return `${this.prefixWithSlash()}{path}`;
|
|
2077
|
-
}
|
|
2078
|
-
strip(pathname) {
|
|
2079
|
-
const regex = new RegExp(`^${this.escapeRegex(this.prefixWithSlash())}`);
|
|
2080
|
-
return pathname.replace(regex, "");
|
|
2081
|
-
}
|
|
2082
|
-
canonicalizeForkSource(header) {
|
|
2083
|
-
return this.strip(header);
|
|
2084
|
-
}
|
|
2085
|
-
prefixWithSlash() {
|
|
2086
|
-
return this.pathPrefix.endsWith("/") ? this.pathPrefix : `${this.pathPrefix}/`;
|
|
2087
|
-
}
|
|
2088
|
-
escapeRegex(value) {
|
|
2089
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2090
|
-
}
|
|
2091
|
-
};
|
|
2092
|
-
|
|
2093
|
-
//#endregion
|
|
2094
|
-
//#region src/http/services/append-http-service.ts
|
|
2095
|
-
var AppendHttpService = class {
|
|
2096
|
-
constructor(deps) {
|
|
2097
|
-
this.deps = deps;
|
|
2098
|
-
}
|
|
2099
|
-
async execute(ctx) {
|
|
2100
|
-
const parsed = this.parseHeaders(ctx.request);
|
|
2101
|
-
if (!parsed.ok) return parsed.response;
|
|
2102
|
-
const body = await this.readAndValidateBody(ctx.request, parsed.contentType, parsed.wantClose);
|
|
2103
|
-
if (!body.ok) return body.response;
|
|
2104
|
-
const result = await ctx.stream.append({
|
|
2105
|
-
data: body.data,
|
|
2106
|
-
contentType: parsed.contentType ?? "application/octet-stream",
|
|
2107
|
-
seq: parsed.seq,
|
|
2108
|
-
producer: parsed.producerHeaders.kind === "ok" ? parsed.producerHeaders.producer : void 0,
|
|
2109
|
-
close: parsed.wantClose,
|
|
2110
|
-
expectedOffset: parsed.expectedOffset
|
|
2111
|
-
});
|
|
2112
|
-
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
2113
|
-
return this.toResponse(result, parsed.producerHeaders, body.isEmpty);
|
|
2114
|
-
}
|
|
2115
|
-
parseHeaders(request) {
|
|
2116
|
-
const producerHeaders = this.deps.producerHeaders.parse(request);
|
|
2117
|
-
if (producerHeaders.kind === "invalid") return {
|
|
2118
|
-
ok: false,
|
|
2119
|
-
response: this.deps.responses.badRequest("Invalid producer headers")
|
|
2120
|
-
};
|
|
2121
|
-
const expectedOffset = request.headers.get("stream-expected-offset") ?? void 0;
|
|
2122
|
-
if (expectedOffset !== void 0 && !this.deps.isValidOffset(expectedOffset)) return {
|
|
2123
|
-
ok: false,
|
|
2124
|
-
response: this.deps.responses.badRequest("Invalid expected offset")
|
|
2125
|
-
};
|
|
2126
|
-
return {
|
|
2127
|
-
ok: true,
|
|
2128
|
-
contentType: request.headers.get("content-type"),
|
|
2129
|
-
seq: request.headers.get("stream-seq") ?? void 0,
|
|
2130
|
-
wantClose: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
2131
|
-
expectedOffset,
|
|
2132
|
-
producerHeaders
|
|
2133
|
-
};
|
|
2134
|
-
}
|
|
2135
|
-
async readAndValidateBody(request, contentType, wantClose) {
|
|
2136
|
-
const body = await this.deps.bodyReader.read(request);
|
|
2137
|
-
if (!body.ok) return body;
|
|
2138
|
-
const isEmpty = body.byteLength === 0;
|
|
2139
|
-
if (isEmpty && !wantClose) return {
|
|
2140
|
-
ok: false,
|
|
2141
|
-
response: this.deps.responses.badRequest("Empty body not allowed")
|
|
2142
|
-
};
|
|
2143
|
-
if (!contentType && !isEmpty) return {
|
|
2144
|
-
ok: false,
|
|
2145
|
-
response: this.deps.responses.badRequest("Content-Type required")
|
|
2146
|
-
};
|
|
2147
|
-
if (!isEmpty && contentType?.toLowerCase().startsWith("application/json")) try {
|
|
2148
|
-
const parsed = JSON.parse(new TextDecoder().decode(body.data));
|
|
2149
|
-
if (Array.isArray(parsed) && parsed.length === 0) return {
|
|
2150
|
-
ok: false,
|
|
2151
|
-
response: this.deps.responses.badRequest("Empty arrays not allowed")
|
|
2152
|
-
};
|
|
2153
|
-
} catch (error) {
|
|
2154
|
-
if (error instanceof SyntaxError) return {
|
|
2155
|
-
ok: false,
|
|
2156
|
-
response: this.deps.responses.invalidJson()
|
|
73
|
+
type: entry.type,
|
|
74
|
+
key,
|
|
75
|
+
value: entry.value,
|
|
76
|
+
headers: {
|
|
77
|
+
operation: "upsert",
|
|
78
|
+
...headers
|
|
79
|
+
}
|
|
2157
80
|
};
|
|
2158
|
-
throw error;
|
|
2159
81
|
}
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
switch (result.status) {
|
|
2168
|
-
case "not-found": return this.deps.responses.notFound();
|
|
2169
|
-
case "gone": return this.deps.responses.gone();
|
|
2170
|
-
case "conflict": {
|
|
2171
|
-
if (result.conflictReason === "closed") return this.deps.responses.empty(409, {
|
|
2172
|
-
"stream-closed": "true",
|
|
2173
|
-
"stream-next-offset": result.offset
|
|
2174
|
-
});
|
|
2175
|
-
if (result.conflictReason === "expected-offset") return this.deps.responses.conflict("Expected offset mismatch", { "stream-next-offset": result.offset });
|
|
2176
|
-
return this.deps.responses.conflict(result.conflictReason === "content-type" ? "Content-Type mismatch" : "Sequence conflict");
|
|
82
|
+
const key = checkKey(entry.type, "key", entry.key);
|
|
83
|
+
return entry.oldValue === void 0 ? {
|
|
84
|
+
type: entry.type,
|
|
85
|
+
key,
|
|
86
|
+
headers: {
|
|
87
|
+
operation: "delete",
|
|
88
|
+
...headers
|
|
2177
89
|
}
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
case "duplicate": return this.deps.responses.empty(204, {
|
|
2186
|
-
"stream-next-offset": result.offset,
|
|
2187
|
-
"producer-epoch": String(result.producerEpoch),
|
|
2188
|
-
"producer-seq": String(result.producerSeq),
|
|
2189
|
-
...result.closed ? { "stream-closed": "true" } : {}
|
|
2190
|
-
});
|
|
2191
|
-
case "appended": {
|
|
2192
|
-
const headers = {
|
|
2193
|
-
"stream-next-offset": result.offset,
|
|
2194
|
-
...result.closed ? { "stream-closed": "true" } : {}
|
|
2195
|
-
};
|
|
2196
|
-
if (result.producerEpoch !== void 0) headers["producer-epoch"] = String(result.producerEpoch);
|
|
2197
|
-
if (result.producerSeq !== void 0) headers["producer-seq"] = String(result.producerSeq);
|
|
2198
|
-
return this.deps.responses.empty(producerHeaders.kind === "ok" && !isEmpty ? 200 : 204, headers);
|
|
2199
|
-
}
|
|
2200
|
-
}
|
|
2201
|
-
}
|
|
2202
|
-
};
|
|
2203
|
-
|
|
2204
|
-
//#endregion
|
|
2205
|
-
//#region src/http/services/create-http-service.ts
|
|
2206
|
-
var CreateHttpService = class {
|
|
2207
|
-
constructor(deps) {
|
|
2208
|
-
this.deps = deps;
|
|
2209
|
-
}
|
|
2210
|
-
async execute(ctx) {
|
|
2211
|
-
const parsed = this.parseHeaders(ctx.request);
|
|
2212
|
-
if (!parsed.ok) return parsed.response;
|
|
2213
|
-
const body = await this.deps.bodyReader.read(ctx.request);
|
|
2214
|
-
if (!body.ok) return body.response;
|
|
2215
|
-
const normalized = this.normalizeInitialData(body.data, parsed.contentType);
|
|
2216
|
-
if (!normalized.ok) return normalized.response;
|
|
2217
|
-
const result = await this.deps.protocol.create(ctx.streamId, {
|
|
2218
|
-
contentType: parsed.contentType,
|
|
2219
|
-
ttlSeconds: parsed.ttlSeconds,
|
|
2220
|
-
expiresAt: parsed.expiresAt,
|
|
2221
|
-
initialData: normalized.initialData,
|
|
2222
|
-
closed: parsed.wantClosed,
|
|
2223
|
-
forkedFrom: parsed.forkedFromStreamId,
|
|
2224
|
-
forkOffset: parsed.forkOffset,
|
|
2225
|
-
forkSubOffset: parsed.forkSubOffset
|
|
2226
|
-
});
|
|
2227
|
-
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
2228
|
-
return this.toResponse(result, ctx.request.url);
|
|
2229
|
-
}
|
|
2230
|
-
parseHeaders(request) {
|
|
2231
|
-
const rawContentType = request.headers.get("content-type");
|
|
2232
|
-
const ttlHeader = request.headers.get("stream-ttl");
|
|
2233
|
-
const expiresAtHeader = request.headers.get("stream-expires-at");
|
|
2234
|
-
const forkedFromHeader = request.headers.get("stream-forked-from");
|
|
2235
|
-
const forkOffsetHeader = request.headers.get("stream-fork-offset");
|
|
2236
|
-
const forkSubOffsetHeader = request.headers.get("stream-fork-sub-offset");
|
|
2237
|
-
if (ttlHeader && !/^(0|[1-9]\d*)$/.test(ttlHeader)) return {
|
|
2238
|
-
ok: false,
|
|
2239
|
-
response: this.deps.responses.badRequest("Invalid Stream-TTL format")
|
|
2240
|
-
};
|
|
2241
|
-
if (ttlHeader && expiresAtHeader) return {
|
|
2242
|
-
ok: false,
|
|
2243
|
-
response: this.deps.responses.badRequest("Cannot specify both Stream-TTL and Stream-Expires-At")
|
|
2244
|
-
};
|
|
2245
|
-
if (expiresAtHeader && isNaN(new Date(expiresAtHeader).getTime())) return {
|
|
2246
|
-
ok: false,
|
|
2247
|
-
response: this.deps.responses.badRequest("Invalid Stream-Expires-At format")
|
|
2248
|
-
};
|
|
2249
|
-
if (forkOffsetHeader && !forkedFromHeader) return {
|
|
2250
|
-
ok: false,
|
|
2251
|
-
response: this.deps.responses.badRequest("Stream-Fork-Offset requires Stream-Forked-From")
|
|
2252
|
-
};
|
|
2253
|
-
if (forkSubOffsetHeader !== null) {
|
|
2254
|
-
if (!forkedFromHeader) return {
|
|
2255
|
-
ok: false,
|
|
2256
|
-
response: this.deps.responses.badRequest("Stream-Fork-Sub-Offset requires Stream-Forked-From")
|
|
2257
|
-
};
|
|
2258
|
-
if (!/^(0|[1-9]\d*)$/.test(forkSubOffsetHeader)) return {
|
|
2259
|
-
ok: false,
|
|
2260
|
-
response: this.deps.responses.badRequest("Invalid Stream-Fork-Sub-Offset format")
|
|
2261
|
-
};
|
|
2262
|
-
if (parseInt(forkSubOffsetHeader, 10) > 0 && !forkOffsetHeader) return {
|
|
2263
|
-
ok: false,
|
|
2264
|
-
response: this.deps.responses.badRequest("Stream-Fork-Sub-Offset greater than zero requires Stream-Fork-Offset")
|
|
2265
|
-
};
|
|
2266
|
-
}
|
|
2267
|
-
const isFork = !!forkedFromHeader;
|
|
2268
|
-
return {
|
|
2269
|
-
ok: true,
|
|
2270
|
-
contentType: rawContentType ?? (isFork ? void 0 : "application/octet-stream"),
|
|
2271
|
-
ttlSeconds: ttlHeader ? parseInt(ttlHeader, 10) : void 0,
|
|
2272
|
-
expiresAt: expiresAtHeader ?? void 0,
|
|
2273
|
-
wantClosed: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
2274
|
-
forkedFromStreamId: forkedFromHeader ? this.deps.path.canonicalizeForkSource(forkedFromHeader) : void 0,
|
|
2275
|
-
forkOffset: forkOffsetHeader ?? void 0,
|
|
2276
|
-
forkSubOffset: forkSubOffsetHeader !== null ? parseInt(forkSubOffsetHeader, 10) : void 0
|
|
2277
|
-
};
|
|
2278
|
-
}
|
|
2279
|
-
normalizeInitialData(data, contentType) {
|
|
2280
|
-
let effectiveInitialData = data.byteLength > 0 ? data : void 0;
|
|
2281
|
-
if (effectiveInitialData && contentType?.toLowerCase().startsWith("application/json")) try {
|
|
2282
|
-
const parsed = JSON.parse(new TextDecoder().decode(effectiveInitialData));
|
|
2283
|
-
if (Array.isArray(parsed) && parsed.length === 0) effectiveInitialData = void 0;
|
|
2284
|
-
} catch (error) {
|
|
2285
|
-
if (error instanceof SyntaxError) return {
|
|
2286
|
-
ok: false,
|
|
2287
|
-
response: this.deps.responses.invalidJson()
|
|
2288
|
-
};
|
|
2289
|
-
throw error;
|
|
2290
|
-
}
|
|
2291
|
-
return {
|
|
2292
|
-
ok: true,
|
|
2293
|
-
initialData: effectiveInitialData
|
|
2294
|
-
};
|
|
2295
|
-
}
|
|
2296
|
-
toResponse(result, location) {
|
|
2297
|
-
if (result.status === "not-found") return this.deps.responses.notFound(result.errorMessage ?? "Source stream not found");
|
|
2298
|
-
if (result.status === "bad-request") return this.deps.responses.badRequest(result.errorMessage ?? "Invalid fork parameters");
|
|
2299
|
-
if (result.status === "conflict") return this.deps.responses.conflict(result.errorMessage ?? "Stream exists with different configuration");
|
|
2300
|
-
const success = result;
|
|
2301
|
-
const status = success.status === "created" ? 201 : 200;
|
|
2302
|
-
return this.deps.responses.empty(status, {
|
|
2303
|
-
"content-type": success.contentType,
|
|
2304
|
-
"stream-next-offset": success.nextOffset,
|
|
2305
|
-
...status === 201 ? { location } : {},
|
|
2306
|
-
...success.closed ? { "stream-closed": "true" } : {}
|
|
2307
|
-
});
|
|
2308
|
-
}
|
|
2309
|
-
};
|
|
2310
|
-
|
|
2311
|
-
//#endregion
|
|
2312
|
-
//#region src/http/services/delete-http-service.ts
|
|
2313
|
-
var DeleteHttpService = class {
|
|
2314
|
-
constructor(deps) {
|
|
2315
|
-
this.deps = deps;
|
|
2316
|
-
}
|
|
2317
|
-
async execute(ctx) {
|
|
2318
|
-
const result = await ctx.stream.delete();
|
|
2319
|
-
if (result.status === "not-found") return this.deps.responses.notFound();
|
|
2320
|
-
if (result.status === "gone") return this.deps.responses.gone();
|
|
2321
|
-
return this.deps.responses.empty(204);
|
|
2322
|
-
}
|
|
2323
|
-
};
|
|
2324
|
-
|
|
2325
|
-
//#endregion
|
|
2326
|
-
//#region src/http/services/long-poll-http-service.ts
|
|
2327
|
-
var LongPollHttpService = class {
|
|
2328
|
-
constructor(deps) {
|
|
2329
|
-
this.deps = deps;
|
|
2330
|
-
}
|
|
2331
|
-
async execute(stream, offset, cursor) {
|
|
2332
|
-
const result = await stream.readLive({
|
|
2333
|
-
offset,
|
|
2334
|
-
mode: "long-poll",
|
|
2335
|
-
cursor
|
|
2336
|
-
});
|
|
2337
|
-
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
2338
|
-
if (result.status === "not-found") return this.deps.responses.notFound();
|
|
2339
|
-
if (result.status === "gone") return this.deps.responses.gone();
|
|
2340
|
-
if (result.messages.length === 0) return this.toNoContentResponse(result);
|
|
2341
|
-
const metadata = await stream.metadata();
|
|
2342
|
-
if (metadata.status === "not-found") return this.deps.responses.notFound();
|
|
2343
|
-
if (metadata.status === "gone") return this.deps.responses.gone();
|
|
2344
|
-
return new Response(this.deps.bodyCodec.encodeHttpBody(result.messages, metadata.contentType), { headers: {
|
|
2345
|
-
"content-type": metadata.contentType,
|
|
2346
|
-
"stream-next-offset": result.nextOffset,
|
|
2347
|
-
"stream-up-to-date": "true",
|
|
2348
|
-
...result.closed ? {} : { "stream-cursor": result.cursor },
|
|
2349
|
-
...result.closed ? { "stream-closed": "true" } : {}
|
|
2350
|
-
} });
|
|
2351
|
-
}
|
|
2352
|
-
toNoContentResponse(result) {
|
|
2353
|
-
return this.deps.responses.empty(204, {
|
|
2354
|
-
"stream-next-offset": result.nextOffset,
|
|
2355
|
-
"stream-up-to-date": "true",
|
|
2356
|
-
...result.closed ? {} : { "stream-cursor": result.cursor },
|
|
2357
|
-
...result.closed ? { "stream-closed": "true" } : {}
|
|
2358
|
-
});
|
|
2359
|
-
}
|
|
2360
|
-
};
|
|
2361
|
-
|
|
2362
|
-
//#endregion
|
|
2363
|
-
//#region src/http/services/metadata-http-service.ts
|
|
2364
|
-
var MetadataHttpService = class {
|
|
2365
|
-
constructor(deps) {
|
|
2366
|
-
this.deps = deps;
|
|
2367
|
-
}
|
|
2368
|
-
async execute(ctx) {
|
|
2369
|
-
const result = await ctx.stream.metadata();
|
|
2370
|
-
if (result.status === "not-found") return this.deps.responses.notFound();
|
|
2371
|
-
if (result.status === "gone") return this.deps.responses.gone();
|
|
2372
|
-
return this.deps.responses.empty(200, {
|
|
2373
|
-
"content-type": result.contentType,
|
|
2374
|
-
"stream-next-offset": result.nextOffset,
|
|
2375
|
-
...result.ttlSeconds ? { "stream-ttl": String(result.ttlSeconds) } : {},
|
|
2376
|
-
...result.expiresAt ? { "stream-expires-at": result.expiresAt } : {},
|
|
2377
|
-
...result.closed ? { "stream-closed": "true" } : {},
|
|
2378
|
-
"cache-control": CACHE_NO_STORE
|
|
2379
|
-
});
|
|
2380
|
-
}
|
|
2381
|
-
};
|
|
2382
|
-
|
|
2383
|
-
//#endregion
|
|
2384
|
-
//#region src/http/services/read-http-service.ts
|
|
2385
|
-
var ReadHttpService = class {
|
|
2386
|
-
constructor(deps) {
|
|
2387
|
-
this.deps = deps;
|
|
2388
|
-
}
|
|
2389
|
-
async execute(ctx) {
|
|
2390
|
-
const query = this.deps.readQuery.parse(ctx.url);
|
|
2391
|
-
if (!query.ok) return query.response;
|
|
2392
|
-
let effectiveOffset = query.offset;
|
|
2393
|
-
if (query.offset === "now") {
|
|
2394
|
-
const now = await this.resolveNowOffset(ctx, query.live);
|
|
2395
|
-
if (!now.ok) return now.response;
|
|
2396
|
-
effectiveOffset = now.offset;
|
|
2397
|
-
if (now.response) return now.response;
|
|
2398
|
-
}
|
|
2399
|
-
if (query.live) {
|
|
2400
|
-
if (!effectiveOffset) return this.deps.responses.badRequest("offset required for live modes");
|
|
2401
|
-
return query.live === "sse" ? this.deps.sse.execute(ctx.stream, effectiveOffset, query.cursor) : this.deps.longPoll.execute(ctx.stream, effectiveOffset, query.cursor);
|
|
2402
|
-
}
|
|
2403
|
-
return this.handleCatchUp(ctx, effectiveOffset, query.offset ?? "-1");
|
|
2404
|
-
}
|
|
2405
|
-
async resolveNowOffset(ctx, live) {
|
|
2406
|
-
const meta = await ctx.stream.metadata();
|
|
2407
|
-
if (meta.status === "not-found") return {
|
|
2408
|
-
ok: false,
|
|
2409
|
-
response: this.deps.responses.notFound()
|
|
2410
|
-
};
|
|
2411
|
-
if (meta.status === "gone") return {
|
|
2412
|
-
ok: false,
|
|
2413
|
-
response: this.deps.responses.gone()
|
|
2414
|
-
};
|
|
2415
|
-
const offset = meta.nextOffset;
|
|
2416
|
-
if (!live) {
|
|
2417
|
-
const contentType = meta.contentType;
|
|
2418
|
-
return {
|
|
2419
|
-
ok: true,
|
|
2420
|
-
offset,
|
|
2421
|
-
response: new Response(this.deps.bodyCodec.emptyBodyForContentType(contentType), { headers: {
|
|
2422
|
-
"content-type": contentType,
|
|
2423
|
-
"stream-next-offset": offset,
|
|
2424
|
-
"stream-up-to-date": "true",
|
|
2425
|
-
...meta.closed ? { "stream-closed": "true" } : {},
|
|
2426
|
-
"cache-control": CACHE_NO_STORE
|
|
2427
|
-
} })
|
|
2428
|
-
};
|
|
2429
|
-
}
|
|
2430
|
-
return {
|
|
2431
|
-
ok: true,
|
|
2432
|
-
offset
|
|
2433
|
-
};
|
|
2434
|
-
}
|
|
2435
|
-
async handleCatchUp(ctx, offset, startOffset) {
|
|
2436
|
-
const result = await ctx.stream.read({ offset });
|
|
2437
|
-
if (result.status === "not-found") return this.deps.responses.notFound();
|
|
2438
|
-
if (result.status === "gone") return this.deps.responses.gone();
|
|
2439
|
-
const etag = this.deps.etags.forCatchUp(ctx.url.pathname, startOffset, result.nextOffset, result.closed === true);
|
|
2440
|
-
if (ctx.request.headers.get("if-none-match") === etag) return this.deps.responses.empty(304, {
|
|
2441
|
-
etag,
|
|
2442
|
-
"cache-control": CACHE_REVALIDATE
|
|
2443
|
-
});
|
|
2444
|
-
const metadata = await ctx.stream.metadata();
|
|
2445
|
-
if (metadata.status === "not-found") return this.deps.responses.notFound();
|
|
2446
|
-
if (metadata.status === "gone") return this.deps.responses.gone();
|
|
2447
|
-
return new Response(this.deps.bodyCodec.encodeHttpBody(result.messages, metadata.contentType), { headers: {
|
|
2448
|
-
"content-type": metadata.contentType,
|
|
2449
|
-
"stream-next-offset": result.nextOffset,
|
|
2450
|
-
...result.upToDate ? { "stream-up-to-date": "true" } : {},
|
|
2451
|
-
...result.closed ? { "stream-closed": "true" } : {},
|
|
2452
|
-
etag,
|
|
2453
|
-
"cache-control": CACHE_REVALIDATE
|
|
2454
|
-
} });
|
|
2455
|
-
}
|
|
2456
|
-
};
|
|
2457
|
-
|
|
2458
|
-
//#endregion
|
|
2459
|
-
//#region src/http/services/sse-http-service.ts
|
|
2460
|
-
const CONNECTION_TIMEOUT_MS = 6e4;
|
|
2461
|
-
var SseHttpService = class {
|
|
2462
|
-
constructor(deps) {
|
|
2463
|
-
this.deps = deps;
|
|
2464
|
-
}
|
|
2465
|
-
async execute(stream, offset, cursor) {
|
|
2466
|
-
const metadata = await stream.metadata();
|
|
2467
|
-
if (metadata.status === "not-found") return this.deps.responses.notFound();
|
|
2468
|
-
if (metadata.status === "gone") return this.deps.responses.gone();
|
|
2469
|
-
const contentTypeLower = metadata.contentType.toLowerCase();
|
|
2470
|
-
const encoding = {
|
|
2471
|
-
isText: contentTypeLower.startsWith("text/"),
|
|
2472
|
-
isJson: contentTypeLower.startsWith("application/json"),
|
|
2473
|
-
useBase64: false
|
|
2474
|
-
};
|
|
2475
|
-
encoding.useBase64 = !encoding.isText && !encoding.isJson;
|
|
2476
|
-
const body = this.createStream(stream, offset, cursor, metadata.nextOffset, metadata.closed === true, encoding);
|
|
2477
|
-
return new Response(body, { headers: {
|
|
2478
|
-
"content-type": "text/event-stream",
|
|
2479
|
-
"cache-control": "no-cache",
|
|
2480
|
-
connection: "keep-alive",
|
|
2481
|
-
...encoding.useBase64 ? { "stream-sse-data-encoding": "base64" } : {}
|
|
2482
|
-
} });
|
|
2483
|
-
}
|
|
2484
|
-
createStream(stream, offset, cursor, metadataNextOffset, metadataClosed, encoding) {
|
|
2485
|
-
let currentOffset = offset;
|
|
2486
|
-
let currentCursor = cursor;
|
|
2487
|
-
const connectionStartTime = Date.now();
|
|
2488
|
-
const sseEvents = this.deps.sseEvents;
|
|
2489
|
-
const clock = this.deps.clock;
|
|
2490
|
-
let cancelActiveRead;
|
|
2491
|
-
return new ReadableStream({
|
|
2492
|
-
start: async (controller) => {
|
|
2493
|
-
const liveReadAbortController = new AbortController();
|
|
2494
|
-
let inactive = false;
|
|
2495
|
-
const shouldStop = () => inactive || liveReadAbortController.signal.aborted;
|
|
2496
|
-
const stop = () => {
|
|
2497
|
-
inactive = true;
|
|
2498
|
-
liveReadAbortController.abort();
|
|
2499
|
-
};
|
|
2500
|
-
cancelActiveRead = stop;
|
|
2501
|
-
const close = () => {
|
|
2502
|
-
if (inactive) return;
|
|
2503
|
-
inactive = true;
|
|
2504
|
-
liveReadAbortController.abort();
|
|
2505
|
-
try {
|
|
2506
|
-
controller.close();
|
|
2507
|
-
} catch {}
|
|
2508
|
-
};
|
|
2509
|
-
const enqueue = (chunk) => {
|
|
2510
|
-
if (shouldStop()) return false;
|
|
2511
|
-
try {
|
|
2512
|
-
controller.enqueue(chunk);
|
|
2513
|
-
return true;
|
|
2514
|
-
} catch {
|
|
2515
|
-
stop();
|
|
2516
|
-
return false;
|
|
2517
|
-
}
|
|
2518
|
-
};
|
|
2519
|
-
const writeChunks = (chunks, enabled) => {
|
|
2520
|
-
if (!enabled) return true;
|
|
2521
|
-
for (const chunk of chunks) if (!enqueue(chunk)) return false;
|
|
2522
|
-
return true;
|
|
2523
|
-
};
|
|
2524
|
-
try {
|
|
2525
|
-
let initialNextOffset;
|
|
2526
|
-
let initialUpToDate;
|
|
2527
|
-
let initialClosed = false;
|
|
2528
|
-
if (currentOffset === "now") {
|
|
2529
|
-
initialNextOffset = metadataNextOffset;
|
|
2530
|
-
initialUpToDate = true;
|
|
2531
|
-
initialClosed = metadataClosed;
|
|
2532
|
-
} else {
|
|
2533
|
-
const initialResult = await stream.read({ offset: currentOffset === "-1" ? void 0 : currentOffset });
|
|
2534
|
-
if (shouldStop()) return;
|
|
2535
|
-
if (initialResult.status === "not-found" || initialResult.status === "gone") {
|
|
2536
|
-
close();
|
|
2537
|
-
return;
|
|
2538
|
-
}
|
|
2539
|
-
if (!writeChunks(sseEvents.dataEvent(initialResult.messages, encoding), initialResult.messages.length > 0)) return;
|
|
2540
|
-
initialNextOffset = initialResult.nextOffset;
|
|
2541
|
-
initialUpToDate = initialResult.upToDate;
|
|
2542
|
-
initialClosed = initialResult.closed === true;
|
|
2543
|
-
}
|
|
2544
|
-
currentCursor = generateCursor(clock, currentCursor);
|
|
2545
|
-
if (!enqueue(sseEvents.controlEvent(this.buildControlData(initialNextOffset, currentCursor, initialUpToDate, initialClosed)))) return;
|
|
2546
|
-
if (initialClosed) {
|
|
2547
|
-
close();
|
|
2548
|
-
return;
|
|
2549
|
-
}
|
|
2550
|
-
currentOffset = initialNextOffset;
|
|
2551
|
-
while (!shouldStop()) {
|
|
2552
|
-
if (Date.now() - connectionStartTime >= CONNECTION_TIMEOUT_MS) {
|
|
2553
|
-
close();
|
|
2554
|
-
return;
|
|
2555
|
-
}
|
|
2556
|
-
const result = await stream.readLive({
|
|
2557
|
-
offset: currentOffset,
|
|
2558
|
-
mode: "sse",
|
|
2559
|
-
cursor: currentCursor,
|
|
2560
|
-
signal: liveReadAbortController.signal
|
|
2561
|
-
});
|
|
2562
|
-
if (shouldStop()) return;
|
|
2563
|
-
if (result.status === "not-found" || result.status === "gone" || result.status === "not-supported") {
|
|
2564
|
-
close();
|
|
2565
|
-
return;
|
|
2566
|
-
}
|
|
2567
|
-
if (!writeChunks(sseEvents.dataEvent(result.messages, encoding), result.messages.length > 0)) return;
|
|
2568
|
-
if (!enqueue(sseEvents.controlEvent(this.buildControlData(result.nextOffset, result.cursor, result.upToDate, result.closed === true)))) return;
|
|
2569
|
-
currentOffset = result.nextOffset;
|
|
2570
|
-
currentCursor = result.cursor;
|
|
2571
|
-
if (result.closed) {
|
|
2572
|
-
close();
|
|
2573
|
-
return;
|
|
2574
|
-
}
|
|
2575
|
-
if (result.status === "timeout") continue;
|
|
2576
|
-
}
|
|
2577
|
-
} catch (error) {
|
|
2578
|
-
if (!shouldStop()) console.error("SSE stream error:", error);
|
|
2579
|
-
close();
|
|
2580
|
-
}
|
|
2581
|
-
},
|
|
2582
|
-
cancel: () => {
|
|
2583
|
-
cancelActiveRead?.();
|
|
90
|
+
} : {
|
|
91
|
+
type: entry.type,
|
|
92
|
+
key,
|
|
93
|
+
old_value: entry.oldValue,
|
|
94
|
+
headers: {
|
|
95
|
+
operation: "delete",
|
|
96
|
+
...headers
|
|
2584
97
|
}
|
|
2585
|
-
});
|
|
2586
|
-
}
|
|
2587
|
-
buildControlData(nextOffset, cursor, upToDate, closed) {
|
|
2588
|
-
if (closed) return {
|
|
2589
|
-
streamNextOffset: nextOffset,
|
|
2590
|
-
streamClosed: true
|
|
2591
|
-
};
|
|
2592
|
-
return {
|
|
2593
|
-
streamNextOffset: nextOffset,
|
|
2594
|
-
streamCursor: cursor,
|
|
2595
|
-
...upToDate ? { upToDate: true } : {}
|
|
2596
|
-
};
|
|
2597
|
-
}
|
|
2598
|
-
};
|
|
2599
|
-
|
|
2600
|
-
//#endregion
|
|
2601
|
-
//#region src/http.ts
|
|
2602
|
-
function createHttpHandler(options) {
|
|
2603
|
-
return new HttpHandler(options);
|
|
2604
|
-
}
|
|
2605
|
-
var HttpHandler = class {
|
|
2606
|
-
dispatch;
|
|
2607
|
-
constructor(options) {
|
|
2608
|
-
const path = new StreamPathService(options.pathPrefix ?? "/");
|
|
2609
|
-
const responses = new HttpResponseFactory();
|
|
2610
|
-
const bodyReader = new RequestBodyReader(options.maxMessageSize ?? 1024 * 1024, responses);
|
|
2611
|
-
const bodyCodec = new MessageBodyCodec();
|
|
2612
|
-
const producerHeaders = new ProducerHeaderParser();
|
|
2613
|
-
const readQuery = new ReadQueryParser((offset) => options.protocol.isValidOffset(offset));
|
|
2614
|
-
const etags = new EtagBuilder();
|
|
2615
|
-
const sseEvents = new SseEventEncoder(bodyCodec);
|
|
2616
|
-
const longPoll = new LongPollHttpService({
|
|
2617
|
-
responses,
|
|
2618
|
-
bodyCodec
|
|
2619
|
-
});
|
|
2620
|
-
const sse = new SseHttpService({
|
|
2621
|
-
responses,
|
|
2622
|
-
sseEvents,
|
|
2623
|
-
clock: systemClock
|
|
2624
|
-
});
|
|
2625
|
-
this.dispatch = new HttpDispatchService({
|
|
2626
|
-
protocol: options.protocol,
|
|
2627
|
-
path,
|
|
2628
|
-
responses,
|
|
2629
|
-
create: new CreateHttpService({
|
|
2630
|
-
protocol: options.protocol,
|
|
2631
|
-
path,
|
|
2632
|
-
responses,
|
|
2633
|
-
bodyReader
|
|
2634
|
-
}),
|
|
2635
|
-
append: new AppendHttpService({
|
|
2636
|
-
responses,
|
|
2637
|
-
bodyReader,
|
|
2638
|
-
producerHeaders,
|
|
2639
|
-
isValidOffset: (offset) => options.protocol.isValidOffset(offset)
|
|
2640
|
-
}),
|
|
2641
|
-
read: new ReadHttpService({
|
|
2642
|
-
responses,
|
|
2643
|
-
bodyCodec,
|
|
2644
|
-
readQuery,
|
|
2645
|
-
etags,
|
|
2646
|
-
longPoll,
|
|
2647
|
-
sse
|
|
2648
|
-
}),
|
|
2649
|
-
metadata: new MetadataHttpService({ responses }),
|
|
2650
|
-
delete: new DeleteHttpService({ responses })
|
|
2651
|
-
});
|
|
2652
|
-
}
|
|
2653
|
-
async fetch(request) {
|
|
2654
|
-
return this.dispatch.fetch(request);
|
|
2655
|
-
}
|
|
2656
|
-
};
|
|
2657
|
-
|
|
2658
|
-
//#endregion
|
|
2659
|
-
//#region src/http/read-only-dispatch-service.ts
|
|
2660
|
-
var ReadOnlyHttpDispatchService = class {
|
|
2661
|
-
constructor(deps) {
|
|
2662
|
-
this.deps = deps;
|
|
2663
|
-
}
|
|
2664
|
-
async fetch(request) {
|
|
2665
|
-
return this.deps.responses.secure(await this.execute(request));
|
|
2666
|
-
}
|
|
2667
|
-
async execute(request) {
|
|
2668
|
-
const url = new URL(request.url);
|
|
2669
|
-
const streamId = this.deps.path.strip(url.pathname);
|
|
2670
|
-
if (!streamId || streamId === url.pathname) return this.deps.responses.badRequest(`Stream path required: ${this.deps.path.requiredPathPattern()}`);
|
|
2671
|
-
const ctx = {
|
|
2672
|
-
request,
|
|
2673
|
-
url,
|
|
2674
|
-
streamId
|
|
2675
|
-
};
|
|
2676
|
-
try {
|
|
2677
|
-
switch (request.method) {
|
|
2678
|
-
case "GET": return await this.withBoundStream(ctx, (bound) => this.deps.read.execute(bound));
|
|
2679
|
-
case "HEAD": return await this.withBoundStream(ctx, (bound) => this.deps.metadata.execute(bound));
|
|
2680
|
-
default: return this.deps.responses.methodNotAllowed();
|
|
2681
|
-
}
|
|
2682
|
-
} catch (error) {
|
|
2683
|
-
if (isNotSupportedError(error)) return notSupportedResponse(notSupportedFromError(error), this.deps.responses);
|
|
2684
|
-
console.error("Error handling request:", error);
|
|
2685
|
-
return this.deps.responses.internalError();
|
|
2686
|
-
}
|
|
2687
|
-
}
|
|
2688
|
-
async withBoundStream(ctx, fn) {
|
|
2689
|
-
const lookup = await this.deps.protocol.get(ctx.streamId);
|
|
2690
|
-
if (lookup.status === "not-found") return this.deps.responses.notFound();
|
|
2691
|
-
if (lookup.status === "gone") return this.deps.responses.gone();
|
|
2692
|
-
if (isNotSupported(lookup)) return notSupportedResponse(lookup, this.deps.responses);
|
|
2693
|
-
return fn({
|
|
2694
|
-
...ctx,
|
|
2695
|
-
stream: lookup.stream
|
|
2696
|
-
});
|
|
2697
|
-
}
|
|
2698
|
-
};
|
|
2699
|
-
|
|
2700
|
-
//#endregion
|
|
2701
|
-
//#region src/read-only-http.ts
|
|
2702
|
-
function createReadOnlyHttpHandler(options) {
|
|
2703
|
-
return new ReadOnlyHttpHandler(options);
|
|
2704
|
-
}
|
|
2705
|
-
var ReadOnlyHttpHandler = class {
|
|
2706
|
-
dispatch;
|
|
2707
|
-
constructor(options) {
|
|
2708
|
-
const path = new StreamPathService(options.pathPrefix ?? "/");
|
|
2709
|
-
const responses = new HttpResponseFactory();
|
|
2710
|
-
const bodyCodec = new MessageBodyCodec();
|
|
2711
|
-
const readQuery = new ReadQueryParser((offset) => options.protocol.isValidOffset(offset));
|
|
2712
|
-
const etags = new EtagBuilder();
|
|
2713
|
-
const sseEvents = new SseEventEncoder(bodyCodec);
|
|
2714
|
-
const longPoll = new LongPollHttpService({
|
|
2715
|
-
responses,
|
|
2716
|
-
bodyCodec
|
|
2717
|
-
});
|
|
2718
|
-
const sse = new SseHttpService({
|
|
2719
|
-
responses,
|
|
2720
|
-
sseEvents,
|
|
2721
|
-
clock: systemClock
|
|
2722
|
-
});
|
|
2723
|
-
this.dispatch = new ReadOnlyHttpDispatchService({
|
|
2724
|
-
protocol: options.protocol,
|
|
2725
|
-
path,
|
|
2726
|
-
responses,
|
|
2727
|
-
read: new ReadHttpService({
|
|
2728
|
-
responses,
|
|
2729
|
-
bodyCodec,
|
|
2730
|
-
readQuery,
|
|
2731
|
-
etags,
|
|
2732
|
-
longPoll,
|
|
2733
|
-
sse
|
|
2734
|
-
}),
|
|
2735
|
-
metadata: new MetadataHttpService({ responses })
|
|
2736
|
-
});
|
|
2737
|
-
}
|
|
2738
|
-
async fetch(request) {
|
|
2739
|
-
return this.dispatch.fetch(request);
|
|
2740
|
-
}
|
|
2741
|
-
};
|
|
2742
|
-
|
|
2743
|
-
//#endregion
|
|
2744
|
-
//#region src/client/batch-encoding.ts
|
|
2745
|
-
const decoder = new TextDecoder();
|
|
2746
|
-
/**
|
|
2747
|
-
* Real impedance matching: turn a substrate's `StoredMessage[]` into a single
|
|
2748
|
-
* content-aware delivery batch, matching `MessageBodyCodec` semantics so direct
|
|
2749
|
-
* and remote consumers observe the same payload shape.
|
|
2750
|
-
*
|
|
2751
|
-
* The media type is derived from the stream content type: `application/json`
|
|
2752
|
-
* (parameters ignored) yields a `json` batch, `text/*` a `text` batch, and
|
|
2753
|
-
* everything else (including an absent content type) a `bytes` batch.
|
|
2754
|
-
*
|
|
2755
|
-
* Throws `SyntaxError` on invalid stored JSON; callers map that to a
|
|
2756
|
-
* `parse-error` failure.
|
|
2757
|
-
*/
|
|
2758
|
-
function encodeBatch(contentType, messages, meta) {
|
|
2759
|
-
const mediaType = contentType.split(";", 1)[0].trim().toLowerCase();
|
|
2760
|
-
if (mediaType === "application/json") {
|
|
2761
|
-
const body = `[${messages.map((message) => decoder.decode(message.data)).join(",")}]`;
|
|
2762
|
-
return {
|
|
2763
|
-
kind: "json",
|
|
2764
|
-
items: JSON.parse(body),
|
|
2765
|
-
...meta
|
|
2766
|
-
};
|
|
2767
|
-
}
|
|
2768
|
-
if (mediaType.startsWith("text/")) return {
|
|
2769
|
-
kind: "text",
|
|
2770
|
-
text: messages.map((message) => decoder.decode(message.data)).join(""),
|
|
2771
|
-
...meta
|
|
2772
|
-
};
|
|
2773
|
-
const length = messages.reduce((total, message) => total + message.data.byteLength, 0);
|
|
2774
|
-
const data = new Uint8Array(length);
|
|
2775
|
-
let position = 0;
|
|
2776
|
-
for (const message of messages) {
|
|
2777
|
-
data.set(message.data, position);
|
|
2778
|
-
position += message.data.byteLength;
|
|
2779
|
-
}
|
|
2780
|
-
return {
|
|
2781
|
-
kind: "bytes",
|
|
2782
|
-
data,
|
|
2783
|
-
...meta
|
|
2784
|
-
};
|
|
2785
|
-
}
|
|
2786
|
-
|
|
2787
|
-
//#endregion
|
|
2788
|
-
//#region src/client/read-session.ts
|
|
2789
|
-
/**
|
|
2790
|
-
* The single client read-session implementation, shared by every adapter.
|
|
2791
|
-
*
|
|
2792
|
-
* It is a one-consumer, one-batch queue whose producer is backpressured by
|
|
2793
|
-
* iterator delivery. Iteration never throws for operational failures: the
|
|
2794
|
-
* terminal outcome is delivered through {@link ClientReadSession.done}, which
|
|
2795
|
-
* always resolves. Only programmer misuse (double iteration, concurrent
|
|
2796
|
-
* `next()`) throws.
|
|
2797
|
-
*/
|
|
2798
|
-
var ClientReadSession = class {
|
|
2799
|
-
done;
|
|
2800
|
-
contentType;
|
|
2801
|
-
startOffset;
|
|
2802
|
-
offset;
|
|
2803
|
-
cursor;
|
|
2804
|
-
upToDate;
|
|
2805
|
-
streamClosed;
|
|
2806
|
-
doneResolve;
|
|
2807
|
-
pending;
|
|
2808
|
-
waiting;
|
|
2809
|
-
ended = false;
|
|
2810
|
-
iterated = false;
|
|
2811
|
-
cancelHook;
|
|
2812
|
-
constructor(options) {
|
|
2813
|
-
this.contentType = options.contentType;
|
|
2814
|
-
this.startOffset = options.startOffset;
|
|
2815
|
-
this.offset = options.offset ?? options.startOffset;
|
|
2816
|
-
this.cursor = options.cursor;
|
|
2817
|
-
this.upToDate = options.upToDate ?? false;
|
|
2818
|
-
this.streamClosed = options.streamClosed ?? false;
|
|
2819
|
-
this.cancelHook = options.onCancel;
|
|
2820
|
-
this.done = new Promise((resolve) => {
|
|
2821
|
-
this.doneResolve = resolve;
|
|
2822
|
-
});
|
|
2823
|
-
}
|
|
2824
|
-
setCancelHook(hook) {
|
|
2825
|
-
this.cancelHook = hook;
|
|
2826
|
-
}
|
|
2827
|
-
[Symbol.asyncIterator]() {
|
|
2828
|
-
if (this.iterated) throw new Error("A stream read session can only be iterated once");
|
|
2829
|
-
this.iterated = true;
|
|
2830
|
-
return this;
|
|
2831
|
-
}
|
|
2832
|
-
next() {
|
|
2833
|
-
if (this.pending) return Promise.resolve(this.acceptPending());
|
|
2834
|
-
if (this.ended) return Promise.resolve({
|
|
2835
|
-
done: true,
|
|
2836
|
-
value: void 0
|
|
2837
|
-
});
|
|
2838
|
-
if (this.waiting) return Promise.reject(new Error("Concurrent iterator.next() calls are invalid"));
|
|
2839
|
-
return new Promise((resolve) => {
|
|
2840
|
-
this.waiting = { resolve };
|
|
2841
|
-
});
|
|
2842
|
-
}
|
|
2843
|
-
return() {
|
|
2844
|
-
this.cancel();
|
|
2845
|
-
return Promise.resolve({
|
|
2846
|
-
done: true,
|
|
2847
|
-
value: void 0
|
|
2848
|
-
});
|
|
2849
|
-
}
|
|
2850
|
-
cancel(reason) {
|
|
2851
|
-
if (this.ended) return;
|
|
2852
|
-
this.cancelHook?.(reason);
|
|
2853
|
-
this.end({ status: "cancelled" });
|
|
2854
|
-
}
|
|
2855
|
-
/** Producer side: hand a batch to the consumer, backpressured until accepted. */
|
|
2856
|
-
async deliver(batch) {
|
|
2857
|
-
if (this.ended) return;
|
|
2858
|
-
if (this.pending) throw new Error("Read session producer exceeded its one-batch buffer");
|
|
2859
|
-
if (this.waiting) {
|
|
2860
|
-
const waiting = this.waiting;
|
|
2861
|
-
this.waiting = void 0;
|
|
2862
|
-
this.updateState(batch);
|
|
2863
|
-
waiting.resolve({
|
|
2864
|
-
done: false,
|
|
2865
|
-
value: batch
|
|
2866
|
-
});
|
|
2867
|
-
return;
|
|
2868
|
-
}
|
|
2869
|
-
await new Promise((accepted) => {
|
|
2870
|
-
this.pending = {
|
|
2871
|
-
batch,
|
|
2872
|
-
accepted
|
|
2873
|
-
};
|
|
2874
|
-
});
|
|
2875
|
-
}
|
|
2876
|
-
/** Producer side: terminate the session with its outcome. Always resolves `done`. */
|
|
2877
|
-
end(result) {
|
|
2878
|
-
if (this.ended) return;
|
|
2879
|
-
this.ended = true;
|
|
2880
|
-
this.pending?.accepted();
|
|
2881
|
-
this.pending = void 0;
|
|
2882
|
-
this.waiting?.resolve({
|
|
2883
|
-
done: true,
|
|
2884
|
-
value: void 0
|
|
2885
|
-
});
|
|
2886
|
-
this.waiting = void 0;
|
|
2887
|
-
this.doneResolve(result);
|
|
2888
|
-
}
|
|
2889
|
-
acceptPending() {
|
|
2890
|
-
const pending = this.pending;
|
|
2891
|
-
this.pending = void 0;
|
|
2892
|
-
this.updateState(pending.batch);
|
|
2893
|
-
pending.accepted();
|
|
2894
|
-
return {
|
|
2895
|
-
done: false,
|
|
2896
|
-
value: pending.batch
|
|
2897
|
-
};
|
|
2898
|
-
}
|
|
2899
|
-
updateState(batch) {
|
|
2900
|
-
this.offset = batch.offset;
|
|
2901
|
-
this.cursor = batch.cursor;
|
|
2902
|
-
this.upToDate = batch.upToDate;
|
|
2903
|
-
this.streamClosed = batch.streamClosed;
|
|
2904
|
-
}
|
|
2905
|
-
};
|
|
2906
|
-
|
|
2907
|
-
//#endregion
|
|
2908
|
-
//#region src/client/direct/results.ts
|
|
2909
|
-
function failure(code, message, options = {}) {
|
|
2910
|
-
return {
|
|
2911
|
-
status: "error",
|
|
2912
|
-
code,
|
|
2913
|
-
message,
|
|
2914
|
-
httpStatus: options.httpStatus,
|
|
2915
|
-
retryable: options.retryable ?? false,
|
|
2916
|
-
cause: options.cause
|
|
2917
|
-
};
|
|
2918
|
-
}
|
|
2919
|
-
function abortedFailure(cause) {
|
|
2920
|
-
return failure("aborted", "Stream operation was aborted", { cause });
|
|
2921
|
-
}
|
|
2922
|
-
function clientClosedFailure() {
|
|
2923
|
-
return failure("client-closed", "Stream protocol client is closed");
|
|
2924
|
-
}
|
|
2925
|
-
/** Maps an unexpected thrown value (not a protocol result) to a failure. */
|
|
2926
|
-
function failureFromThrown(error) {
|
|
2927
|
-
if (error instanceof SyntaxError) return failure("parse-error", error.message, { cause: error });
|
|
2928
|
-
if (isNotSupportedError(error)) return failure("not-supported", error.message, { cause: error });
|
|
2929
|
-
return failure("unknown", "Stream operation failed", { cause: error });
|
|
2930
|
-
}
|
|
2931
|
-
/** Narrows the shared absent/failure statuses of a get/metadata/read result. */
|
|
2932
|
-
function absentResult(result) {
|
|
2933
|
-
if (result.status === "not-found") return { status: "not-found" };
|
|
2934
|
-
if (result.status === "gone") return { status: "gone" };
|
|
2935
|
-
return residualFailure(result);
|
|
2936
|
-
}
|
|
2937
|
-
function mapCreate(result) {
|
|
2938
|
-
if (result.status === "created") return {
|
|
2939
|
-
status: "created",
|
|
2940
|
-
contentType: result.contentType
|
|
2941
|
-
};
|
|
2942
|
-
if (result.status === "exists" || result.status === "conflict") return { status: "conflict" };
|
|
2943
|
-
return residualFailure(result);
|
|
2944
|
-
}
|
|
2945
|
-
function mapAppend(result) {
|
|
2946
|
-
if (result.status === "appended" || result.status === "duplicate") return { status: "appended" };
|
|
2947
|
-
if (result.status === "not-found") return { status: "not-found" };
|
|
2948
|
-
if (result.status === "gone") return { status: "gone" };
|
|
2949
|
-
if (result.status === "conflict") return result.conflictReason === "closed" ? { status: "closed" } : { status: "conflict" };
|
|
2950
|
-
return residualFailure(result);
|
|
2951
|
-
}
|
|
2952
|
-
function mapClose(result) {
|
|
2953
|
-
if (result.status === "appended" || result.status === "duplicate") return {
|
|
2954
|
-
status: "closed",
|
|
2955
|
-
finalOffset: result.offset
|
|
2956
|
-
};
|
|
2957
|
-
if (result.status === "not-found") return { status: "not-found" };
|
|
2958
|
-
if (result.status === "gone") return { status: "gone" };
|
|
2959
|
-
if (result.status === "conflict") return { status: "conflict" };
|
|
2960
|
-
return residualFailure(result);
|
|
2961
|
-
}
|
|
2962
|
-
/** Maps a mid-read terminal protocol result to a read-session failure. */
|
|
2963
|
-
function readFailure(result) {
|
|
2964
|
-
if (result.status === "not-found") return failure("unknown", "Stream not found during read");
|
|
2965
|
-
if (result.status === "gone") return failure("unknown", "Stream is gone during read");
|
|
2966
|
-
return residualFailure(result);
|
|
2967
|
-
}
|
|
2968
|
-
function residualFailure(result) {
|
|
2969
|
-
switch (result.status) {
|
|
2970
|
-
case "not-supported": return failure("not-supported", `Feature is not supported: ${result.feature}`);
|
|
2971
|
-
case "bad-request":
|
|
2972
|
-
case "invalid-epoch-seq": return failure("bad-request", "Invalid stream request");
|
|
2973
|
-
case "busy": return failure("busy", "Stream is busy", { retryable: true });
|
|
2974
|
-
default: return failure("unknown", `Unexpected stream result: ${result.status}`);
|
|
2975
|
-
}
|
|
2976
|
-
}
|
|
2977
|
-
|
|
2978
|
-
//#endregion
|
|
2979
|
-
//#region src/client/direct/read.ts
|
|
2980
|
-
const START = "-1";
|
|
2981
|
-
/**
|
|
2982
|
-
* Resolves a read into a session and drives the catch-up (and optional live)
|
|
2983
|
-
* pump. The pump delivers content-aware batches and never throws into the
|
|
2984
|
-
* consumer: it ends the session with a {@link ReadEndResult}.
|
|
2985
|
-
*/
|
|
2986
|
-
async function directRead(client, id, options) {
|
|
2987
|
-
return client.run(options.signal, async (operationSignal) => {
|
|
2988
|
-
const found = await client.streamsy.get(id);
|
|
2989
|
-
if (found.status !== "ok") return absentResult(found);
|
|
2990
|
-
const metadata = await found.stream.metadata();
|
|
2991
|
-
if (metadata.status !== "ok") return absentResult(metadata);
|
|
2992
|
-
const controller = new AbortController();
|
|
2993
|
-
const signal = combineSignals(operationSignal, controller.signal);
|
|
2994
|
-
const session = new ClientReadSession({
|
|
2995
|
-
contentType: metadata.contentType,
|
|
2996
|
-
startOffset: options.offset ?? START,
|
|
2997
|
-
onCancel: (reason) => controller.abort(reason)
|
|
2998
|
-
});
|
|
2999
|
-
pump(found.stream, metadata.contentType, options, signal, session);
|
|
3000
|
-
return {
|
|
3001
|
-
status: "ok",
|
|
3002
|
-
session
|
|
3003
98
|
};
|
|
3004
99
|
});
|
|
3005
100
|
}
|
|
3006
|
-
async function pump(stream, contentType, options, signal, session) {
|
|
3007
|
-
let offset = options.offset ?? START;
|
|
3008
|
-
let cursor;
|
|
3009
|
-
const finish = () => session.end(signal.aborted ? { status: "cancelled" } : { status: "done" });
|
|
3010
|
-
try {
|
|
3011
|
-
while (!signal.aborted) {
|
|
3012
|
-
const result = await stream.read({ offset });
|
|
3013
|
-
if (result.status !== "ok") return session.end(readFailure(result));
|
|
3014
|
-
const batch = encodeBatch(contentType, result.messages, {
|
|
3015
|
-
offset: result.nextOffset,
|
|
3016
|
-
upToDate: result.upToDate,
|
|
3017
|
-
streamClosed: result.closed === true
|
|
3018
|
-
});
|
|
3019
|
-
await session.deliver(batch);
|
|
3020
|
-
offset = batch.offset;
|
|
3021
|
-
if (batch.streamClosed || batch.upToDate) break;
|
|
3022
|
-
}
|
|
3023
|
-
if (options.live !== "long-poll" && options.live !== "sse") return finish();
|
|
3024
|
-
while (!signal.aborted && !session.streamClosed) {
|
|
3025
|
-
const result = await stream.readLive({
|
|
3026
|
-
offset,
|
|
3027
|
-
mode: options.live,
|
|
3028
|
-
cursor,
|
|
3029
|
-
signal
|
|
3030
|
-
});
|
|
3031
|
-
if (result.status !== "ok" && result.status !== "timeout") return session.end(readFailure(result));
|
|
3032
|
-
const batch = encodeBatch(contentType, result.messages, {
|
|
3033
|
-
offset: result.nextOffset,
|
|
3034
|
-
cursor: result.cursor,
|
|
3035
|
-
upToDate: result.upToDate,
|
|
3036
|
-
streamClosed: result.closed === true
|
|
3037
|
-
});
|
|
3038
|
-
await session.deliver(batch);
|
|
3039
|
-
offset = batch.offset;
|
|
3040
|
-
cursor = batch.cursor;
|
|
3041
|
-
if (batch.streamClosed) break;
|
|
3042
|
-
}
|
|
3043
|
-
finish();
|
|
3044
|
-
} catch (error) {
|
|
3045
|
-
if (signal.aborted) session.end({ status: "cancelled" });
|
|
3046
|
-
else session.end(failureFromThrown(error));
|
|
3047
|
-
}
|
|
3048
|
-
}
|
|
3049
|
-
|
|
3050
101
|
//#endregion
|
|
3051
|
-
//#region src/
|
|
3052
|
-
|
|
3053
|
-
/**
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
this.id = streamId;
|
|
3059
|
-
}
|
|
3060
|
-
async head(options) {
|
|
3061
|
-
return this.client.run(options?.signal, async () => {
|
|
3062
|
-
const found = await this.client.streamsy.get(this.id);
|
|
3063
|
-
if (found.status !== "ok") return absentResult(found);
|
|
3064
|
-
const metadata = await found.stream.metadata();
|
|
3065
|
-
if (metadata.status !== "ok") return absentResult(metadata);
|
|
3066
|
-
return {
|
|
3067
|
-
status: "ok",
|
|
3068
|
-
contentType: metadata.contentType,
|
|
3069
|
-
offset: metadata.nextOffset,
|
|
3070
|
-
closed: metadata.closed === true
|
|
3071
|
-
};
|
|
3072
|
-
});
|
|
3073
|
-
}
|
|
3074
|
-
async create(options = {}) {
|
|
3075
|
-
return this.client.run(options.signal, async () => {
|
|
3076
|
-
const result = await this.client.streamsy.create(this.id, {
|
|
3077
|
-
contentType: options.contentType,
|
|
3078
|
-
ttlSeconds: options.ttlSeconds,
|
|
3079
|
-
expiresAt: options.expiresAt,
|
|
3080
|
-
initialData: toBytes(options.initialData),
|
|
3081
|
-
closed: options.closed
|
|
3082
|
-
});
|
|
3083
|
-
return mapCreate(result);
|
|
3084
|
-
});
|
|
3085
|
-
}
|
|
3086
|
-
async append(data, options = {}) {
|
|
3087
|
-
return this.client.run(options.signal, async () => {
|
|
3088
|
-
if (options.contentType === void 0) return failure("bad-request", "append requires a contentType");
|
|
3089
|
-
const resolved = await this.resolve();
|
|
3090
|
-
if (!resolved.ok) return resolved.result;
|
|
3091
|
-
const result = await resolved.stream.append({
|
|
3092
|
-
data: toBytes(data),
|
|
3093
|
-
contentType: options.contentType,
|
|
3094
|
-
seq: options.seq
|
|
3095
|
-
});
|
|
3096
|
-
return mapAppend(result);
|
|
3097
|
-
});
|
|
3098
|
-
}
|
|
3099
|
-
async close(options = {}) {
|
|
3100
|
-
return this.client.run(options.signal, async () => {
|
|
3101
|
-
const resolved = await this.resolve();
|
|
3102
|
-
if (!resolved.ok) return resolved.result;
|
|
3103
|
-
let contentType = options.contentType;
|
|
3104
|
-
if (contentType === void 0) {
|
|
3105
|
-
const found = await this.contentTypeFor(resolved.stream);
|
|
3106
|
-
if (!found.ok) return found.result;
|
|
3107
|
-
contentType = found.contentType;
|
|
3108
|
-
}
|
|
3109
|
-
const result = await resolved.stream.append({
|
|
3110
|
-
data: toBytes(options.finalData) ?? new Uint8Array(),
|
|
3111
|
-
contentType,
|
|
3112
|
-
close: true
|
|
3113
|
-
});
|
|
3114
|
-
return mapClose(result);
|
|
3115
|
-
});
|
|
3116
|
-
}
|
|
3117
|
-
async read(options = {}) {
|
|
3118
|
-
return directRead(this.client, this.id, options);
|
|
3119
|
-
}
|
|
3120
|
-
async resolve() {
|
|
3121
|
-
const found = await this.client.streamsy.get(this.id);
|
|
3122
|
-
if (found.status === "ok") return {
|
|
3123
|
-
ok: true,
|
|
3124
|
-
stream: found.stream
|
|
3125
|
-
};
|
|
3126
|
-
return {
|
|
3127
|
-
ok: false,
|
|
3128
|
-
result: absentResult(found)
|
|
3129
|
-
};
|
|
3130
|
-
}
|
|
3131
|
-
async contentTypeFor(stream) {
|
|
3132
|
-
const metadata = await stream.metadata();
|
|
3133
|
-
if (metadata.status === "ok") return {
|
|
3134
|
-
ok: true,
|
|
3135
|
-
contentType: metadata.contentType
|
|
3136
|
-
};
|
|
3137
|
-
return {
|
|
3138
|
-
ok: false,
|
|
3139
|
-
result: absentResult(metadata)
|
|
3140
|
-
};
|
|
3141
|
-
}
|
|
3142
|
-
};
|
|
3143
|
-
function toBytes(value) {
|
|
3144
|
-
return typeof value === "string" ? encoder.encode(value) : value;
|
|
3145
|
-
}
|
|
3146
|
-
|
|
3147
|
-
//#endregion
|
|
3148
|
-
//#region src/client/direct/client.ts
|
|
3149
|
-
/** Structural refinement test: is this client the exact-Streamsy direct adapter? */
|
|
3150
|
-
function hasStreamsyProtocol(client) {
|
|
3151
|
-
return "streamsy" in client;
|
|
3152
|
-
}
|
|
3153
|
-
function directProtocolClient(factory) {
|
|
3154
|
-
return new DirectProtocolClient(factory);
|
|
3155
|
-
}
|
|
3156
|
-
/**
|
|
3157
|
-
* Adapts a `StreamProtocolFactory` to the transport-neutral client seam. It
|
|
3158
|
-
* keeps a single client-level abort controller whose signal is threaded into
|
|
3159
|
-
* every operation and read session; `close()` aborts it and rejects new work.
|
|
3160
|
-
* There is no session registry: sessions observe the abort through their own
|
|
3161
|
-
* signal and end with `{ status: "cancelled" }`.
|
|
3162
|
-
*/
|
|
3163
|
-
var DirectProtocolClient = class {
|
|
3164
|
-
streamsy;
|
|
3165
|
-
controller = new AbortController();
|
|
3166
|
-
disposed = false;
|
|
3167
|
-
constructor(factory) {
|
|
3168
|
-
this.streamsy = factory;
|
|
3169
|
-
}
|
|
3170
|
-
stream(streamId) {
|
|
3171
|
-
return new DirectProtocolHandle(this, streamId);
|
|
3172
|
-
}
|
|
3173
|
-
async close(reason) {
|
|
3174
|
-
if (this.disposed) return;
|
|
3175
|
-
this.disposed = true;
|
|
3176
|
-
this.controller.abort(reason);
|
|
3177
|
-
}
|
|
3178
|
-
/**
|
|
3179
|
-
* Runs one operation under the combined client/caller signal, converting a
|
|
3180
|
-
* disposed client, an already-aborted signal, and unexpected throws into
|
|
3181
|
-
* {@link ClientFailure} members. Domain results flow through untouched.
|
|
3182
|
-
*/
|
|
3183
|
-
async run(signal, work) {
|
|
3184
|
-
if (this.disposed) return clientClosedFailure();
|
|
3185
|
-
const combined = combineSignals(this.controller.signal, signal);
|
|
3186
|
-
if (combined.aborted) return abortedFailure(combined.reason);
|
|
3187
|
-
try {
|
|
3188
|
-
return await work(combined);
|
|
3189
|
-
} catch (error) {
|
|
3190
|
-
if (combined.aborted) return abortedFailure(combined.reason ?? error);
|
|
3191
|
-
return failureFromThrown(error);
|
|
3192
|
-
}
|
|
3193
|
-
}
|
|
3194
|
-
};
|
|
3195
|
-
function combineSignals(...signals) {
|
|
3196
|
-
const present = signals.filter((signal) => signal !== void 0);
|
|
3197
|
-
if (present.length === 0) return new AbortController().signal;
|
|
3198
|
-
return present.length === 1 ? present[0] : AbortSignal.any(present);
|
|
3199
|
-
}
|
|
3200
|
-
|
|
102
|
+
//#region src/toolkit/producer.ts
|
|
103
|
+
var producer_exports = /* @__PURE__ */ __exportAll({ next: () => next });
|
|
104
|
+
/** Advance only after the caller has acknowledged appended or duplicate. Persist this tuple at the owning edge. */
|
|
105
|
+
const next = (position) => ({
|
|
106
|
+
...position,
|
|
107
|
+
producerSeq: position.producerSeq + 1
|
|
108
|
+
});
|
|
3201
109
|
//#endregion
|
|
3202
|
-
//#region src/
|
|
3203
|
-
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
*/
|
|
3212
|
-
const clone = (value) => structuredClone(value);
|
|
3213
|
-
function withSerializedSeam(adapter) {
|
|
3214
|
-
const wrapped = {
|
|
3215
|
-
getRecord: async (streamId) => clone(await adapter.getRecord(clone(streamId))),
|
|
3216
|
-
listMessages: async (streamId, options) => clone(await adapter.listMessages(clone(streamId), clone(options))),
|
|
3217
|
-
getProducerState: async (streamId, producerId) => clone(await adapter.getProducerState(clone(streamId), clone(producerId))),
|
|
3218
|
-
append: async (streamId, plan) => clone(await adapter.append(clone(streamId), clone(plan))),
|
|
3219
|
-
awaitChange: async (streamId, options) => clone(await adapter.awaitChange(clone(streamId), clone(options))),
|
|
3220
|
-
scheduleExpiry: (streamId, at) => adapter.scheduleExpiry(clone(streamId), clone(at)),
|
|
3221
|
-
cancelExpiry: (streamId) => adapter.cancelExpiry(clone(streamId)),
|
|
3222
|
-
create: async (plan) => clone(await adapter.create(clone(plan))),
|
|
3223
|
-
delete: async (plan) => clone(await adapter.delete(clone(plan)))
|
|
3224
|
-
};
|
|
3225
|
-
const fork = adapter.fork;
|
|
3226
|
-
if (fork) wrapped.fork = async (plan) => clone(await fork.call(adapter, clone(plan)));
|
|
3227
|
-
return wrapped;
|
|
3228
|
-
}
|
|
3229
|
-
/** Wrap `makeAdapter` so every case exercises the serializability wrapper. */
|
|
3230
|
-
function serialized(makeAdapter) {
|
|
3231
|
-
return async () => withSerializedSeam(await makeAdapter());
|
|
3232
|
-
}
|
|
3233
|
-
function encode(value) {
|
|
3234
|
-
return new TextEncoder().encode(value);
|
|
3235
|
-
}
|
|
3236
|
-
function assert(condition, message) {
|
|
3237
|
-
if (!condition) throw new Error(`storage-adapter-contract: ${message}`);
|
|
3238
|
-
}
|
|
3239
|
-
function assertStatus(result, expected, label) {
|
|
3240
|
-
if (result.status !== expected) throw new Error(`storage-adapter-contract: ${label} — expected status "${expected}", got "${result.status}"`);
|
|
3241
|
-
}
|
|
3242
|
-
function newRecord(id, forkedFrom) {
|
|
3243
|
-
return {
|
|
3244
|
-
id,
|
|
3245
|
-
config: {
|
|
3246
|
-
contentType: TEXT_TYPE,
|
|
3247
|
-
createdAt: 0
|
|
3248
|
-
},
|
|
3249
|
-
lifecycle: forkedFrom ? {
|
|
3250
|
-
forkedFrom,
|
|
3251
|
-
forkOffset: ZERO_OFFSET
|
|
3252
|
-
} : {},
|
|
3253
|
-
currentOffset: ZERO_OFFSET,
|
|
3254
|
-
counter: 0
|
|
3255
|
-
};
|
|
3256
|
-
}
|
|
3257
|
-
async function currentRecord(adapter, id) {
|
|
3258
|
-
const record = await adapter.getRecord(id);
|
|
3259
|
-
assert(record, `expected record for stream "${id}"`);
|
|
3260
|
-
return record;
|
|
3261
|
-
}
|
|
3262
|
-
/** Build an append plan that advances the tail by `texts.length` messages. */
|
|
3263
|
-
function advancePlan(record, texts) {
|
|
3264
|
-
const allocation = allocate(defaultOffsetGenerator, record.currentOffset, record.counter, texts.length);
|
|
3265
|
-
return {
|
|
3266
|
-
preconditions: {
|
|
3267
|
-
expectedOffset: record.currentOffset,
|
|
3268
|
-
expectedClosed: false
|
|
3269
|
-
},
|
|
3270
|
-
messages: texts.map((value, index) => ({
|
|
3271
|
-
data: encode(value),
|
|
3272
|
-
offset: allocation.offsets[index],
|
|
3273
|
-
timestamp: 0
|
|
3274
|
-
})),
|
|
3275
|
-
recordPatch: {
|
|
3276
|
-
currentOffset: allocation.nextOffset,
|
|
3277
|
-
counter: allocation.endCounter
|
|
3278
|
-
}
|
|
3279
|
-
};
|
|
3280
|
-
}
|
|
3281
|
-
async function appendTexts(adapter, id, texts) {
|
|
3282
|
-
const record = await currentRecord(adapter, id);
|
|
3283
|
-
return adapter.append(id, advancePlan(record, texts));
|
|
3284
|
-
}
|
|
3285
|
-
async function createStream(adapter, id) {
|
|
3286
|
-
const result = await adapter.create({ record: newRecord(id) });
|
|
3287
|
-
assertStatus(result, "created", `create("${id}")`);
|
|
3288
|
-
}
|
|
3289
|
-
/** Bind the adapter's required level-triggered `awaitChange` to a stream id. */
|
|
3290
|
-
function awaitChangeFor(adapter) {
|
|
3291
|
-
return (id, options) => adapter.awaitChange(id, options);
|
|
3292
|
-
}
|
|
3293
|
-
function delay(ms) {
|
|
3294
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
3295
|
-
}
|
|
3296
|
-
/** Let a freshly-started `awaitChange` register its waiter before we mutate. */
|
|
3297
|
-
function tick() {
|
|
3298
|
-
return new Promise((resolve) => setTimeout(resolve, 0));
|
|
3299
|
-
}
|
|
3300
|
-
/** Resolves `true` if `promise` is still unsettled after `ms`. */
|
|
3301
|
-
function staysPending(promise, ms) {
|
|
3302
|
-
return Promise.race([promise.then(() => false, () => false), delay(ms).then(() => true)]);
|
|
3303
|
-
}
|
|
3304
|
-
function runAppendContract(makeAdapter, harness) {
|
|
3305
|
-
harness.it("append advances the tail and folds close", async () => {
|
|
3306
|
-
const adapter = await makeAdapter();
|
|
3307
|
-
await createStream(adapter, "s");
|
|
3308
|
-
const appended = await appendTexts(adapter, "s", ["a", "b"]);
|
|
3309
|
-
assertStatus(appended, "appended", "append");
|
|
3310
|
-
assert(appended.status === "appended", "append narrows");
|
|
3311
|
-
assert(appended.record.counter === 2, "counter advanced to 2");
|
|
3312
|
-
assert(appended.record.currentOffset === formatCounter(2), "offset advanced");
|
|
3313
|
-
assert((await adapter.listMessages("s")).length === 2, "two messages listable");
|
|
3314
|
-
const record = await currentRecord(adapter, "s");
|
|
3315
|
-
const closed = await adapter.append("s", {
|
|
3316
|
-
preconditions: {
|
|
3317
|
-
expectedOffset: record.currentOffset,
|
|
3318
|
-
expectedClosed: false
|
|
3319
|
-
},
|
|
3320
|
-
messages: [],
|
|
3321
|
-
recordPatch: { lifecycle: {
|
|
3322
|
-
closed: true,
|
|
3323
|
-
closedAt: 0
|
|
3324
|
-
} }
|
|
3325
|
-
});
|
|
3326
|
-
assertStatus(closed, "appended", "close append");
|
|
3327
|
-
assert(closed.status === "appended" && closed.record.lifecycle.closed === true, "closed folded");
|
|
3328
|
-
});
|
|
3329
|
-
harness.it("append rejects a stale expectedOffset with reason 'offset' and writes nothing", async () => {
|
|
3330
|
-
const adapter = await makeAdapter();
|
|
3331
|
-
await createStream(adapter, "s");
|
|
3332
|
-
await appendTexts(adapter, "s", ["a"]);
|
|
3333
|
-
const stale = await adapter.append("s", {
|
|
3334
|
-
preconditions: {
|
|
3335
|
-
expectedOffset: ZERO_OFFSET,
|
|
3336
|
-
expectedClosed: false
|
|
3337
|
-
},
|
|
3338
|
-
messages: [{
|
|
3339
|
-
data: encode("b"),
|
|
3340
|
-
offset: formatCounter(2),
|
|
3341
|
-
timestamp: 0
|
|
3342
|
-
}],
|
|
3343
|
-
recordPatch: {
|
|
3344
|
-
currentOffset: formatCounter(2),
|
|
3345
|
-
counter: 2
|
|
3346
|
-
}
|
|
3347
|
-
});
|
|
3348
|
-
assertStatus(stale, "precondition-failed", "stale offset");
|
|
3349
|
-
assert(stale.status === "precondition-failed" && stale.reason === "offset", "reason offset");
|
|
3350
|
-
const record = await currentRecord(adapter, "s");
|
|
3351
|
-
assert(record.currentOffset === OFFSET_1 && record.counter === 1, "tail unchanged");
|
|
3352
|
-
assert((await adapter.listMessages("s")).length === 1, "no extra message written");
|
|
3353
|
-
});
|
|
3354
|
-
harness.it("append rejects a violated expectedClosed with reason 'closed' and writes nothing", async () => {
|
|
3355
|
-
const adapter = await makeAdapter();
|
|
3356
|
-
await createStream(adapter, "s");
|
|
3357
|
-
const failed = await adapter.append("s", {
|
|
3358
|
-
preconditions: {
|
|
3359
|
-
expectedOffset: ZERO_OFFSET,
|
|
3360
|
-
expectedClosed: true
|
|
3361
|
-
},
|
|
3362
|
-
messages: [{
|
|
3363
|
-
data: encode("a"),
|
|
3364
|
-
offset: OFFSET_1,
|
|
3365
|
-
timestamp: 0
|
|
3366
|
-
}],
|
|
3367
|
-
recordPatch: {
|
|
3368
|
-
currentOffset: OFFSET_1,
|
|
3369
|
-
counter: 1
|
|
3370
|
-
}
|
|
3371
|
-
});
|
|
3372
|
-
assertStatus(failed, "precondition-failed", "closed precondition");
|
|
3373
|
-
assert(failed.status === "precondition-failed" && failed.reason === "closed", "reason closed");
|
|
3374
|
-
const record = await currentRecord(adapter, "s");
|
|
3375
|
-
assert(record.currentOffset === ZERO_OFFSET && record.counter === 0, "tail unchanged");
|
|
3376
|
-
assert((await adapter.listMessages("s")).length === 0, "no message written");
|
|
3377
|
-
});
|
|
3378
|
-
harness.it("append rejects a failed producer CAS with reason 'producer' and writes nothing", async () => {
|
|
3379
|
-
const adapter = await makeAdapter();
|
|
3380
|
-
await createStream(adapter, "s");
|
|
3381
|
-
const seeded = await adapter.append("s", {
|
|
3382
|
-
preconditions: {
|
|
3383
|
-
expectedOffset: ZERO_OFFSET,
|
|
3384
|
-
expectedClosed: false,
|
|
3385
|
-
producer: {
|
|
3386
|
-
producerId: "p",
|
|
3387
|
-
expected: void 0,
|
|
3388
|
-
next: {
|
|
3389
|
-
epoch: 1,
|
|
3390
|
-
lastSeq: 0
|
|
3391
|
-
}
|
|
3392
|
-
}
|
|
3393
|
-
},
|
|
3394
|
-
messages: [{
|
|
3395
|
-
data: encode("a"),
|
|
3396
|
-
offset: OFFSET_1,
|
|
3397
|
-
timestamp: 0
|
|
3398
|
-
}],
|
|
3399
|
-
recordPatch: {
|
|
3400
|
-
currentOffset: OFFSET_1,
|
|
3401
|
-
counter: 1
|
|
3402
|
-
}
|
|
3403
|
-
});
|
|
3404
|
-
assertStatus(seeded, "appended", "seed producer");
|
|
3405
|
-
const record = await currentRecord(adapter, "s");
|
|
3406
|
-
const failed = await adapter.append("s", {
|
|
3407
|
-
preconditions: {
|
|
3408
|
-
expectedOffset: record.currentOffset,
|
|
3409
|
-
expectedClosed: false,
|
|
3410
|
-
producer: {
|
|
3411
|
-
producerId: "p",
|
|
3412
|
-
expected: {
|
|
3413
|
-
epoch: 9,
|
|
3414
|
-
lastSeq: 9
|
|
3415
|
-
},
|
|
3416
|
-
next: {
|
|
3417
|
-
epoch: 2,
|
|
3418
|
-
lastSeq: 0
|
|
3419
|
-
}
|
|
3420
|
-
}
|
|
3421
|
-
},
|
|
3422
|
-
messages: [{
|
|
3423
|
-
data: encode("b"),
|
|
3424
|
-
offset: formatCounter(2),
|
|
3425
|
-
timestamp: 0
|
|
3426
|
-
}],
|
|
3427
|
-
recordPatch: {
|
|
3428
|
-
currentOffset: formatCounter(2),
|
|
3429
|
-
counter: 2
|
|
3430
|
-
}
|
|
3431
|
-
});
|
|
3432
|
-
assertStatus(failed, "precondition-failed", "producer CAS");
|
|
3433
|
-
assert(failed.status === "precondition-failed" && failed.reason === "producer", "reason producer");
|
|
3434
|
-
const after = await currentRecord(adapter, "s");
|
|
3435
|
-
assert(after.currentOffset === OFFSET_1 && after.counter === 1, "tail unchanged on CAS failure");
|
|
3436
|
-
assert((await adapter.listMessages("s")).length === 1, "no message written on CAS failure");
|
|
3437
|
-
const producer = await adapter.getProducerState("s", "p");
|
|
3438
|
-
assert(producer?.epoch === 1 && producer.lastSeq === 0, "producer state unchanged");
|
|
3439
|
-
});
|
|
3440
|
-
harness.it("append rejects an absent-expected producer CAS when the producer already exists", async () => {
|
|
3441
|
-
const adapter = await makeAdapter();
|
|
3442
|
-
await createStream(adapter, "s");
|
|
3443
|
-
const seeded = await adapter.append("s", {
|
|
3444
|
-
preconditions: {
|
|
3445
|
-
expectedOffset: ZERO_OFFSET,
|
|
3446
|
-
expectedClosed: false,
|
|
3447
|
-
producer: {
|
|
3448
|
-
producerId: "p",
|
|
3449
|
-
next: {
|
|
3450
|
-
epoch: 1,
|
|
3451
|
-
lastSeq: 0
|
|
3452
|
-
}
|
|
3453
|
-
}
|
|
3454
|
-
},
|
|
3455
|
-
messages: [{
|
|
3456
|
-
data: encode("a"),
|
|
3457
|
-
offset: OFFSET_1,
|
|
3458
|
-
timestamp: 0
|
|
3459
|
-
}],
|
|
3460
|
-
recordPatch: {
|
|
3461
|
-
currentOffset: OFFSET_1,
|
|
3462
|
-
counter: 1
|
|
3463
|
-
}
|
|
3464
|
-
});
|
|
3465
|
-
assertStatus(seeded, "appended", "seed producer");
|
|
3466
|
-
const record = await currentRecord(adapter, "s");
|
|
3467
|
-
const failed = await adapter.append("s", {
|
|
3468
|
-
preconditions: {
|
|
3469
|
-
expectedOffset: record.currentOffset,
|
|
3470
|
-
expectedClosed: false,
|
|
3471
|
-
producer: {
|
|
3472
|
-
producerId: "p",
|
|
3473
|
-
next: {
|
|
3474
|
-
epoch: 2,
|
|
3475
|
-
lastSeq: 0
|
|
3476
|
-
}
|
|
3477
|
-
}
|
|
3478
|
-
},
|
|
3479
|
-
messages: [{
|
|
3480
|
-
data: encode("b"),
|
|
3481
|
-
offset: formatCounter(2),
|
|
3482
|
-
timestamp: 0
|
|
3483
|
-
}],
|
|
3484
|
-
recordPatch: {
|
|
3485
|
-
currentOffset: formatCounter(2),
|
|
3486
|
-
counter: 2
|
|
3487
|
-
}
|
|
3488
|
-
});
|
|
3489
|
-
assertStatus(failed, "precondition-failed", "absent-expected CAS on existing producer");
|
|
3490
|
-
assert(failed.status === "precondition-failed" && failed.reason === "producer", "reason producer");
|
|
3491
|
-
const producer = await adapter.getProducerState("s", "p");
|
|
3492
|
-
assert(producer?.epoch === 1 && producer.lastSeq === 0, "producer state unchanged");
|
|
3493
|
-
assert((await adapter.listMessages("s")).length === 1, "no message written");
|
|
3494
|
-
});
|
|
3495
|
-
harness.it("append accepts a lifecycle-only TTL touch without advancing the tail", async () => {
|
|
3496
|
-
const adapter = await makeAdapter();
|
|
3497
|
-
await createStream(adapter, "s");
|
|
3498
|
-
const before = await currentRecord(adapter, "s");
|
|
3499
|
-
const touched = await adapter.append("s", {
|
|
3500
|
-
preconditions: {
|
|
3501
|
-
expectedOffset: before.currentOffset,
|
|
3502
|
-
expectedClosed: false
|
|
3503
|
-
},
|
|
3504
|
-
recordPatch: { lifecycle: { expiresAtMs: 1e6 } }
|
|
3505
|
-
});
|
|
3506
|
-
assertStatus(touched, "appended", "touch");
|
|
3507
|
-
assert(touched.status === "appended", "touch narrows");
|
|
3508
|
-
assert(touched.record.currentOffset === before.currentOffset, "touch keeps offset");
|
|
3509
|
-
assert(touched.record.counter === before.counter, "touch keeps counter");
|
|
3510
|
-
assert(touched.record.lifecycle.expiresAtMs === 1e6, "touch renewed deadline");
|
|
3511
|
-
assert((await adapter.listMessages("s")).length === 0, "touch wrote no messages");
|
|
3512
|
-
});
|
|
3513
|
-
}
|
|
3514
|
-
function runReadContract(makeAdapter, harness) {
|
|
3515
|
-
harness.it("listMessages windows by lexicographic offset order: exclusive after, inclusive until", async () => {
|
|
3516
|
-
const adapter = await makeAdapter();
|
|
3517
|
-
await createStream(adapter, "s");
|
|
3518
|
-
const appended = await appendTexts(adapter, "s", [
|
|
3519
|
-
"a",
|
|
3520
|
-
"b",
|
|
3521
|
-
"c",
|
|
3522
|
-
"d"
|
|
3523
|
-
]);
|
|
3524
|
-
assertStatus(appended, "appended", "seed messages");
|
|
3525
|
-
const all = await adapter.listMessages("s");
|
|
3526
|
-
assert(all.length === 4, "four messages listable");
|
|
3527
|
-
const sorted = all.map((m) => m.offset).toSorted();
|
|
3528
|
-
assert(all.every((m, i) => m.offset === sorted[i]), "messages returned in lexicographic offset order");
|
|
3529
|
-
const afterFirst = await adapter.listMessages("s", { after: formatCounter(1) });
|
|
3530
|
-
assert(afterFirst.length === 3, "after excludes the boundary message");
|
|
3531
|
-
assert(afterFirst[0].offset === formatCounter(2), "after starts past the boundary");
|
|
3532
|
-
const untilThird = await adapter.listMessages("s", { until: formatCounter(3) });
|
|
3533
|
-
assert(untilThird.length === 3, "until includes the boundary message");
|
|
3534
|
-
assert(untilThird[2].offset === formatCounter(3), "until ends at the boundary");
|
|
3535
|
-
const window = await adapter.listMessages("s", {
|
|
3536
|
-
after: formatCounter(1),
|
|
3537
|
-
until: formatCounter(3),
|
|
3538
|
-
limit: 1
|
|
3539
|
-
});
|
|
3540
|
-
assert(window.length === 1 && window[0].offset === formatCounter(2), "window + limit");
|
|
3541
|
-
});
|
|
3542
|
-
}
|
|
3543
|
-
function runAwaitChangeContract(makeAdapter, harness) {
|
|
3544
|
-
harness.it("awaitChange returns 'changed' immediately when the tail already advanced", async () => {
|
|
3545
|
-
const adapter = await makeAdapter();
|
|
3546
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3547
|
-
await createStream(adapter, "s");
|
|
3548
|
-
await appendTexts(adapter, "s", ["a"]);
|
|
3549
|
-
const result = await awaitChange("s", {
|
|
3550
|
-
fromOffset: ZERO_OFFSET,
|
|
3551
|
-
observedClosed: false,
|
|
3552
|
-
observedSoftDeleted: false,
|
|
3553
|
-
timeoutMs: 1e3
|
|
3554
|
-
});
|
|
3555
|
-
assertStatus(result, "changed", "immediate change");
|
|
3556
|
-
assert(result.snapshot.currentOffset === OFFSET_1, "snapshot reflects the new tail");
|
|
3557
|
-
});
|
|
3558
|
-
harness.it("awaitChange times out with a fresh snapshot when nothing changes", async () => {
|
|
3559
|
-
const adapter = await makeAdapter();
|
|
3560
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3561
|
-
await createStream(adapter, "s");
|
|
3562
|
-
const record = await currentRecord(adapter, "s");
|
|
3563
|
-
const result = await awaitChange("s", {
|
|
3564
|
-
fromOffset: record.currentOffset,
|
|
3565
|
-
observedClosed: false,
|
|
3566
|
-
observedSoftDeleted: false,
|
|
3567
|
-
timeoutMs: 80
|
|
3568
|
-
});
|
|
3569
|
-
assertStatus(result, "timeout", "timeout");
|
|
3570
|
-
assert(result.snapshot.present === true, "snapshot present");
|
|
3571
|
-
assert(result.snapshot.currentOffset === ZERO_OFFSET, "snapshot at the parked tail");
|
|
3572
|
-
});
|
|
3573
|
-
harness.it("awaitChange wakes a parked waiter on a committing append", async () => {
|
|
3574
|
-
const adapter = await makeAdapter();
|
|
3575
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3576
|
-
await createStream(adapter, "s");
|
|
3577
|
-
const record = await currentRecord(adapter, "s");
|
|
3578
|
-
const pending = awaitChange("s", {
|
|
3579
|
-
fromOffset: record.currentOffset,
|
|
3580
|
-
observedClosed: false,
|
|
3581
|
-
observedSoftDeleted: false,
|
|
3582
|
-
timeoutMs: 2e3
|
|
3583
|
-
});
|
|
3584
|
-
await tick();
|
|
3585
|
-
await appendTexts(adapter, "s", ["a"]);
|
|
3586
|
-
const result = await pending;
|
|
3587
|
-
assertStatus(result, "changed", "wake on append");
|
|
3588
|
-
assert(result.snapshot.currentOffset === OFFSET_1, "snapshot reflects the append");
|
|
3589
|
-
});
|
|
3590
|
-
harness.it("awaitChange wakes a parked waiter on a close transition", async () => {
|
|
3591
|
-
const adapter = await makeAdapter();
|
|
3592
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3593
|
-
await createStream(adapter, "s");
|
|
3594
|
-
const record = await currentRecord(adapter, "s");
|
|
3595
|
-
const pending = awaitChange("s", {
|
|
3596
|
-
fromOffset: record.currentOffset,
|
|
3597
|
-
observedClosed: false,
|
|
3598
|
-
observedSoftDeleted: false,
|
|
3599
|
-
timeoutMs: 2e3
|
|
3600
|
-
});
|
|
3601
|
-
await tick();
|
|
3602
|
-
const closed = await adapter.append("s", {
|
|
3603
|
-
preconditions: {
|
|
3604
|
-
expectedOffset: record.currentOffset,
|
|
3605
|
-
expectedClosed: false
|
|
3606
|
-
},
|
|
3607
|
-
messages: [],
|
|
3608
|
-
recordPatch: { lifecycle: {
|
|
3609
|
-
closed: true,
|
|
3610
|
-
closedAt: 0
|
|
3611
|
-
} }
|
|
3612
|
-
});
|
|
3613
|
-
assertStatus(closed, "appended", "close append");
|
|
3614
|
-
const result = await pending;
|
|
3615
|
-
assertStatus(result, "changed", "wake on close");
|
|
3616
|
-
assert(result.snapshot.closed === true, "snapshot reports closed");
|
|
3617
|
-
});
|
|
3618
|
-
harness.it("awaitChange wakes a parked waiter on a soft-delete transition", async () => {
|
|
3619
|
-
const adapter = await makeAdapter();
|
|
3620
|
-
if (!adapter.fork) return;
|
|
3621
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3622
|
-
await createStream(adapter, "parent");
|
|
3623
|
-
const forked = await adapter.fork({
|
|
3624
|
-
child: newRecord("child", "parent"),
|
|
3625
|
-
sourceId: "parent",
|
|
3626
|
-
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3627
|
-
});
|
|
3628
|
-
assertStatus(forked, "created", "fork child");
|
|
3629
|
-
const record = await currentRecord(adapter, "parent");
|
|
3630
|
-
const pending = awaitChange("parent", {
|
|
3631
|
-
fromOffset: record.currentOffset,
|
|
3632
|
-
observedClosed: false,
|
|
3633
|
-
observedSoftDeleted: false,
|
|
3634
|
-
timeoutMs: 2e3
|
|
3635
|
-
});
|
|
3636
|
-
await tick();
|
|
3637
|
-
const deleted = await adapter.delete({
|
|
3638
|
-
streamId: "parent",
|
|
3639
|
-
reason: "delete"
|
|
3640
|
-
});
|
|
3641
|
-
assertStatus(deleted, "retained-soft-deleted", "soft delete parent");
|
|
3642
|
-
const result = await pending;
|
|
3643
|
-
assertStatus(result, "changed", "wake on soft-delete");
|
|
3644
|
-
assert(result.snapshot.softDeleted === true, "snapshot reports soft-deleted");
|
|
3645
|
-
});
|
|
3646
|
-
harness.it("awaitChange wakes a parked waiter on a purge", async () => {
|
|
3647
|
-
const adapter = await makeAdapter();
|
|
3648
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3649
|
-
await createStream(adapter, "s");
|
|
3650
|
-
const record = await currentRecord(adapter, "s");
|
|
3651
|
-
const pending = awaitChange("s", {
|
|
3652
|
-
fromOffset: record.currentOffset,
|
|
3653
|
-
observedClosed: false,
|
|
3654
|
-
observedSoftDeleted: false,
|
|
3655
|
-
timeoutMs: 2e3
|
|
3656
|
-
});
|
|
3657
|
-
await tick();
|
|
3658
|
-
const deleted = await adapter.delete({
|
|
3659
|
-
streamId: "s",
|
|
3660
|
-
reason: "delete"
|
|
3661
|
-
});
|
|
3662
|
-
assertStatus(deleted, "purged", "purge");
|
|
3663
|
-
const result = await pending;
|
|
3664
|
-
assertStatus(result, "changed", "wake on purge");
|
|
3665
|
-
assert(result.snapshot.present === false, "snapshot reports the record gone");
|
|
3666
|
-
});
|
|
3667
|
-
harness.it("awaitChange treats an offset regression (purge then re-create) as changed", async () => {
|
|
3668
|
-
const adapter = await makeAdapter();
|
|
3669
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3670
|
-
await createStream(adapter, "s");
|
|
3671
|
-
await appendTexts(adapter, "s", ["a", "b"]);
|
|
3672
|
-
const parked = await currentRecord(adapter, "s");
|
|
3673
|
-
const deleted = await adapter.delete({
|
|
3674
|
-
streamId: "s",
|
|
3675
|
-
reason: "delete"
|
|
3676
|
-
});
|
|
3677
|
-
assertStatus(deleted, "purged", "purge");
|
|
3678
|
-
await createStream(adapter, "s");
|
|
3679
|
-
const result = await awaitChange("s", {
|
|
3680
|
-
fromOffset: parked.currentOffset,
|
|
3681
|
-
observedClosed: false,
|
|
3682
|
-
observedSoftDeleted: false,
|
|
3683
|
-
timeoutMs: 200
|
|
3684
|
-
});
|
|
3685
|
-
assertStatus(result, "changed", "offset regression detected");
|
|
3686
|
-
assert(result.snapshot.currentOffset === ZERO_OFFSET, "snapshot shows the new incarnation");
|
|
3687
|
-
});
|
|
3688
|
-
harness.it("awaitChange survives the lost-notify race (a commit before registration)", async () => {
|
|
3689
|
-
const adapter = await makeAdapter();
|
|
3690
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3691
|
-
await createStream(adapter, "s");
|
|
3692
|
-
await appendTexts(adapter, "s", ["a"]);
|
|
3693
|
-
const result = await awaitChange("s", {
|
|
3694
|
-
fromOffset: ZERO_OFFSET,
|
|
3695
|
-
observedClosed: false,
|
|
3696
|
-
observedSoftDeleted: false,
|
|
3697
|
-
timeoutMs: 200
|
|
3698
|
-
});
|
|
3699
|
-
assertStatus(result, "changed", "lost-notify re-check");
|
|
3700
|
-
assert(result.snapshot.currentOffset === OFFSET_1, "re-read caught the missed commit");
|
|
3701
|
-
});
|
|
3702
|
-
harness.it("awaitChange ignores a non-advancing wake and resolves on the real advance", async () => {
|
|
3703
|
-
const adapter = await makeAdapter();
|
|
3704
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3705
|
-
await createStream(adapter, "s");
|
|
3706
|
-
const parked = await currentRecord(adapter, "s");
|
|
3707
|
-
const pending = awaitChange("s", {
|
|
3708
|
-
fromOffset: parked.currentOffset,
|
|
3709
|
-
observedClosed: false,
|
|
3710
|
-
observedSoftDeleted: false,
|
|
3711
|
-
timeoutMs: 4e3
|
|
3712
|
-
});
|
|
3713
|
-
await tick();
|
|
3714
|
-
const touched = await adapter.append("s", {
|
|
3715
|
-
preconditions: {
|
|
3716
|
-
expectedOffset: parked.currentOffset,
|
|
3717
|
-
expectedClosed: false
|
|
3718
|
-
},
|
|
3719
|
-
recordPatch: { lifecycle: { expiresAtMs: 1e6 } }
|
|
3720
|
-
});
|
|
3721
|
-
assertStatus(touched, "appended", "touch");
|
|
3722
|
-
assert(await staysPending(pending, 60), "waiter did not resolve on a non-advancing wake");
|
|
3723
|
-
await appendTexts(adapter, "s", ["a"]);
|
|
3724
|
-
const result = await pending;
|
|
3725
|
-
assertStatus(result, "changed", "resolve on real advance");
|
|
3726
|
-
assert(result.snapshot.currentOffset === OFFSET_1, "snapshot reflects the advance");
|
|
3727
|
-
});
|
|
3728
|
-
}
|
|
3729
|
-
function runLifecycleContract(makeAdapter, harness) {
|
|
3730
|
-
harness.it("create is idempotent (second create returns 'exists')", async () => {
|
|
3731
|
-
const adapter = await makeAdapter();
|
|
3732
|
-
const created = await adapter.create({ record: newRecord("s") });
|
|
3733
|
-
assertStatus(created, "created", "first create");
|
|
3734
|
-
const again = await adapter.create({ record: newRecord("s") });
|
|
3735
|
-
assertStatus(again, "exists", "second create");
|
|
3736
|
-
assert(again.status === "exists" && again.record.id === "s", "exists returns the record");
|
|
3737
|
-
});
|
|
3738
|
-
harness.it("create persists a record that arrives already closed", async () => {
|
|
3739
|
-
const adapter = await makeAdapter();
|
|
3740
|
-
const closedRecord = {
|
|
3741
|
-
...newRecord("s"),
|
|
3742
|
-
lifecycle: {
|
|
3743
|
-
closed: true,
|
|
3744
|
-
closedAt: 0
|
|
3745
|
-
}
|
|
3746
|
-
};
|
|
3747
|
-
const created = await adapter.create({ record: closedRecord });
|
|
3748
|
-
assertStatus(created, "created", "create closed record");
|
|
3749
|
-
const record = await currentRecord(adapter, "s");
|
|
3750
|
-
assert(record.lifecycle.closed === true, "stream created closed");
|
|
3751
|
-
assert(record.lifecycle.closedAt === 0, "closedAt persisted");
|
|
3752
|
-
});
|
|
3753
|
-
harness.it("fork is capability-by-presence: omitting it is a valid, unsupported configuration", async () => {
|
|
3754
|
-
const adapter = await makeAdapter();
|
|
3755
|
-
if (adapter.fork === void 0) {
|
|
3756
|
-
assert(typeof adapter.create === "function" && typeof adapter.delete === "function", "a forkless adapter still provides the required create/delete intents");
|
|
3757
|
-
return;
|
|
3758
|
-
}
|
|
3759
|
-
assert(typeof adapter.fork === "function", "fork capability is a callable method when present");
|
|
3760
|
-
});
|
|
3761
|
-
harness.it("fork creates a child and is idempotent; a missing source is 'fork-source-gone'", async () => {
|
|
3762
|
-
const adapter = await makeAdapter();
|
|
3763
|
-
if (!adapter.fork) return;
|
|
3764
|
-
await createStream(adapter, "parent");
|
|
3765
|
-
const forked = await adapter.fork({
|
|
3766
|
-
child: newRecord("child", "parent"),
|
|
3767
|
-
sourceId: "parent",
|
|
3768
|
-
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3769
|
-
});
|
|
3770
|
-
assertStatus(forked, "created", "fork");
|
|
3771
|
-
assert(await adapter.getRecord("child") !== null, "child materialized");
|
|
3772
|
-
const again = await adapter.fork({
|
|
3773
|
-
child: newRecord("child", "parent"),
|
|
3774
|
-
sourceId: "parent",
|
|
3775
|
-
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3776
|
-
});
|
|
3777
|
-
assertStatus(again, "exists", "idempotent fork");
|
|
3778
|
-
assert(again.status === "exists" && again.record.id === "child", "fork exists returns the existing child record");
|
|
3779
|
-
assert(again.status === "exists" && again.record.lifecycle.forkedFrom === "parent", "existing child record carries its lineage");
|
|
3780
|
-
const gone = await adapter.fork({
|
|
3781
|
-
child: newRecord("orphan", "missing"),
|
|
3782
|
-
sourceId: "missing",
|
|
3783
|
-
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3784
|
-
});
|
|
3785
|
-
assertStatus(gone, "fork-source-gone", "missing source");
|
|
3786
|
-
});
|
|
3787
|
-
harness.it("delete purges a stream with no dependents", async () => {
|
|
3788
|
-
const adapter = await makeAdapter();
|
|
3789
|
-
await createStream(adapter, "s");
|
|
3790
|
-
const deleted = await adapter.delete({
|
|
3791
|
-
streamId: "s",
|
|
3792
|
-
reason: "delete"
|
|
3793
|
-
});
|
|
3794
|
-
assertStatus(deleted, "purged", "purge");
|
|
3795
|
-
assert(await adapter.getRecord("s") === null, "record gone after purge");
|
|
3796
|
-
});
|
|
3797
|
-
harness.it("delete is 'not-found' for an absent stream", async () => {
|
|
3798
|
-
const adapter = await makeAdapter();
|
|
3799
|
-
const deleted = await adapter.delete({
|
|
3800
|
-
streamId: "missing",
|
|
3801
|
-
reason: "delete"
|
|
3802
|
-
});
|
|
3803
|
-
assertStatus(deleted, "not-found", "not-found");
|
|
3804
|
-
});
|
|
3805
|
-
harness.it("delete soft-deletes an ancestor with dependents, then cascade-purges", async () => {
|
|
3806
|
-
const adapter = await makeAdapter();
|
|
3807
|
-
if (!adapter.fork) return;
|
|
3808
|
-
await createStream(adapter, "parent");
|
|
3809
|
-
const forked = await adapter.fork({
|
|
3810
|
-
child: newRecord("child", "parent"),
|
|
3811
|
-
sourceId: "parent",
|
|
3812
|
-
precondition: { sourceLiveAtOffset: ZERO_OFFSET }
|
|
3813
|
-
});
|
|
3814
|
-
assertStatus(forked, "created", "fork child");
|
|
3815
|
-
const retained = await adapter.delete({
|
|
3816
|
-
streamId: "parent",
|
|
3817
|
-
reason: "delete"
|
|
3818
|
-
});
|
|
3819
|
-
assertStatus(retained, "retained-soft-deleted", "soft delete parent");
|
|
3820
|
-
assert((await adapter.getRecord("parent"))?.lifecycle.softDeleted === true, "parent soft-deleted");
|
|
3821
|
-
const gone = await adapter.delete({
|
|
3822
|
-
streamId: "parent",
|
|
3823
|
-
reason: "delete"
|
|
3824
|
-
});
|
|
3825
|
-
assertStatus(gone, "gone", "re-delete soft-deleted ancestor");
|
|
3826
|
-
const purged = await adapter.delete({
|
|
3827
|
-
streamId: "child",
|
|
3828
|
-
reason: "delete"
|
|
3829
|
-
});
|
|
3830
|
-
assertStatus(purged, "purged", "purge child");
|
|
3831
|
-
assert(await adapter.getRecord("child") === null, "child gone");
|
|
3832
|
-
assert(await adapter.getRecord("parent") === null, "parent cascade-purged");
|
|
3833
|
-
});
|
|
3834
|
-
}
|
|
3835
|
-
function runCancellationContract(makeAdapter, harness) {
|
|
3836
|
-
harness.it("raceAbortAwaitChange resolves timeout-shaped on caller abort without rejecting", async () => {
|
|
3837
|
-
const adapter = await makeAdapter();
|
|
3838
|
-
const awaitChange = awaitChangeFor(adapter);
|
|
3839
|
-
await createStream(adapter, "s");
|
|
3840
|
-
const record = await currentRecord(adapter, "s");
|
|
3841
|
-
const fallback = buildChangeSnapshot(record);
|
|
3842
|
-
const controller = new AbortController();
|
|
3843
|
-
const wait = awaitChange("s", {
|
|
3844
|
-
fromOffset: record.currentOffset,
|
|
3845
|
-
observedClosed: false,
|
|
3846
|
-
observedSoftDeleted: false,
|
|
3847
|
-
timeoutMs: 150
|
|
3848
|
-
});
|
|
3849
|
-
const raced = raceAbortAwaitChange(wait, fallback, controller.signal);
|
|
3850
|
-
controller.abort();
|
|
3851
|
-
const result = await raced;
|
|
3852
|
-
assertStatus(result, "timeout", "aborted race");
|
|
3853
|
-
assert(result.snapshot === fallback, "abort surfaces the caller's fallback snapshot");
|
|
3854
|
-
await wait;
|
|
3855
|
-
});
|
|
3856
|
-
}
|
|
3857
|
-
/**
|
|
3858
|
-
* Register the full storage-adapter contract against `makeAdapter` using the
|
|
3859
|
-
* provided test harness. Wrap in the caller's own `describe` for grouping:
|
|
3860
|
-
*
|
|
3861
|
-
* ```ts
|
|
3862
|
-
* import { it } from "vitest";
|
|
3863
|
-
* describe("memory adapter contract", () => {
|
|
3864
|
-
* runStorageAdapterContract(() => createMemoryStorageAdapter(), { it });
|
|
3865
|
-
* });
|
|
3866
|
-
* ```
|
|
3867
|
-
*/
|
|
3868
|
-
function runStorageAdapterContract(makeAdapter, harness) {
|
|
3869
|
-
const make = serialized(makeAdapter);
|
|
3870
|
-
runAppendContract(make, harness);
|
|
3871
|
-
runReadContract(make, harness);
|
|
3872
|
-
runAwaitChangeContract(make, harness);
|
|
3873
|
-
runLifecycleContract(make, harness);
|
|
3874
|
-
runCancellationContract(make, harness);
|
|
3875
|
-
}
|
|
3876
|
-
|
|
110
|
+
//#region src/streamsy.ts
|
|
111
|
+
var streamsy_exports = /* @__PURE__ */ __exportAll({
|
|
112
|
+
Wildcard: () => Wildcard,
|
|
113
|
+
bytes: () => bytes,
|
|
114
|
+
custom: () => custom,
|
|
115
|
+
group: () => group,
|
|
116
|
+
json: () => json,
|
|
117
|
+
state: () => state
|
|
118
|
+
});
|
|
3877
119
|
//#endregion
|
|
3878
|
-
export {
|
|
120
|
+
export { AppendConflict, AppendResult, ChangeSnapshot, CommitBoundary, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_exports as Producer, ProducerGap, ProducerId, ProducerPrecondition, ProducerState, RecordPatch, StaleEpoch, Storage, StorageCapabilities, StorageFault, StoredMessage, address_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
|