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