@streamsy/core 0.1.0 → 0.2.1

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +643 -91
  2. package/dist/index.js +2228 -541
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,92 +1,4 @@
1
- //#region src/protocol/helpers/clock.ts
2
- const systemClock = {
3
- now: () => Date.now(),
4
- date: (value) => new Date(value ?? Date.now())
5
- };
6
-
7
- //#endregion
8
- //#region src/protocol/helpers/producer-idempotency-service.ts
9
- function validateProducer(state, epoch, seq) {
10
- if (!state) return seq === 0 ? {
11
- kind: "accepted",
12
- proposedState: {
13
- epoch,
14
- lastSeq: 0
15
- }
16
- } : {
17
- kind: "gap",
18
- expectedSeq: 0,
19
- receivedSeq: seq
20
- };
21
- if (epoch < state.epoch) return {
22
- kind: "stale-epoch",
23
- currentEpoch: state.epoch
24
- };
25
- if (epoch > state.epoch) return seq === 0 ? {
26
- kind: "accepted",
27
- proposedState: {
28
- epoch,
29
- lastSeq: 0
30
- }
31
- } : { kind: "invalid-epoch-seq" };
32
- if (seq <= state.lastSeq) return {
33
- kind: "duplicate",
34
- lastSeq: state.lastSeq,
35
- epoch: state.epoch
36
- };
37
- if (seq === state.lastSeq + 1) return {
38
- kind: "accepted",
39
- proposedState: {
40
- epoch,
41
- lastSeq: seq
42
- }
43
- };
44
- return {
45
- kind: "gap",
46
- expectedSeq: state.lastSeq + 1,
47
- receivedSeq: seq
48
- };
49
- }
50
- function rejectionToAppendResult(rejection, currentOffset, isClosed) {
51
- switch (rejection.kind) {
52
- case "duplicate": return {
53
- status: "duplicate",
54
- offset: currentOffset,
55
- producerEpoch: rejection.epoch,
56
- producerSeq: rejection.lastSeq,
57
- closed: isClosed
58
- };
59
- case "stale-epoch": return {
60
- status: "stale-epoch",
61
- currentEpoch: rejection.currentEpoch
62
- };
63
- case "gap": return {
64
- status: "producer-gap",
65
- expectedSeq: rejection.expectedSeq,
66
- receivedSeq: rejection.receivedSeq
67
- };
68
- case "invalid-epoch-seq": return { status: "invalid-epoch-seq" };
69
- }
70
- }
71
- var ProducerIdempotencyService = class {
72
- constructor(deps) {
73
- this.deps = deps;
74
- }
75
- load(producerId) {
76
- return this.deps.store.getProducerState(producerId);
77
- }
78
- validate(state, epoch, seq) {
79
- return validateProducer(state, epoch, seq);
80
- }
81
- async persistIfAccepted(producer, validation) {
82
- if (!producer || validation?.kind !== "accepted") return void 0;
83
- await this.deps.store.setProducerState(producer.producerId, validation.proposedState);
84
- return void 0;
85
- }
86
- };
87
-
88
- //#endregion
89
- //#region src/types/factory.ts
1
+ //#region src/types/storage-adapter.ts
90
2
  /** Internal/storage-level unsupported-feature error. */
91
3
  var NotSupportedError = class extends Error {
92
4
  constructor(feature, message) {
@@ -125,6 +37,13 @@ function isNotSupported(value) {
125
37
  return status === "not-supported";
126
38
  }
127
39
 
40
+ //#endregion
41
+ //#region src/protocol/helpers/clock.ts
42
+ const systemClock = {
43
+ now: () => Date.now(),
44
+ date: (value) => new Date(value ?? Date.now())
45
+ };
46
+
128
47
  //#endregion
129
48
  //#region src/protocol/helpers/content-type-matcher.ts
130
49
  /**
@@ -139,7 +58,7 @@ function isNotSupported(value) {
139
58
  *
140
59
  * Used by `AppendService` for append content-type conflicts, by
141
60
  * `CreateStreamService` via `configMatches` for idempotent create checks, and
142
- * by `ForkService` for fork content-type compatibility.
61
+ * by `ForkPlanBuilder` for fork content-type compatibility.
143
62
  */
144
63
  function normalizeContentType(ct) {
145
64
  return ct.toLowerCase().split(";")[0].trim();
@@ -165,7 +84,7 @@ function contentTypeMatches(expected, actual) {
165
84
  * without parameter stripping.
166
85
  * - Invalid JSON propagates the underlying `JSON.parse` error.
167
86
  *
168
- * Used by `AppendService`, `CreateStreamService`, and `ForkService` before
87
+ * Used by `AppendService`, `CreateStreamService`, and `ForkPlanBuilder` before
169
88
  * incoming request bodies are persisted as stored messages.
170
89
  */
171
90
  function frameMessages(data, contentType) {
@@ -175,14 +94,131 @@ function frameMessages(data, contentType) {
175
94
  return [new TextEncoder().encode(JSON.stringify(parsed))];
176
95
  }
177
96
 
97
+ //#endregion
98
+ //#region src/protocol/helpers/offset-generator.ts
99
+ const ZERO_OFFSET = `${"0".repeat(16)}_${"0".repeat(16)}`;
100
+ const FIXED_WIDTH_OFFSET_REGEX = /^\d{16}_\d{16}$/;
101
+ const FORBIDDEN_OFFSET_CHARACTERS = /[,&=?/]/;
102
+ /** Protocol-level constraints that apply to every generated offset scheme. */
103
+ function isSafeOffsetToken(offset) {
104
+ return offset.length > 0 && offset.length < 256 && offset !== "-1" && offset !== "now" && !FORBIDDEN_OFFSET_CHARACTERS.test(offset);
105
+ }
106
+ function isValidOffset(generator, offset) {
107
+ return isSafeOffsetToken(offset) && generator.isValid(offset);
108
+ }
109
+ function compareOffsets(a, b) {
110
+ return a === b ? 0 : a < b ? -1 : 1;
111
+ }
112
+ function formatCounter(counter) {
113
+ return `${String(counter).padStart(16, "0")}_${"0".repeat(16)}`;
114
+ }
115
+ function parseCounter(offset) {
116
+ return parseInt(offset.split("_")[0] ?? "0", 10);
117
+ }
118
+ /** The backwards-compatible fixed-width counter generator used by default. */
119
+ const defaultOffsetGenerator = Object.freeze({
120
+ initialOffset: ZERO_OFFSET,
121
+ isValid(offset) {
122
+ return FIXED_WIDTH_OFFSET_REGEX.test(offset);
123
+ },
124
+ next(previous) {
125
+ return formatCounter(parseCounter(previous) + 1);
126
+ }
127
+ });
128
+ var InvalidGeneratedOffsetError = class extends Error {
129
+ constructor(message) {
130
+ super(message);
131
+ this.name = "InvalidGeneratedOffsetError";
132
+ }
133
+ };
134
+ /** Allocate a batch without interpreting the generator's opaque offset format. */
135
+ function allocate(generator, previousOffset, counter, count) {
136
+ const offsets = [];
137
+ let previous = previousOffset;
138
+ for (let i = 0; i < count; i++) {
139
+ const next = generator.next(previous);
140
+ if (!isValidOffset(generator, next)) throw new InvalidGeneratedOffsetError(`Offset generator returned an invalid token: ${next}`);
141
+ if (compareOffsets(next, previous) <= 0) throw new InvalidGeneratedOffsetError(`Offset generator did not advance lexicographically: ${previous} -> ${next}`);
142
+ offsets.push(next);
143
+ previous = next;
144
+ }
145
+ return {
146
+ endCounter: counter + count,
147
+ offsets,
148
+ nextOffset: previous
149
+ };
150
+ }
151
+ function assertValidOffsetGenerator(generator) {
152
+ if (!isValidOffset(generator, generator.initialOffset)) throw new InvalidGeneratedOffsetError("Offset generator has an invalid initialOffset");
153
+ }
154
+
155
+ //#endregion
156
+ //#region src/protocol/helpers/producer-idempotency-service.ts
157
+ function validateProducer(state, epoch, seq) {
158
+ if (!state) return seq === 0 ? {
159
+ kind: "accepted",
160
+ proposedState: {
161
+ epoch,
162
+ lastSeq: 0
163
+ }
164
+ } : {
165
+ kind: "gap",
166
+ expectedSeq: 0,
167
+ receivedSeq: seq
168
+ };
169
+ if (epoch < state.epoch) return {
170
+ kind: "stale-epoch",
171
+ currentEpoch: state.epoch
172
+ };
173
+ if (epoch > state.epoch) return seq === 0 ? {
174
+ kind: "accepted",
175
+ proposedState: {
176
+ epoch,
177
+ lastSeq: 0
178
+ }
179
+ } : { kind: "invalid-epoch-seq" };
180
+ if (seq <= state.lastSeq) return {
181
+ kind: "duplicate",
182
+ lastSeq: state.lastSeq,
183
+ epoch: state.epoch
184
+ };
185
+ if (seq === state.lastSeq + 1) return {
186
+ kind: "accepted",
187
+ proposedState: {
188
+ epoch,
189
+ lastSeq: seq
190
+ }
191
+ };
192
+ return {
193
+ kind: "gap",
194
+ expectedSeq: state.lastSeq + 1,
195
+ receivedSeq: seq
196
+ };
197
+ }
198
+ function rejectionToAppendResult(rejection, currentOffset, isClosed) {
199
+ switch (rejection.kind) {
200
+ case "duplicate": return {
201
+ status: "duplicate",
202
+ offset: currentOffset,
203
+ producerEpoch: rejection.epoch,
204
+ producerSeq: rejection.lastSeq,
205
+ closed: isClosed
206
+ };
207
+ case "stale-epoch": return {
208
+ status: "stale-epoch",
209
+ currentEpoch: rejection.currentEpoch
210
+ };
211
+ case "gap": return {
212
+ status: "producer-gap",
213
+ expectedSeq: rejection.expectedSeq,
214
+ receivedSeq: rejection.receivedSeq
215
+ };
216
+ case "invalid-epoch-seq": return { status: "invalid-epoch-seq" };
217
+ }
218
+ }
219
+
178
220
  //#endregion
179
221
  //#region src/protocol/append-service.ts
180
- /**
181
- * Mutators return the stream's post-mutation tail offset: the offset of the
182
- * last message they wrote (or the unchanged tail for a body-less close). That
183
- * value is both the exact appended offset and, because reads are
184
- * after-exclusive, the read cursor.
185
- */
186
222
  function appendedResult(offset, validation, closed) {
187
223
  if (validation?.kind === "accepted") return {
188
224
  status: "appended",
@@ -197,18 +233,6 @@ function appendedResult(offset, validation, closed) {
197
233
  closed
198
234
  };
199
235
  }
200
- /**
201
- * Compare-and-swap precondition for optimistic concurrency: when
202
- * `expectedOffset` is set, the append proceeds only if the stream's tail
203
- * still equals it. Atomicity with the mutation is guaranteed because the
204
- * protocol loads the record and runs this service inside the per-stream
205
- * mutation lock.
206
- *
207
- * Pinned precedence: checked after the closed/content-type/sequence conflicts
208
- * and before any mutation, so a CAS failure never advances producer state.
209
- * A close-only append on an already-closed stream stays an idempotent
210
- * success and skips the check (nothing is written, so no update can be lost).
211
- */
212
236
  function expectedOffsetConflict(record, options) {
213
237
  if (options.expectedOffset === void 0 || options.expectedOffset === record.currentOffset) return null;
214
238
  return {
@@ -221,83 +245,116 @@ var AppendService = class {
221
245
  constructor(deps) {
222
246
  this.deps = deps;
223
247
  }
224
- async execute(record, options) {
225
- if (!record) return { status: "not-found" };
226
- if (record.lifecycle.softDeleted) return { status: "gone" };
248
+ plan(record, options, producerState) {
249
+ if (!record) return {
250
+ kind: "terminal",
251
+ result: { status: "not-found" }
252
+ };
253
+ if (record.lifecycle.softDeleted) return {
254
+ kind: "terminal",
255
+ result: { status: "gone" }
256
+ };
227
257
  const isClosed = record.lifecycle.closed === true;
228
258
  const wantClose = options.close === true;
229
259
  const hasBody = options.data.byteLength > 0;
230
260
  let producerValidation;
231
261
  if (options.producer) {
232
- const state = await this.deps.producerIdempotency.load(options.producer.producerId);
233
- if (isNotSupported(state)) return state;
234
- producerValidation = this.deps.producerIdempotency.validate(state, options.producer.producerEpoch, options.producer.producerSeq);
235
- if (producerValidation.kind !== "accepted") return rejectionToAppendResult(producerValidation, record.currentOffset, isClosed);
262
+ producerValidation = validateProducer(producerState, options.producer.producerEpoch, options.producer.producerSeq);
263
+ if (producerValidation.kind !== "accepted") return {
264
+ kind: "terminal",
265
+ result: rejectionToAppendResult(producerValidation, record.currentOffset, isClosed)
266
+ };
236
267
  }
237
268
  if (wantClose && !hasBody) {
238
269
  if (isClosed) return {
239
- status: "appended",
240
- offset: record.currentOffset,
241
- closed: true
270
+ kind: "terminal",
271
+ result: {
272
+ status: "appended",
273
+ offset: record.currentOffset,
274
+ closed: true
275
+ }
242
276
  };
243
277
  const casConflict$1 = expectedOffsetConflict(record, options);
244
- if (casConflict$1) return casConflict$1;
245
- const nextOffset$1 = await this.deps.mutators.closeRecord(record, [], options.seq);
246
- const persisted$1 = await this.deps.producerIdempotency.persistIfAccepted(options.producer, producerValidation);
247
- if (persisted$1?.status === "not-supported") return persisted$1;
248
- return appendedResult(nextOffset$1, producerValidation, true);
278
+ if (casConflict$1) return {
279
+ kind: "terminal",
280
+ result: casConflict$1
281
+ };
282
+ return this.commitDecision(record, [], options, producerState, producerValidation, true);
249
283
  }
250
284
  if (isClosed) return {
251
- status: "conflict",
252
- conflictReason: "closed",
253
- closed: true,
254
- offset: record.currentOffset
285
+ kind: "terminal",
286
+ result: {
287
+ status: "conflict",
288
+ conflictReason: "closed",
289
+ closed: true,
290
+ offset: record.currentOffset
291
+ }
255
292
  };
256
293
  if (!contentTypeMatches(record.config.contentType, options.contentType)) return {
257
- status: "conflict",
258
- conflictReason: "content-type"
294
+ kind: "terminal",
295
+ result: {
296
+ status: "conflict",
297
+ conflictReason: "content-type"
298
+ }
259
299
  };
260
300
  if (options.seq && record.lifecycle.lastSeq && options.seq <= record.lifecycle.lastSeq) return {
261
- status: "conflict",
262
- conflictReason: "sequence"
301
+ kind: "terminal",
302
+ result: {
303
+ status: "conflict",
304
+ conflictReason: "sequence"
305
+ }
263
306
  };
264
307
  const casConflict = expectedOffsetConflict(record, options);
265
- if (casConflict) return casConflict;
308
+ if (casConflict) return {
309
+ kind: "terminal",
310
+ result: casConflict
311
+ };
266
312
  const processed = frameMessages(options.data, record.config.contentType);
267
- const nextOffset = wantClose ? await this.deps.mutators.closeRecord(record, processed, options.seq) : await this.deps.mutators.appendMessages(record, processed, options.seq);
268
- const persisted = await this.deps.producerIdempotency.persistIfAccepted(options.producer, producerValidation);
269
- if (persisted?.status === "not-supported") return persisted;
270
- return appendedResult(nextOffset, producerValidation, wantClose);
313
+ return this.commitDecision(record, processed, options, producerState, producerValidation, wantClose);
314
+ }
315
+ commitDecision(record, data, options, producerState, producerValidation, wantClose) {
316
+ const allocation = allocate(this.deps.offsets, record.currentOffset, record.counter, data.length);
317
+ const now = this.deps.clock.now();
318
+ const messages = data.map((bytes, i) => ({
319
+ data: bytes,
320
+ offset: allocation.offsets[i],
321
+ timestamp: now
322
+ }));
323
+ const expiresAtMs = record.config.ttlSeconds === void 0 ? void 0 : now + record.config.ttlSeconds * 1e3;
324
+ const lifecycle = {
325
+ ...options.seq ? { lastSeq: options.seq } : {},
326
+ ...wantClose ? {
327
+ closed: true,
328
+ closedAt: now
329
+ } : {},
330
+ ...expiresAtMs !== void 0 ? { expiresAtMs } : {}
331
+ };
332
+ const plan = {
333
+ preconditions: {
334
+ expectedOffset: options.expectedOffset ?? record.currentOffset,
335
+ expectedClosed: false,
336
+ ...options.producer && producerValidation?.kind === "accepted" ? { producer: {
337
+ producerId: options.producer.producerId,
338
+ expected: producerState,
339
+ next: producerValidation.proposedState
340
+ } } : {}
341
+ },
342
+ messages,
343
+ recordPatch: {
344
+ currentOffset: allocation.nextOffset,
345
+ counter: allocation.endCounter,
346
+ lifecycle
347
+ }
348
+ };
349
+ return {
350
+ kind: "append",
351
+ plan,
352
+ afterCommit: expiresAtMs !== void 0 ? { scheduleExpiryAt: expiresAtMs } : {},
353
+ toResult: () => appendedResult(allocation.nextOffset, producerValidation, wantClose)
354
+ };
271
355
  }
272
356
  };
273
357
 
274
- //#endregion
275
- //#region src/protocol/helpers/offset-generator.ts
276
- const ZERO_OFFSET = `${"0".repeat(16)}_${"0".repeat(16)}`;
277
- const OFFSET_REGEX = /^\d{1,16}_\d{1,16}$/;
278
- function isValidOffset(offset) {
279
- return OFFSET_REGEX.test(offset);
280
- }
281
- function compareOffsets(a, b) {
282
- return a === b ? 0 : a < b ? -1 : 1;
283
- }
284
- function formatCounter(counter) {
285
- return `${String(counter).padStart(16, "0")}_${"0".repeat(16)}`;
286
- }
287
- function parseCounter(offset) {
288
- return parseInt(offset.split("_")[0] ?? "0", 10);
289
- }
290
- function allocate(counter, count) {
291
- const offsets = [];
292
- for (let i = 1; i <= count; i++) offsets.push(formatCounter(counter + i));
293
- const endCounter = counter + count;
294
- return {
295
- endCounter,
296
- offsets,
297
- nextOffset: count > 0 ? formatCounter(endCounter) : formatCounter(counter)
298
- };
299
- }
300
-
301
358
  //#endregion
302
359
  //#region src/protocol/read-service.ts
303
360
  function normalizeReadOffset(offset) {
@@ -336,6 +393,32 @@ function generateCursor(clock, previous, random = Math.random) {
336
393
  return String(previousInterval + Math.max(1, Math.floor(random() * 180)));
337
394
  }
338
395
 
396
+ //#endregion
397
+ //#region src/protocol/helpers/race-abort.ts
398
+ function raceAbortAwaitChange(wait, fallbackSnapshot, signal) {
399
+ if (!signal) return wait;
400
+ const timeoutResult = {
401
+ status: "timeout",
402
+ snapshot: fallbackSnapshot
403
+ };
404
+ if (signal.aborted) return Promise.resolve(timeoutResult);
405
+ return new Promise((resolve, reject) => {
406
+ const onAbort = () => {
407
+ cleanup();
408
+ resolve(timeoutResult);
409
+ };
410
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
411
+ signal.addEventListener("abort", onAbort, { once: true });
412
+ wait.then((result) => {
413
+ cleanup();
414
+ resolve(result);
415
+ }, (error) => {
416
+ cleanup();
417
+ reject(error);
418
+ });
419
+ });
420
+ }
421
+
339
422
  //#endregion
340
423
  //#region src/protocol/live-read-service.ts
341
424
  var LiveReadService = class {
@@ -381,18 +464,26 @@ var LiveReadService = class {
381
464
  cursor: generateCursor(this.deps.clock, options.cursor)
382
465
  };
383
466
  }
384
- await this.deps.touch(record);
385
- const immediate = await this.deps.readOwn(options.offset);
467
+ const fromOffset = isValidOffset(this.deps.offsets, options.offset) ? options.offset : this.deps.offsets.initialOffset;
468
+ const immediate = await this.deps.readOwn(fromOffset);
386
469
  if (immediate.messages.length > 0) return {
387
470
  status: "ok",
388
471
  ...immediate,
389
472
  upToDate: true,
390
473
  cursor: generateCursor(this.deps.clock, options.cursor)
391
474
  };
392
- const wait = await this.deps.store.waitForEvent({
393
- timeoutMs: this.deps.longPollTimeoutMs,
394
- signal: options.signal
395
- });
475
+ const observed = {
476
+ present: true,
477
+ currentOffset: record.currentOffset,
478
+ closed: false,
479
+ softDeleted: false
480
+ };
481
+ const wait = await raceAbortAwaitChange(this.deps.store.awaitChange({
482
+ fromOffset,
483
+ observedClosed: observed.closed,
484
+ observedSoftDeleted: observed.softDeleted,
485
+ timeoutMs: this.deps.longPollTimeoutMs
486
+ }), observed, options.signal);
396
487
  const latest = await this.deps.store.getRecord();
397
488
  if (!latest) return {
398
489
  status: "not-found",
@@ -408,11 +499,11 @@ var LiveReadService = class {
408
499
  upToDate: false,
409
500
  cursor: ""
410
501
  };
411
- const r = await this.deps.readOwn(options.offset);
502
+ const r = await this.deps.readOwn(fromOffset);
412
503
  const reachedTail = r.nextOffset === latest.currentOffset;
413
504
  const hasMessages = r.messages.length > 0;
414
505
  return {
415
- status: hasMessages ? "ok" : wait.status === "timeout" || wait.status === "aborted" ? "timeout" : "ok",
506
+ status: hasMessages ? "ok" : wait.status === "timeout" ? "timeout" : "ok",
416
507
  messages: r.messages,
417
508
  nextOffset: r.nextOffset,
418
509
  upToDate: true,
@@ -422,6 +513,39 @@ var LiveReadService = class {
422
513
  }
423
514
  };
424
515
 
516
+ //#endregion
517
+ //#region src/protocol/helpers/bind-stream.ts
518
+ function bindStream(adapter, id) {
519
+ return {
520
+ id,
521
+ getRecord: () => adapter.getRecord(id),
522
+ listMessages: (options) => adapter.listMessages(id, options),
523
+ getProducerState: (producerId) => adapter.getProducerState(id, producerId),
524
+ append: (plan) => adapter.append(id, plan),
525
+ awaitChange: (options) => adapter.awaitChange(id, options),
526
+ scheduleExpiry: (at) => adapter.scheduleExpiry(id, at),
527
+ cancelExpiry: () => adapter.cancelExpiry(id)
528
+ };
529
+ }
530
+
531
+ //#endregion
532
+ //#region src/protocol/helpers/after-commit-effects.ts
533
+ /**
534
+ * Runtime effects that are safe to fire only after the durable mutation has
535
+ * committed. Storage adapters persist each intent atomically; core owns expiry
536
+ * scheduling so failed preconditions never fire timers.
537
+ *
538
+ * Waking live readers is not an after-commit effect: the level-triggered
539
+ * `awaitChange` seam re-reads durable state, so an adapter wakes its own waiters
540
+ * from inside a successful mutation (a pure latency optimization). Correctness
541
+ * never depends on a notification crossing the seam.
542
+ */
543
+ async function runAfterCommit(effects, storage) {
544
+ if (!effects) return;
545
+ if (effects.cancelExpiry) await storage.cancelExpiry();
546
+ else if (effects.scheduleExpiryAt !== void 0) await storage.scheduleExpiry(effects.scheduleExpiryAt);
547
+ }
548
+
425
549
  //#endregion
426
550
  //#region src/protocol/helpers/expiry-policy.ts
427
551
  var ExpiryPolicy = class {
@@ -434,17 +558,22 @@ var ExpiryPolicy = class {
434
558
  return void 0;
435
559
  }
436
560
  async touch(stream, record, reason) {
437
- if (record.config.ttlSeconds === void 0) return;
438
- if (reason === "live-read") return;
561
+ if (record.config.ttlSeconds === void 0) return record;
562
+ if (reason === "live-read") return record;
439
563
  const expiresAtMs = this.deps.clock.now() + record.config.ttlSeconds * 1e3;
440
- await stream.updateRecord({ lifecycle: { expiresAtMs } });
441
- await stream.scheduleExpiry(expiresAtMs, () => this.deps.onScheduledExpiry(stream.id));
564
+ const out = await stream.append({
565
+ preconditions: { expectedOffset: record.currentOffset },
566
+ recordPatch: { lifecycle: { expiresAtMs } }
567
+ });
568
+ if (out.status !== "appended") return record;
569
+ await runAfterCommit({ scheduleExpiryAt: expiresAtMs }, stream);
570
+ return out.record;
442
571
  }
443
572
  async scheduleExpiry(record) {
444
573
  const at = record.lifecycle.expiresAtMs;
445
574
  if (at !== void 0) {
446
575
  const stream = await this.deps.resolve(record.id);
447
- await stream.scheduleExpiry(at, () => this.deps.onScheduledExpiry(record.id));
576
+ await stream.scheduleExpiry(at);
448
577
  }
449
578
  }
450
579
  /**
@@ -475,6 +604,7 @@ function configMatches(existing, options) {
475
604
  if (!contentTypeMatches(existing.config.contentType, contentType)) return false;
476
605
  if ((options.forkedFrom ?? void 0) !== existing.lifecycle.forkedFrom) return false;
477
606
  if (options.forkOffset !== void 0 && options.forkOffset !== existing.lifecycle.forkOffset) return false;
607
+ if ((options.forkSubOffset ?? 0) !== (existing.lifecycle.forkSubOffset ?? 0)) return false;
478
608
  const inheritedForkExpiry = options.forkedFrom && options.ttlSeconds === void 0 && options.expiresAt === void 0;
479
609
  if (existing.config.ttlSeconds !== options.ttlSeconds && !inheritedForkExpiry) return false;
480
610
  if (existing.config.expiresAt !== options.expiresAt && !inheritedForkExpiry) return false;
@@ -487,27 +617,31 @@ var CreateStreamService = class {
487
617
  constructor(deps) {
488
618
  this.deps = deps;
489
619
  }
490
- async execute(record, options) {
491
- if (record) return this.resultForExisting(record, options);
492
- if (options.forkedFrom) return this.deps.mutators.createFork(options);
620
+ plan(record, options) {
621
+ if (record) return {
622
+ kind: "terminal",
623
+ result: this.resultForExisting(record, options)
624
+ };
625
+ if (options.forkedFrom) return { kind: "fork" };
493
626
  const contentType = options.contentType ?? "application/octet-stream";
494
- const initialMessages = options.initialData ? frameMessages(options.initialData, contentType) : [];
627
+ const initialMessages = this.initialMessages(options.initialData, contentType, this.deps.offsets.initialOffset, 0);
495
628
  const wantClosed = options.closed === true;
496
- const newRecord = this.deps.mutators.newRecord(contentType, options);
497
- const createResult = await this.deps.store.createRecord(newRecord);
498
- if (createResult.status === "exists") return this.resultForExisting(createResult.record, options);
499
- await this.deps.mutators.scheduleExpiry(newRecord);
500
- let final = newRecord.currentOffset;
501
- if (initialMessages.length > 0) final = await this.deps.mutators.appendMessages(newRecord, initialMessages);
502
- if (wantClosed) {
503
- const latest = await this.deps.store.getRecord() ?? newRecord;
504
- final = await this.deps.mutators.closeRecord(latest, []);
505
- }
629
+ const newRecord$1 = this.deps.newRecord(contentType, options);
630
+ const finalRecord = this.withInitialTail(newRecord$1, initialMessages, wantClosed);
631
+ const plan = {
632
+ record: finalRecord,
633
+ initialMessages
634
+ };
506
635
  return {
507
- status: "created",
508
- nextOffset: final,
509
- contentType,
510
- closed: wantClosed
636
+ kind: "create",
637
+ plan,
638
+ afterCommit: finalRecord.lifecycle.expiresAtMs !== void 0 ? { scheduleExpiryAt: finalRecord.lifecycle.expiresAtMs } : {},
639
+ toResult: (created) => ({
640
+ status: "created",
641
+ nextOffset: created.currentOffset,
642
+ contentType,
643
+ closed: wantClosed
644
+ })
511
645
  };
512
646
  }
513
647
  resultForExisting(existing, options) {
@@ -530,10 +664,35 @@ var CreateStreamService = class {
530
664
  closed: existing.lifecycle.closed === true
531
665
  };
532
666
  }
667
+ initialMessages(initialData, contentType, previousOffset, startCounter) {
668
+ const framed = initialData ? frameMessages(initialData, contentType) : [];
669
+ const allocation = allocate(this.deps.offsets, previousOffset, startCounter, framed.length);
670
+ const now = this.deps.clock.now();
671
+ return framed.map((data, i) => ({
672
+ data,
673
+ offset: allocation.offsets[i],
674
+ timestamp: now
675
+ }));
676
+ }
677
+ withInitialTail(record, initialMessages, closed) {
678
+ const lastMessage = initialMessages[initialMessages.length - 1];
679
+ return {
680
+ ...record,
681
+ currentOffset: lastMessage?.offset ?? record.currentOffset,
682
+ counter: record.counter + initialMessages.length,
683
+ lifecycle: {
684
+ ...record.lifecycle,
685
+ ...closed ? {
686
+ closed: true,
687
+ closedAt: this.deps.clock.now()
688
+ } : {}
689
+ }
690
+ };
691
+ }
533
692
  };
534
693
 
535
694
  //#endregion
536
- //#region src/protocol/helpers/fork-service.ts
695
+ //#region src/protocol/helpers/fork-plan-builder.ts
537
696
  function resolveForkExpiry(opts, source) {
538
697
  if (opts.ttlSeconds !== void 0) return { ttlSeconds: opts.ttlSeconds };
539
698
  if (opts.expiresAt) return { expiresAt: opts.expiresAt };
@@ -541,121 +700,154 @@ function resolveForkExpiry(opts, source) {
541
700
  if (source.config.expiresAt) return { expiresAt: source.config.expiresAt };
542
701
  return {};
543
702
  }
544
- var ForkService = class {
703
+ var ForkPlanBuilder = class {
545
704
  constructor(deps) {
546
705
  this.deps = deps;
547
706
  }
548
- async execute(targetStream, options) {
549
- const sourcePath = options.forkedFrom;
550
- const sourceStream = await this.deps.resolve(sourcePath);
551
- await this.deps.mutators.expireIfNeeded(sourceStream);
552
- const source = await sourceStream.getRecord();
707
+ build(targetId, sourcePath, source, options, sourceTail) {
553
708
  if (!source) return {
554
- status: "not-found",
555
- nextOffset: "",
556
- contentType: "",
557
- errorMessage: `Source stream not found: ${sourcePath}`
709
+ kind: "terminal",
710
+ result: {
711
+ status: "not-found",
712
+ nextOffset: "",
713
+ contentType: "",
714
+ errorMessage: `Source stream not found: ${sourcePath}`
715
+ }
558
716
  };
559
717
  if (source.lifecycle.softDeleted) return {
560
- status: "conflict",
561
- nextOffset: "",
562
- contentType: "",
563
- conflictReason: "fork-source-soft-deleted",
564
- errorMessage: `Source stream is soft-deleted: ${sourcePath}`
718
+ kind: "terminal",
719
+ result: {
720
+ status: "conflict",
721
+ nextOffset: "",
722
+ contentType: "",
723
+ conflictReason: "fork-source-soft-deleted",
724
+ errorMessage: `Source stream is soft-deleted: ${sourcePath}`
725
+ }
565
726
  };
566
727
  const forkOffset = options.forkOffset ?? source.currentOffset;
567
- if (!isValidOffset(forkOffset)) return {
568
- status: "bad-request",
569
- nextOffset: "",
570
- contentType: "",
571
- errorMessage: "Invalid Stream-Fork-Offset format"
728
+ if (!isValidOffset(this.deps.offsets, forkOffset)) return {
729
+ kind: "terminal",
730
+ result: {
731
+ status: "bad-request",
732
+ nextOffset: "",
733
+ contentType: "",
734
+ errorMessage: "Invalid Stream-Fork-Offset format"
735
+ }
572
736
  };
573
- if (compareOffsets(forkOffset, ZERO_OFFSET) < 0 || compareOffsets(forkOffset, source.currentOffset) > 0) return {
574
- status: "bad-request",
575
- nextOffset: "",
576
- contentType: "",
577
- errorMessage: "Stream-Fork-Offset exceeds source tail"
737
+ if (compareOffsets(forkOffset, this.deps.offsets.initialOffset) < 0 || compareOffsets(forkOffset, source.currentOffset) > 0) return {
738
+ kind: "terminal",
739
+ result: {
740
+ status: "bad-request",
741
+ nextOffset: "",
742
+ contentType: "",
743
+ errorMessage: "Stream-Fork-Offset exceeds source tail"
744
+ }
578
745
  };
579
746
  let contentType = options.contentType;
580
747
  if (!contentType || contentType.trim() === "") contentType = source.config.contentType;
581
748
  else if (!contentTypeMatches(contentType, source.config.contentType)) return {
582
- status: "conflict",
583
- nextOffset: "",
584
- contentType: "",
585
- conflictReason: "fork-content-type",
586
- errorMessage: "Fork Content-Type does not match source"
749
+ kind: "terminal",
750
+ result: {
751
+ status: "conflict",
752
+ nextOffset: "",
753
+ contentType: "",
754
+ conflictReason: "fork-content-type",
755
+ errorMessage: "Fork Content-Type does not match source"
756
+ }
757
+ };
758
+ const subOffset = options.forkSubOffset;
759
+ const prefix = this.materializePrefix(subOffset, contentType, sourceTail);
760
+ if (!prefix.ok) return {
761
+ kind: "terminal",
762
+ result: {
763
+ status: "bad-request",
764
+ nextOffset: "",
765
+ contentType: "",
766
+ errorMessage: prefix.errorMessage
767
+ }
587
768
  };
588
769
  const expiry = resolveForkExpiry(options, source);
589
- const record = this.deps.mutators.newRecord(targetStream, contentType, {
770
+ const baseRecord = this.deps.newRecord(targetId, contentType, {
590
771
  ...options,
591
772
  ...expiry
592
773
  }, {
593
774
  forkedFrom: sourcePath,
594
- forkOffset
775
+ forkOffset,
776
+ ...subOffset !== void 0 && subOffset > 0 ? { forkSubOffset: subOffset } : {}
595
777
  });
596
- const initialMessages = options.initialData ? frameMessages(options.initialData, contentType) : [];
597
- const createResult = await targetStream.createRecord(record);
598
- if (createResult.status === "created") await sourceStream.incrementChildRefCount();
599
- if (createResult.status === "exists") return {
600
- status: "conflict",
601
- nextOffset: "",
602
- contentType: "",
603
- conflictReason: "config-mismatch",
604
- errorMessage: `Stream already exists: ${targetStream.id}`
778
+ const initialMessages = this.initialMessages(prefix.messages, options.initialData, contentType, baseRecord.currentOffset, baseRecord.counter);
779
+ const child = this.withInitialTail(baseRecord, initialMessages);
780
+ const plan = {
781
+ child,
782
+ sourceId: sourcePath,
783
+ initialMessages,
784
+ precondition: { sourceLiveAtOffset: forkOffset }
605
785
  };
606
- await this.deps.mutators.scheduleExpiry(record);
607
- let final = record.currentOffset;
608
- if (initialMessages.length > 0) final = await this.deps.mutators.appendMessages(record, initialMessages);
609
786
  return {
610
- status: "created",
611
- nextOffset: final,
612
- contentType
787
+ kind: "fork",
788
+ plan,
789
+ afterCommit: child.lifecycle.expiresAtMs !== void 0 ? { scheduleExpiryAt: child.lifecycle.expiresAtMs } : {},
790
+ toResult: (record) => ({
791
+ status: "created",
792
+ nextOffset: record.currentOffset,
793
+ contentType
794
+ })
613
795
  };
614
796
  }
615
- };
616
-
617
- //#endregion
618
- //#region src/protocol/helpers/stream-gc-service.ts
619
- var StreamGcService = class {
620
- constructor(deps) {
621
- this.deps = deps;
622
- }
623
- async deleteStream(stream) {
624
- const record = await stream.getRecord();
625
- if (!record) return { status: "not-found" };
626
- if (record.lifecycle.softDeleted) return { status: "gone" };
627
- if (record.lifecycle.childRefCount > 0) {
628
- await stream.updateRecord({ lifecycle: { softDeleted: true } });
629
- await stream.notify("soft-deleted");
630
- return { status: "ok" };
797
+ /**
798
+ * Materialize the partial-message prefix addressed by `forkSubOffset` from the
799
+ * source messages that follow `forkOffset`. `0`/absent yields no prefix. For
800
+ * JSON the sub-offset counts whole flattened messages; for binary/text it
801
+ * counts bytes within the single next source message. Overshoot or an empty
802
+ * source is a 400.
803
+ */
804
+ materializePrefix(subOffset, contentType, sourceTail) {
805
+ if (subOffset === void 0 || subOffset === 0) return {
806
+ ok: true,
807
+ messages: []
808
+ };
809
+ const tail = sourceTail ?? [];
810
+ if (contentType.toLowerCase().startsWith("application/json")) {
811
+ if (subOffset > tail.length) return {
812
+ ok: false,
813
+ errorMessage: "Stream-Fork-Sub-Offset exceeds source message count"
814
+ };
815
+ return {
816
+ ok: true,
817
+ messages: tail.slice(0, subOffset).map((m) => m.data)
818
+ };
631
819
  }
632
- await this.purgeWithCascade(stream, record);
633
- return { status: "ok" };
820
+ const first = tail[0];
821
+ if (!first) return {
822
+ ok: false,
823
+ errorMessage: "Stream-Fork-Sub-Offset has no source message to fork"
824
+ };
825
+ if (subOffset > first.data.byteLength) return {
826
+ ok: false,
827
+ errorMessage: "Stream-Fork-Sub-Offset exceeds source message length"
828
+ };
829
+ return {
830
+ ok: true,
831
+ messages: [first.data.subarray(0, subOffset)]
832
+ };
634
833
  }
635
- async handleScheduledExpiry(streamId) {
636
- const stream = await this.deps.resolve(streamId);
637
- const record = await stream.getRecord();
638
- if (!record) return;
639
- if (!this.deps.mutators.isExpired(record)) return;
640
- if (record.lifecycle.childRefCount > 0) {
641
- await stream.updateRecord({ lifecycle: { softDeleted: true } });
642
- await stream.notify("soft-deleted");
643
- return;
644
- }
645
- await this.purgeWithCascade(stream, record);
646
- }
647
- async purgeWithCascade(stream, record) {
648
- await stream.cancelExpiry();
649
- await stream.deleteMessages();
650
- await stream.deleteProducerStates();
651
- await stream.deleteRecord();
652
- await stream.notify("deleted");
653
- const parentId = record.lifecycle.forkedFrom;
654
- if (!parentId) return;
655
- const parentStream = await this.deps.resolve(parentId);
656
- const newRefCount = await parentStream.decrementChildRefCount();
657
- const parent = await parentStream.getRecord();
658
- if (parent && newRefCount === 0 && parent.lifecycle.softDeleted) await this.purgeWithCascade(parentStream, parent);
834
+ initialMessages(prefix, initialData, contentType, previousOffset, startCounter) {
835
+ const framed = [...prefix, ...initialData ? frameMessages(initialData, contentType) : []];
836
+ const allocation = allocate(this.deps.offsets, previousOffset, startCounter, framed.length);
837
+ const now = this.deps.clock.now();
838
+ return framed.map((data, i) => ({
839
+ data,
840
+ offset: allocation.offsets[i],
841
+ timestamp: now
842
+ }));
843
+ }
844
+ withInitialTail(record, initialMessages) {
845
+ const lastMessage = initialMessages[initialMessages.length - 1];
846
+ return {
847
+ ...record,
848
+ currentOffset: lastMessage?.offset ?? record.currentOffset,
849
+ counter: record.counter + initialMessages.length
850
+ };
659
851
  }
660
852
  };
661
853
 
@@ -670,16 +862,17 @@ var StreamMessageReader = class {
670
862
  }
671
863
  async readChainFor(stream, record, afterOffset, capOffset, touchOwnTtl = true) {
672
864
  const out = [];
673
- if (record.lifecycle.forkedFrom && record.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, record.lifecycle.forkOffset) < 0)) {
674
- const sourceStream = await this.deps.resolve(record.lifecycle.forkedFrom);
865
+ let current = record;
866
+ if (current.lifecycle.forkedFrom && current.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, current.lifecycle.forkOffset) < 0)) {
867
+ const sourceStream = await this.deps.resolve(current.lifecycle.forkedFrom);
675
868
  const source = await sourceStream.getRecord();
676
869
  if (source) {
677
- const upstreamCap = capOffset && compareOffsets(capOffset, record.lifecycle.forkOffset) < 0 ? capOffset : record.lifecycle.forkOffset;
870
+ const upstreamCap = capOffset && compareOffsets(capOffset, current.lifecycle.forkOffset) < 0 ? capOffset : current.lifecycle.forkOffset;
678
871
  out.push(...await this.readChainFor(sourceStream, source, afterOffset, upstreamCap, false));
679
872
  }
680
873
  }
681
- if (touchOwnTtl) await this.deps.expiryPolicy.touch(stream, record, "read");
682
- const ownStart = record.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, record.lifecycle.forkOffset) < 0) ? record.lifecycle.forkOffset : afterOffset;
874
+ if (touchOwnTtl) current = await this.deps.expiryPolicy.touch(stream, current, "read");
875
+ const ownStart = current.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, current.lifecycle.forkOffset) < 0) ? current.lifecycle.forkOffset : afterOffset;
683
876
  const own = await stream.listMessages({
684
877
  after: ownStart,
685
878
  until: capOffset
@@ -695,58 +888,21 @@ var StreamMessageReader = class {
695
888
  nextOffset: ""
696
889
  };
697
890
  const messages = await stream.listMessages({ after });
891
+ if (messages.length > 0) return {
892
+ messages,
893
+ nextOffset: messages[messages.length - 1].offset
894
+ };
895
+ if (after !== void 0 && compareOffsets(after, record.currentOffset) < 0) return {
896
+ messages,
897
+ nextOffset: after
898
+ };
698
899
  return {
699
900
  messages,
700
- nextOffset: messages.length > 0 ? messages[messages.length - 1].offset : record.currentOffset
901
+ nextOffset: record.currentOffset
701
902
  };
702
903
  }
703
904
  };
704
905
 
705
- //#endregion
706
- //#region src/protocol/storage/stream-message-writer.ts
707
- var StreamMessageWriter = class {
708
- constructor(deps) {
709
- this.deps = deps;
710
- }
711
- async appendMessages(record, data, seq) {
712
- await this.deps.expiryPolicy.touch(this.deps.stream, record, "append");
713
- const allocation = allocate(record.counter, data.length);
714
- const now = this.deps.clock.now();
715
- const messages = data.map((bytes, i) => ({
716
- data: bytes,
717
- offset: allocation.offsets[i],
718
- timestamp: now
719
- }));
720
- if (messages.length > 0) await this.deps.stream.appendMessages(messages);
721
- await this.deps.stream.updateRecord({
722
- currentOffset: allocation.nextOffset,
723
- counter: allocation.endCounter,
724
- lifecycle: seq ? { lastSeq: seq } : void 0
725
- });
726
- await this.deps.stream.notify("message");
727
- return allocation.nextOffset;
728
- }
729
- async closeRecord(record, data, seq) {
730
- let latest = record;
731
- let nextOffset = record.currentOffset;
732
- if (data.length > 0) {
733
- nextOffset = await this.appendMessages(record, data, seq);
734
- latest = await this.deps.stream.getRecord() ?? record;
735
- } else await this.deps.expiryPolicy.touch(this.deps.stream, record, "close");
736
- await this.deps.stream.updateRecord({
737
- lifecycle: {
738
- closed: true,
739
- closedAt: this.deps.clock.now(),
740
- ...seq ? { lastSeq: seq } : {}
741
- },
742
- currentOffset: nextOffset,
743
- counter: latest.counter
744
- });
745
- await this.deps.stream.notify("closed");
746
- return nextOffset;
747
- }
748
- };
749
-
750
906
  //#endregion
751
907
  //#region src/protocol/storage/stream-record-factory.ts
752
908
  var StreamRecordFactory = class {
@@ -765,92 +921,126 @@ var StreamRecordFactory = class {
765
921
  id: streamId,
766
922
  config,
767
923
  lifecycle: {
768
- childRefCount: 0,
769
924
  forkedFrom: fork?.forkedFrom,
770
925
  forkOffset,
926
+ ...fork?.forkSubOffset !== void 0 && fork.forkSubOffset > 0 ? { forkSubOffset: fork.forkSubOffset } : {},
771
927
  expiresAtMs: this.deps.expiryPolicy.computeExpiresAtMs(config)
772
928
  },
773
- currentOffset: forkOffset ?? ZERO_OFFSET,
774
- counter: forkOffset ? parseCounter(forkOffset) : 0
929
+ currentOffset: forkOffset ?? this.deps.offsets.initialOffset,
930
+ counter: 0
775
931
  };
776
932
  }
777
933
  };
778
934
 
779
935
  //#endregion
780
936
  //#region src/protocol.ts
781
- const LONG_POLL_TIMEOUT_MS = 1500;
937
+ const LONG_POLL_TIMEOUT_MS = 3e4;
938
+ const MAX_COMMIT_ATTEMPTS = 8;
939
+ const MAX_NO_PROGRESS_ATTEMPTS = 8;
782
940
  function createStreamProtocol(deps) {
783
941
  return new StreamProtocol(deps);
784
942
  }
943
+ async function runDeleteEffects(status, storage) {
944
+ if (status === "purged") await runAfterCommit({ cancelExpiry: true }, storage);
945
+ }
946
+ function mapDelete(status) {
947
+ if (status === "not-found") return { status: "not-found" };
948
+ if (status === "gone") return { status: "gone" };
949
+ return { status: "ok" };
950
+ }
951
+ /**
952
+ * Adapt a storage `Stream` to the live-read store. Every adapter implements
953
+ * `awaitChange` (a backend that cannot wake cheaply polls inside its own
954
+ * implementation), so core wires it straight through with no fallback.
955
+ */
956
+ function liveReadStore(storage) {
957
+ return {
958
+ getRecord: () => storage.getRecord(),
959
+ awaitChange: (options) => storage.awaitChange(options)
960
+ };
961
+ }
785
962
  var ProtocolStream = class {
786
963
  id;
787
964
  appendService;
788
965
  readService;
789
966
  liveReadService;
790
967
  createService;
968
+ forkPlanBuilder;
791
969
  constructor(deps) {
792
970
  this.deps = deps;
793
971
  this.id = deps.storage.id;
794
- const producerIdempotency = new ProducerIdempotencyService({ store: deps.storage });
795
- const messageWriter = new StreamMessageWriter({
796
- stream: deps.storage,
797
- clock: deps.clock,
798
- expiryPolicy: deps.expiryPolicy
799
- });
800
972
  const messageReader = new StreamMessageReader({
801
973
  stream: deps.storage,
802
974
  resolve: deps.resolveStorageStream,
803
975
  expiryPolicy: deps.expiryPolicy
804
976
  });
805
977
  this.appendService = new AppendService({
806
- producerIdempotency,
807
- mutators: {
808
- appendMessages: (record, data, seq) => messageWriter.appendMessages(record, data, seq),
809
- closeRecord: (record, data, seq) => messageWriter.closeRecord(record, data, seq)
810
- }
978
+ clock: deps.clock,
979
+ offsets: deps.offsets
811
980
  });
812
981
  this.readService = new ReadService({ readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset) });
813
982
  this.liveReadService = new LiveReadService({
814
- store: deps.storage,
983
+ store: liveReadStore(deps.storage),
815
984
  clock: deps.clock,
816
985
  longPollTimeoutMs: deps.longPollTimeoutMs,
986
+ offsets: deps.offsets,
817
987
  readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset),
818
- readOwn: (after) => messageReader.readOwn(after),
819
- touch: (record) => deps.expiryPolicy.touch(deps.storage, record, "live-read")
820
- });
821
- const forkService = new ForkService({
822
- resolve: deps.resolveStorageStream,
823
- mutators: {
824
- expireIfNeeded: async (stream) => {
825
- await deps.expiryPolicy.expireIfNeeded(stream);
826
- },
827
- newRecord: (stream, contentType, opts, fork) => deps.recordFactory.newRecord(stream.id, contentType, opts, fork),
828
- scheduleExpiry: (record) => deps.expiryPolicy.scheduleExpiry(record),
829
- appendMessages: (record, data) => messageWriter.appendMessages(record, data)
830
- }
988
+ readOwn: (after) => messageReader.readOwn(after)
831
989
  });
832
990
  this.createService = new CreateStreamService({
833
- store: deps.storage,
834
- mutators: {
835
- newRecord: (contentType, opts) => deps.recordFactory.newRecord(deps.storage.id, contentType, opts, void 0),
836
- scheduleExpiry: (record) => deps.expiryPolicy.scheduleExpiry(record),
837
- appendMessages: (record, data) => messageWriter.appendMessages(record, data),
838
- closeRecord: (record, data) => messageWriter.closeRecord(record, data),
839
- createFork: (opts) => forkService.execute(deps.storage, opts)
840
- }
991
+ clock: deps.clock,
992
+ offsets: deps.offsets,
993
+ newRecord: (contentType, opts) => deps.recordFactory.newRecord(deps.storage.id, contentType, opts, void 0)
994
+ });
995
+ this.forkPlanBuilder = new ForkPlanBuilder({
996
+ clock: deps.clock,
997
+ offsets: deps.offsets,
998
+ newRecord: (streamId, contentType, opts, fork) => deps.recordFactory.newRecord(streamId, contentType, opts, fork)
841
999
  });
842
1000
  }
843
1001
  async create(options) {
844
- return this.deps.withStreamMutationLock(this.deps.storage, async () => {
845
- const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
846
- return this.createService.execute(record, options);
847
- });
1002
+ const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
1003
+ const decision = this.createService.plan(record, options);
1004
+ if (decision.kind === "terminal") return decision.result;
1005
+ if (decision.kind === "fork") return this.createFork(options);
1006
+ const commit = await this.deps.adapter.create(decision.plan);
1007
+ if (commit.status === "exists") return this.createService.resultForExisting(commit.record, options);
1008
+ await runAfterCommit(decision.afterCommit, this.deps.storage);
1009
+ this.deps.emitAfterCommit(commit.record);
1010
+ return decision.toResult(commit.record);
848
1011
  }
849
1012
  async append(options) {
850
- return this.deps.withStreamMutationLock(this.deps.storage, async () => {
851
- const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
852
- return this.appendService.execute(record, options);
853
- });
1013
+ let lastRecord = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
1014
+ let noProgressAttempts = 0;
1015
+ let attempt = 0;
1016
+ const hasUserExpectedOffset = options.expectedOffset !== void 0;
1017
+ while (true) {
1018
+ const producerState = options.producer ? await this.deps.storage.getProducerState(options.producer.producerId) : void 0;
1019
+ const decision = this.appendService.plan(lastRecord, options, producerState);
1020
+ if (decision.kind === "terminal") return decision.result;
1021
+ const out = await this.deps.storage.append(decision.plan);
1022
+ if (out.status === "appended") {
1023
+ await runAfterCommit(decision.afterCommit, this.deps.storage);
1024
+ this.deps.emitAfterCommit(out.record);
1025
+ return decision.toResult(out.record);
1026
+ }
1027
+ lastRecord = out.record;
1028
+ if (lastRecord === null) return { status: "not-found" };
1029
+ if (hasUserExpectedOffset) {
1030
+ attempt++;
1031
+ if (attempt >= MAX_COMMIT_ATTEMPTS) return {
1032
+ status: "conflict",
1033
+ conflictReason: "expected-offset",
1034
+ offset: lastRecord.currentOffset
1035
+ };
1036
+ } else {
1037
+ const previousOffset = decision.plan.preconditions.expectedOffset ?? this.deps.offsets.initialOffset;
1038
+ const madeProgress = compareOffsets(lastRecord.currentOffset, previousOffset) > 0;
1039
+ noProgressAttempts = madeProgress ? 0 : noProgressAttempts + 1;
1040
+ if (noProgressAttempts >= MAX_NO_PROGRESS_ATTEMPTS) return { status: "busy" };
1041
+ }
1042
+ await Promise.resolve();
1043
+ }
854
1044
  }
855
1045
  async read(options) {
856
1046
  const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
@@ -875,35 +1065,83 @@ var ProtocolStream = class {
875
1065
  }
876
1066
  async delete() {
877
1067
  await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
878
- return this.deps.gcService.deleteStream(this.deps.storage);
1068
+ const commit = await this.deps.adapter.delete({
1069
+ streamId: this.id,
1070
+ reason: "delete"
1071
+ });
1072
+ await runDeleteEffects(commit.status, this.deps.storage);
1073
+ return mapDelete(commit.status);
1074
+ }
1075
+ /**
1076
+ * Read the source messages immediately after `forkOffset`, composed through
1077
+ * the source's own fork chain, so a sub-offset fork can materialize a
1078
+ * partial-message prefix (and chained forks compose). Only needed when a
1079
+ * positive `forkSubOffset` is requested; validation of the offset/sub-offset
1080
+ * combination stays in the fork plan builder.
1081
+ */
1082
+ async readSourceTailForSubOffset(sourceStream, source, options) {
1083
+ const subOffset = options.forkSubOffset;
1084
+ if (subOffset === void 0 || subOffset <= 0 || !source) return void 0;
1085
+ const forkOffset = options.forkOffset ?? source.currentOffset;
1086
+ if (!isValidOffset(this.deps.offsets, forkOffset)) return void 0;
1087
+ const reader = new StreamMessageReader({
1088
+ stream: sourceStream,
1089
+ resolve: this.deps.resolveStorageStream,
1090
+ expiryPolicy: this.deps.expiryPolicy
1091
+ });
1092
+ return reader.readChain(source, forkOffset, void 0, false);
1093
+ }
1094
+ async createFork(options) {
1095
+ const fork = this.deps.adapter.fork;
1096
+ if (!fork) return notSupported("fork");
1097
+ const sourceId = options.forkedFrom;
1098
+ const sourceStream = this.deps.resolveStorageStream(sourceId);
1099
+ const source = await this.deps.expiryPolicy.expireIfNeeded(sourceStream);
1100
+ const sourceTail = await this.readSourceTailForSubOffset(sourceStream, source, options);
1101
+ const decision = this.forkPlanBuilder.build(this.id, sourceId, source, options, sourceTail);
1102
+ if (decision.kind === "terminal") return decision.result;
1103
+ const commit = await fork.call(this.deps.adapter, decision.plan);
1104
+ if (commit.status === "exists") return this.createService.resultForExisting(commit.record, options);
1105
+ if (commit.status === "fork-source-gone") return {
1106
+ status: "not-found",
1107
+ nextOffset: "",
1108
+ contentType: "",
1109
+ errorMessage: `Source stream not found: ${sourceId}`
1110
+ };
1111
+ await runAfterCommit(decision.afterCommit, this.deps.storage);
1112
+ this.deps.emitAfterCommit(commit.record);
1113
+ return decision.toResult(commit.record);
879
1114
  }
880
1115
  };
881
1116
  var StreamProtocol = class {
882
1117
  clock;
883
1118
  longPollTimeoutMs;
884
1119
  expiryPolicy;
885
- gcService;
886
1120
  recordFactory;
1121
+ offsetGenerator;
1122
+ hooks = new Set();
887
1123
  constructor(deps) {
888
1124
  this.deps = deps;
889
1125
  this.clock = deps.clock ?? systemClock;
1126
+ this.offsetGenerator = deps.offsetGenerator ?? defaultOffsetGenerator;
1127
+ assertValidOffsetGenerator(this.offsetGenerator);
890
1128
  this.longPollTimeoutMs = deps.longPollTimeoutMs ?? LONG_POLL_TIMEOUT_MS;
891
1129
  this.expiryPolicy = new ExpiryPolicy({
892
1130
  resolve: (id) => this.storageStream(id),
893
1131
  clock: this.clock,
894
1132
  onScheduledExpiry: (id) => this.handleScheduledExpiry(id)
895
1133
  });
896
- this.gcService = new StreamGcService({
897
- resolve: (id) => this.storageStream(id),
898
- mutators: { isExpired: (record) => this.expiryPolicy.isExpired(record) }
899
- });
900
1134
  this.recordFactory = new StreamRecordFactory({
901
1135
  clock: this.clock,
902
- expiryPolicy: this.expiryPolicy
1136
+ expiryPolicy: this.expiryPolicy,
1137
+ offsets: this.offsetGenerator
903
1138
  });
904
1139
  }
1140
+ isValidOffset(offset) {
1141
+ return isValidOffset(this.offsetGenerator, offset);
1142
+ }
905
1143
  async create(streamId, options) {
906
- const storage = await this.storageStream(streamId);
1144
+ const storage = this.storageStream(streamId);
907
1145
  const stream = this.boundProtocolStream(storage);
908
1146
  const result = await stream.create(options);
909
1147
  if (result.status === "created" || result.status === "exists") return {
@@ -913,7 +1151,7 @@ var StreamProtocol = class {
913
1151
  return result;
914
1152
  }
915
1153
  async get(streamId) {
916
- const storage = await this.storageStream(streamId);
1154
+ const storage = this.storageStream(streamId);
917
1155
  const record = await this.expiryPolicy.expireIfNeeded(storage);
918
1156
  if (!record) return { status: "not-found" };
919
1157
  if (record.lifecycle.softDeleted) return { status: "gone" };
@@ -922,33 +1160,231 @@ var StreamProtocol = class {
922
1160
  stream: this.boundProtocolStream(storage)
923
1161
  };
924
1162
  }
925
- /** Called by adapter schedulers/alarms; core decides soft-delete vs purge. */
1163
+ onAfterCommit(hook) {
1164
+ this.hooks.add(hook);
1165
+ return () => {
1166
+ this.hooks.delete(hook);
1167
+ };
1168
+ }
1169
+ /** Called by adapter schedulers/alarms; core decides whether expiry applies. */
926
1170
  async handleScheduledExpiry(streamId) {
927
- return this.gcService.handleScheduledExpiry(streamId);
1171
+ const storage = this.storageStream(streamId);
1172
+ const record = await storage.getRecord();
1173
+ if (!record) return;
1174
+ if (!this.expiryPolicy.isExpired(record)) {
1175
+ await this.expiryPolicy.scheduleExpiry(record);
1176
+ return;
1177
+ }
1178
+ const commit = await this.deps.storage.adapter.delete({
1179
+ streamId,
1180
+ reason: "expiry"
1181
+ });
1182
+ await runDeleteEffects(commit.status, storage);
928
1183
  }
929
1184
  boundProtocolStream(storage) {
930
1185
  return new ProtocolStream({
931
1186
  storage,
1187
+ adapter: this.deps.storage.adapter,
932
1188
  clock: this.clock,
933
1189
  longPollTimeoutMs: this.longPollTimeoutMs,
934
1190
  expiryPolicy: this.expiryPolicy,
935
- gcService: this.gcService,
936
1191
  recordFactory: this.recordFactory,
937
1192
  resolveStorageStream: (id) => this.storageStream(id),
938
- withStreamMutationLock: (stream, fn) => this.withStreamMutationLock(stream, fn)
1193
+ emitAfterCommit: (record) => this.emitAfterCommit(record),
1194
+ offsets: this.offsetGenerator
939
1195
  });
940
1196
  }
941
- async storageStream(streamId) {
942
- return this.deps.storage.factory.getStream(streamId);
1197
+ /** Bind the flat adapter to one id for ergonomic core-side per-stream calls. */
1198
+ storageStream(streamId) {
1199
+ return bindStream(this.deps.storage.adapter, streamId);
1200
+ }
1201
+ emitAfterCommit(record) {
1202
+ const event = {
1203
+ streamId: record.id,
1204
+ offset: record.currentOffset,
1205
+ closed: record.lifecycle.closed === true,
1206
+ softDeleted: record.lifecycle.softDeleted === true
1207
+ };
1208
+ for (const hook of this.hooks) try {
1209
+ hook(event);
1210
+ } catch (error) {
1211
+ console.warn("after-commit hook failed", error);
1212
+ }
1213
+ }
1214
+ };
1215
+
1216
+ //#endregion
1217
+ //#region src/storage/strategies/cascade-reclaim.ts
1218
+ async function cascadeReclaim(store, plan, lineage) {
1219
+ const record = await store.getRecord(plan.streamId);
1220
+ if (!record) return { status: "not-found" };
1221
+ if (plan.reason === "delete" && record.lifecycle.softDeleted) return { status: "gone" };
1222
+ const dependents = await lineage.countDependents(plan.streamId);
1223
+ if (dependents > 0) {
1224
+ await store.softDelete(plan.streamId);
1225
+ return { status: "retained-soft-deleted" };
1226
+ }
1227
+ await purgeAndCascade(store, lineage, record);
1228
+ return { status: "purged" };
1229
+ }
1230
+ async function plainPurge(store, plan) {
1231
+ const record = await store.getRecord(plan.streamId);
1232
+ if (!record) return { status: "not-found" };
1233
+ if (plan.reason === "delete" && record.lifecycle.softDeleted) return { status: "gone" };
1234
+ await store.purgeSelf(plan.streamId);
1235
+ return { status: "purged" };
1236
+ }
1237
+ async function purgeAndCascade(store, lineage, record) {
1238
+ await store.purgeSelf(record.id);
1239
+ let childId = record.id;
1240
+ let parentId = record.lifecycle.forkedFrom;
1241
+ while (parentId) {
1242
+ await lineage.dropEdge(parentId, childId);
1243
+ const parent = await store.getRecord(parentId);
1244
+ if (!parent || parent.lifecycle.softDeleted !== true) return;
1245
+ const dependents = await lineage.countDependents(parentId);
1246
+ if (dependents > 0) return;
1247
+ await store.purgeSelf(parentId);
1248
+ childId = parentId;
1249
+ parentId = parent.lifecycle.forkedFrom;
1250
+ }
1251
+ }
1252
+
1253
+ //#endregion
1254
+ //#region src/storage/strategies/ref-count-lineage.ts
1255
+ function refCountLineage(store) {
1256
+ return {
1257
+ async countDependents(parent) {
1258
+ return store.countDependents ? store.countDependents(parent) : 0;
1259
+ },
1260
+ async addEdge(parent, child) {
1261
+ await store.addEdge?.(parent, child);
1262
+ },
1263
+ async dropEdge(parent, child) {
1264
+ await store.dropEdge?.(parent, child);
1265
+ }
1266
+ };
1267
+ }
1268
+
1269
+ //#endregion
1270
+ //#region src/storage/strategies/reverse-index-lineage.ts
1271
+ function reverseIndexLineage(query) {
1272
+ return {
1273
+ countDependents(parent) {
1274
+ return query(parent);
1275
+ },
1276
+ async addEdge() {},
1277
+ async dropEdge() {}
1278
+ };
1279
+ }
1280
+
1281
+ //#endregion
1282
+ //#region src/storage/strategies/copy-on-fork.ts
1283
+ function copyOnForkReclaim() {
1284
+ return {
1285
+ async countDependents() {
1286
+ return 0;
1287
+ },
1288
+ async addEdge() {},
1289
+ async dropEdge() {}
1290
+ };
1291
+ }
1292
+
1293
+ //#endregion
1294
+ //#region src/storage/strategies/ttl-only.ts
1295
+ function ttlOnlyReclaim() {
1296
+ return {
1297
+ async countDependents() {
1298
+ return 1;
1299
+ },
1300
+ async addEdge() {},
1301
+ async dropEdge() {}
1302
+ };
1303
+ }
1304
+
1305
+ //#endregion
1306
+ //#region src/storage/memory/lineage-store.ts
1307
+ var MemoryLineageStore = class {
1308
+ constructor(state) {
1309
+ this.state = state;
1310
+ }
1311
+ async getRecord(id) {
1312
+ return this.state.getExistingStream(id)?.getRecord() ?? null;
1313
+ }
1314
+ async purgeSelf(id) {
1315
+ this.state.getExistingStream(id)?.purgeSelf();
943
1316
  }
944
- async withStreamMutationLock(storage, fn) {
945
- return storage.withMutationLock(fn);
1317
+ async softDelete(id) {
1318
+ this.state.getExistingStream(id)?.softDelete();
1319
+ }
1320
+ async addEdge(parent, child) {
1321
+ this.state.addEdge(parent, child);
1322
+ }
1323
+ async dropEdge(parent, child) {
1324
+ this.state.dropEdge(parent, child);
1325
+ }
1326
+ async countDependents(parent) {
1327
+ return this.state.countDependents(parent);
946
1328
  }
947
1329
  };
948
1330
 
1331
+ //#endregion
1332
+ //#region src/protocol/helpers/change-snapshot.ts
1333
+ /** Build the serializable, change-relevant snapshot of a (possibly absent) record. */
1334
+ function buildChangeSnapshot(record) {
1335
+ if (!record) return {
1336
+ present: false,
1337
+ currentOffset: ZERO_OFFSET,
1338
+ closed: false,
1339
+ softDeleted: false
1340
+ };
1341
+ return {
1342
+ present: true,
1343
+ currentOffset: record.currentOffset,
1344
+ closed: record.lifecycle.closed === true,
1345
+ softDeleted: record.lifecycle.softDeleted === true
1346
+ };
1347
+ }
1348
+ /**
1349
+ * The level-triggered "differs" predicate. A snapshot differs from what the
1350
+ * caller observed when the record was purged, transitioned to soft-deleted or
1351
+ * closed, or its offset is not the parked position. Offset **inequality** — not
1352
+ * just advance — is the trigger: within one incarnation an offset only ever
1353
+ * advances, so a *lower* offset means the stream was purged and re-created
1354
+ * while the waiter was parked, which is also "something happened".
1355
+ */
1356
+ function changeSnapshotDiffers(snapshot, options) {
1357
+ if (!snapshot.present) return true;
1358
+ if (snapshot.softDeleted && options.observedSoftDeleted !== true) return true;
1359
+ if (snapshot.closed && options.observedClosed !== true) return true;
1360
+ return compareOffsets(snapshot.currentOffset, options.fromOffset) !== 0;
1361
+ }
1362
+
1363
+ //#endregion
1364
+ //#region src/protocol/helpers/await-change-loop.ts
1365
+ async function runAwaitChangeLoop(deps, options) {
1366
+ const now = deps.now ?? (() => Date.now());
1367
+ const budget = deps.totalCapMs === void 0 ? options.timeoutMs : Math.min(options.timeoutMs, deps.totalCapMs);
1368
+ const start = now();
1369
+ while (true) {
1370
+ const snapshot = buildChangeSnapshot(await deps.readRecord());
1371
+ if (changeSnapshotDiffers(snapshot, options)) return {
1372
+ status: "changed",
1373
+ snapshot
1374
+ };
1375
+ const remaining = budget - (now() - start);
1376
+ if (remaining <= 0) return {
1377
+ status: "timeout",
1378
+ snapshot
1379
+ };
1380
+ const park = deps.parkCapMs === void 0 ? remaining : Math.min(remaining, deps.parkCapMs);
1381
+ await deps.waitForWake(park);
1382
+ }
1383
+ }
1384
+
949
1385
  //#endregion
950
1386
  //#region src/storage/memory/lib/clone.ts
951
- function clone(value) {
1387
+ function clone$1(value) {
952
1388
  if (value === null || value === void 0) return value;
953
1389
  return structuredClone(value);
954
1390
  }
@@ -960,18 +1396,18 @@ var MessageStore = class {
960
1396
  constructor(records) {
961
1397
  this.records = records;
962
1398
  }
963
- async appendMessages(messages) {
1399
+ appendMessages(messages) {
964
1400
  this.records.requireRecord();
965
- this.messages.push(...clone(messages));
1401
+ this.messages.push(...clone$1(messages));
966
1402
  }
967
- async listMessages(options = {}) {
1403
+ listMessages(options = {}) {
968
1404
  let out = this.messages;
969
1405
  if (options.after) out = out.filter((m) => m.offset > options.after);
970
1406
  if (options.until) out = out.filter((m) => m.offset <= options.until);
971
1407
  if (options.limit !== void 0) out = out.slice(0, options.limit);
972
- return clone(out);
1408
+ return clone$1(out);
973
1409
  }
974
- async deleteMessages() {
1410
+ deleteMessages() {
975
1411
  this.messages = [];
976
1412
  }
977
1413
  };
@@ -983,14 +1419,14 @@ var ProducerStore = class {
983
1419
  constructor(records) {
984
1420
  this.records = records;
985
1421
  }
986
- async getProducerState(producerId) {
987
- return clone(this.producers.get(producerId));
1422
+ getProducerState(producerId) {
1423
+ return clone$1(this.producers.get(producerId));
988
1424
  }
989
- async setProducerState(producerId, producerState) {
1425
+ setProducerState(producerId, producerState) {
990
1426
  this.records.requireRecord();
991
- this.producers.set(producerId, clone(producerState));
1427
+ this.producers.set(producerId, clone$1(producerState));
992
1428
  }
993
- async deleteProducerStates() {
1429
+ deleteProducerStates() {
994
1430
  this.producers.clear();
995
1431
  }
996
1432
  };
@@ -1002,19 +1438,19 @@ var RecordStore = class {
1002
1438
  constructor(id) {
1003
1439
  this.id = id;
1004
1440
  }
1005
- async getRecord() {
1006
- return clone(this.record ?? null);
1441
+ getRecord() {
1442
+ return clone$1(this.record ?? null);
1007
1443
  }
1008
- async createRecord(record) {
1444
+ createRecord(record) {
1009
1445
  if (record.id !== this.id) throw new Error(`Record id ${record.id} does not match bound stream ${this.id}`);
1010
1446
  if (this.record) return {
1011
1447
  status: "exists",
1012
- record: clone(this.record)
1448
+ record: clone$1(this.record)
1013
1449
  };
1014
- this.record = clone(record);
1450
+ this.record = clone$1(record);
1015
1451
  return { status: "created" };
1016
1452
  }
1017
- async updateRecord(patch) {
1453
+ updateRecord(patch) {
1018
1454
  const record = this.requireRecord();
1019
1455
  this.record = {
1020
1456
  ...record,
@@ -1029,87 +1465,46 @@ var RecordStore = class {
1029
1465
  currentOffset: patch.currentOffset ?? record.currentOffset,
1030
1466
  counter: patch.counter ?? record.counter
1031
1467
  };
1032
- return clone(this.record);
1468
+ return clone$1(this.record);
1033
1469
  }
1034
- async deleteRecord() {
1470
+ deleteRecord() {
1035
1471
  this.record = void 0;
1036
1472
  }
1037
- async incrementChildRefCount() {
1038
- const updated = this.updateStoredRecord((record) => {
1039
- const next = record.lifecycle.childRefCount + 1;
1040
- return {
1041
- ...record,
1042
- lifecycle: {
1043
- ...record.lifecycle,
1044
- childRefCount: next
1045
- }
1046
- };
1047
- });
1048
- return updated.lifecycle.childRefCount;
1049
- }
1050
- async decrementChildRefCount() {
1051
- const updated = this.updateStoredRecord((record) => {
1052
- const next = Math.max(0, record.lifecycle.childRefCount - 1);
1053
- return {
1054
- ...record,
1055
- lifecycle: {
1056
- ...record.lifecycle,
1057
- childRefCount: next
1058
- }
1059
- };
1060
- });
1061
- return updated.lifecycle.childRefCount;
1062
- }
1063
1473
  requireRecord() {
1064
1474
  if (!this.record) throw new Error(`Stream not found: ${this.id}`);
1065
1475
  return this.record;
1066
1476
  }
1067
- updateStoredRecord(update) {
1068
- this.record = update(this.requireRecord());
1069
- return this.record;
1070
- }
1071
- };
1072
-
1073
- //#endregion
1074
- //#region src/storage/memory/utils/lock.ts
1075
- var MemoryLock = class {
1076
- lock;
1077
- async withLock(fn) {
1078
- while (this.lock) await this.lock;
1079
- let release;
1080
- this.lock = new Promise((resolve) => release = resolve);
1081
- try {
1082
- return await fn();
1083
- } finally {
1084
- this.lock = void 0;
1085
- release();
1086
- }
1087
- }
1088
1477
  };
1089
1478
 
1090
1479
  //#endregion
1091
1480
  //#region src/storage/memory/utils/notifier.ts
1481
+ /**
1482
+ * In-process wake bus backing the memory adapter's level-triggered `awaitChange`.
1483
+ *
1484
+ * A parked waiter resolves either when a mutation calls {@link wake} or after its
1485
+ * timeout; the caller re-reads durable state to decide whether anything relevant
1486
+ * changed. Spurious wakes are safe — the caller simply re-checks and parks again
1487
+ * within its remaining budget.
1488
+ */
1092
1489
  var MemoryNotifier = class {
1093
- waiters = new Set();
1094
- waitForEvent(options) {
1490
+ wakeWaiters = new Set();
1491
+ waitForWake(timeoutMs) {
1095
1492
  return new Promise((resolve) => {
1096
- const timeout = setTimeout(() => finish({ status: "timeout" }), options.timeoutMs);
1097
- const finish = (result) => {
1493
+ const finish = () => {
1098
1494
  clearTimeout(timeout);
1099
- this.waiters.delete(finish);
1100
- resolve(result);
1495
+ this.wakeWaiters.delete(finish);
1496
+ resolve();
1101
1497
  };
1102
- this.waiters.add(finish);
1103
- options.signal?.addEventListener("abort", () => finish({ status: "aborted" }), { once: true });
1498
+ const timeout = setTimeout(finish, timeoutMs);
1499
+ this.wakeWaiters.add(finish);
1104
1500
  });
1105
1501
  }
1106
- notify(type) {
1107
- const waiters = [...this.waiters];
1108
- this.waiters.clear();
1109
- for (const waiter of waiters) waiter({
1110
- status: "notified",
1111
- type
1112
- });
1502
+ /** Wake every parked `awaitChange` waiter. Called from inside a mutation. */
1503
+ wake() {
1504
+ if (this.wakeWaiters.size === 0) return;
1505
+ const waiters = [...this.wakeWaiters];
1506
+ this.wakeWaiters.clear();
1507
+ for (const waiter of waiters) waiter();
1113
1508
  }
1114
1509
  };
1115
1510
 
@@ -1117,11 +1512,18 @@ var MemoryNotifier = class {
1117
1512
  //#region src/storage/memory/utils/timeout-scheduler.ts
1118
1513
  var TimeoutScheduler = class {
1119
1514
  timer;
1120
- schedule(at, callback) {
1515
+ constructor(callback) {
1516
+ this.callback = callback;
1517
+ }
1518
+ schedule(at) {
1121
1519
  this.cancel();
1122
- if (!callback) return;
1123
- const delay = Math.max(0, at - Date.now());
1124
- this.timer = setTimeout(() => void callback(), delay);
1520
+ if (!this.callback) return;
1521
+ const delay$1 = Math.max(0, at - Date.now());
1522
+ this.timer = setTimeout(() => {
1523
+ Promise.resolve(this.callback?.()).catch((error) => {
1524
+ console.error("memory expiry callback failed", error);
1525
+ });
1526
+ }, delay$1);
1125
1527
  }
1126
1528
  cancel() {
1127
1529
  if (this.timer) clearTimeout(this.timer);
@@ -1131,105 +1533,232 @@ var TimeoutScheduler = class {
1131
1533
 
1132
1534
  //#endregion
1133
1535
  //#region src/storage/memory/stream.ts
1536
+ /** Adapter-private per-stream handle. Not on the seam — owned by the memory state. */
1134
1537
  var MemoryStream = class {
1135
1538
  records;
1136
1539
  messages;
1137
1540
  producers;
1138
- lock;
1139
1541
  notifier;
1140
1542
  timeout;
1141
- constructor(id, deleteFromState) {
1543
+ constructor(id, deleteFromState, onScheduledExpiry) {
1142
1544
  this.id = id;
1143
1545
  this.deleteFromState = deleteFromState;
1144
1546
  this.records = new RecordStore(id);
1145
1547
  this.messages = new MessageStore(this.records);
1146
1548
  this.producers = new ProducerStore(this.records);
1147
- this.lock = new MemoryLock();
1148
1549
  this.notifier = new MemoryNotifier();
1149
- this.timeout = new TimeoutScheduler();
1550
+ this.timeout = new TimeoutScheduler(onScheduledExpiry);
1150
1551
  }
1151
1552
  getRecord() {
1152
1553
  return this.records.getRecord();
1153
1554
  }
1154
- createRecord(record) {
1155
- return this.records.createRecord(record);
1156
- }
1157
- updateRecord(patch) {
1158
- return this.records.updateRecord(patch);
1159
- }
1160
- async deleteRecord() {
1161
- await this.records.deleteRecord();
1162
- await this.messages.deleteMessages();
1163
- await this.producers.deleteProducerStates();
1164
- this.timeout.cancel();
1165
- this.deleteFromState();
1555
+ /** Public append intent (no `createRecord`). */
1556
+ append(plan) {
1557
+ const out = this.applyMutation({
1558
+ preconditions: plan.preconditions,
1559
+ messages: plan.messages,
1560
+ recordPatch: plan.recordPatch
1561
+ });
1562
+ if (out.status === "committed") return {
1563
+ status: "appended",
1564
+ record: out.record
1565
+ };
1566
+ return {
1567
+ status: "precondition-failed",
1568
+ record: out.record,
1569
+ reason: out.reason ?? "offset"
1570
+ };
1166
1571
  }
1167
- appendMessages(messages) {
1168
- return this.messages.appendMessages(messages);
1572
+ /**
1573
+ * Adapter-internal write engine shared by `append` (no `createRecord`) and the
1574
+ * `create`/`fork` intents (with `createRecord`).
1575
+ */
1576
+ applyMutation(plan) {
1577
+ let record = this.records.getRecord();
1578
+ if (plan.createRecord) {
1579
+ if (record) return {
1580
+ status: "precondition-failed",
1581
+ record
1582
+ };
1583
+ const created = this.records.createRecord(plan.createRecord);
1584
+ if (created.status === "exists") return {
1585
+ status: "precondition-failed",
1586
+ record: created.record
1587
+ };
1588
+ record = this.records.getRecord();
1589
+ }
1590
+ if (!record) return {
1591
+ status: "precondition-failed",
1592
+ record: null
1593
+ };
1594
+ if (plan.preconditions.expectedOffset !== void 0 && plan.preconditions.expectedOffset !== record.currentOffset) return {
1595
+ status: "precondition-failed",
1596
+ record,
1597
+ reason: "offset"
1598
+ };
1599
+ if (plan.preconditions.expectedClosed !== void 0 && plan.preconditions.expectedClosed !== (record.lifecycle.closed === true)) return {
1600
+ status: "precondition-failed",
1601
+ record,
1602
+ reason: "closed"
1603
+ };
1604
+ const producer = plan.preconditions.producer;
1605
+ if (producer) {
1606
+ const current = this.producers.getProducerState(producer.producerId);
1607
+ if (!producerStatesEqual(current, producer.expected)) return {
1608
+ status: "precondition-failed",
1609
+ record,
1610
+ reason: "producer"
1611
+ };
1612
+ }
1613
+ if (plan.messages && plan.messages.length > 0) this.messages.appendMessages(plan.messages);
1614
+ if (plan.recordPatch) record = this.records.updateRecord(plan.recordPatch);
1615
+ if (producer) this.producers.setProducerState(producer.producerId, producer.next);
1616
+ this.notifier.wake();
1617
+ return {
1618
+ status: "committed",
1619
+ record: this.records.getRecord() ?? record
1620
+ };
1169
1621
  }
1170
1622
  listMessages(options) {
1171
1623
  return this.messages.listMessages(options);
1172
1624
  }
1173
- deleteMessages() {
1174
- return this.messages.deleteMessages();
1175
- }
1176
1625
  getProducerState(producerId) {
1177
1626
  return this.producers.getProducerState(producerId);
1178
1627
  }
1179
- setProducerState(producerId, state) {
1180
- return this.producers.setProducerState(producerId, state);
1181
- }
1182
- deleteProducerStates() {
1183
- return this.producers.deleteProducerStates();
1184
- }
1185
- incrementChildRefCount() {
1186
- return this.records.incrementChildRefCount();
1187
- }
1188
- decrementChildRefCount() {
1189
- return this.records.decrementChildRefCount();
1190
- }
1191
- withMutationLock(fn) {
1192
- return this.lock.withLock(fn);
1628
+ purgeSelf() {
1629
+ this.messages.deleteMessages();
1630
+ this.producers.deleteProducerStates();
1631
+ this.records.deleteRecord();
1632
+ this.timeout.cancel();
1633
+ this.deleteFromState();
1634
+ this.notifier.wake();
1193
1635
  }
1194
- waitForEvent(options) {
1195
- return this.notifier.waitForEvent(options);
1636
+ softDelete() {
1637
+ this.records.updateRecord({ lifecycle: { softDeleted: true } });
1638
+ this.notifier.wake();
1196
1639
  }
1197
- notify(type) {
1198
- return this.notifier.notify(type);
1640
+ /**
1641
+ * Level-triggered live wait via the shared exported loop: re-read durable
1642
+ * state first (so a mutation that landed between the caller's observation and
1643
+ * this call is never missed), then park on the wake bus until the state
1644
+ * advances or the budget expires. Read and park are synchronous with the wake
1645
+ * bus here, so no per-park cap is needed.
1646
+ */
1647
+ awaitChange(options) {
1648
+ return runAwaitChangeLoop({
1649
+ readRecord: () => this.records.getRecord(),
1650
+ waitForWake: (timeoutMs) => this.notifier.waitForWake(timeoutMs)
1651
+ }, options);
1199
1652
  }
1200
- scheduleExpiry(at, callback) {
1201
- return this.timeout.schedule(at, callback);
1653
+ scheduleExpiry(at) {
1654
+ return this.timeout.schedule(at);
1202
1655
  }
1203
1656
  cancelExpiry() {
1204
1657
  return this.timeout.cancel();
1205
1658
  }
1206
1659
  };
1660
+ function producerStatesEqual(left, right) {
1661
+ if (!left || !right) return left === right;
1662
+ return left.epoch === right.epoch && left.lastSeq === right.lastSeq;
1663
+ }
1207
1664
 
1208
1665
  //#endregion
1209
1666
  //#region src/storage/memory/state.ts
1210
1667
  /** Shared in-memory stream registry. */
1211
1668
  var MemoryStreamState = class {
1212
1669
  streams = new Map();
1670
+ childEdges = new Map();
1671
+ constructor(onScheduledExpiry) {
1672
+ this.onScheduledExpiry = onScheduledExpiry;
1673
+ }
1213
1674
  getStream(id) {
1214
1675
  let stream = this.streams.get(id);
1215
1676
  if (!stream) {
1216
- stream = new MemoryStream(id, () => this.streams.delete(id));
1677
+ stream = new MemoryStream(id, () => this.deleteStream(id), () => this.onScheduledExpiry?.(id));
1217
1678
  this.streams.set(id, stream);
1218
1679
  }
1219
1680
  return stream;
1220
1681
  }
1221
- stream(id) {
1222
- return this.getStream(id);
1682
+ getExistingStream(id) {
1683
+ return this.streams.get(id);
1684
+ }
1685
+ addEdge(parent, child) {
1686
+ const children = this.childEdges.get(parent) ?? new Set();
1687
+ children.add(child);
1688
+ this.childEdges.set(parent, children);
1689
+ }
1690
+ dropEdge(parent, child) {
1691
+ const children = this.childEdges.get(parent);
1692
+ if (!children) return;
1693
+ children.delete(child);
1694
+ if (children.size === 0) this.childEdges.delete(parent);
1695
+ }
1696
+ countDependents(parent) {
1697
+ return this.childEdges.get(parent)?.size ?? 0;
1698
+ }
1699
+ deleteStream(id) {
1700
+ this.streams.delete(id);
1701
+ this.childEdges.delete(id);
1223
1702
  }
1224
1703
  };
1225
1704
 
1226
1705
  //#endregion
1227
- //#region src/storage/memory/factory.ts
1228
- function createMemoryStreamFactory(options = {}) {
1229
- const state = options.state ?? new MemoryStreamState();
1230
- return { async getStream(streamId) {
1231
- return state.getStream(streamId);
1232
- } };
1706
+ //#region src/storage/memory/adapter.ts
1707
+ function createMemoryStorageAdapter(options = {}) {
1708
+ const state = options.state ?? new MemoryStreamState(options.onScheduledExpiry);
1709
+ const lineageStore = new MemoryLineageStore(state);
1710
+ const lineage = refCountLineage(lineageStore);
1711
+ return {
1712
+ getRecord: (streamId) => Promise.resolve(state.getStream(streamId).getRecord()),
1713
+ listMessages: (streamId, listOptions) => Promise.resolve(state.getStream(streamId).listMessages(listOptions)),
1714
+ getProducerState: (streamId, producerId) => Promise.resolve(state.getStream(streamId).getProducerState(producerId)),
1715
+ append: (streamId, plan) => Promise.resolve(state.getStream(streamId).append(plan)),
1716
+ awaitChange: (streamId, awaitOptions) => state.getStream(streamId).awaitChange(awaitOptions),
1717
+ scheduleExpiry: (streamId, at) => state.getStream(streamId).scheduleExpiry(at),
1718
+ cancelExpiry: (streamId) => state.getStream(streamId).cancelExpiry(),
1719
+ async create(plan) {
1720
+ const stream = state.getStream(plan.record.id);
1721
+ const result = stream.applyMutation({
1722
+ createRecord: plan.record,
1723
+ preconditions: {},
1724
+ messages: plan.initialMessages
1725
+ });
1726
+ if (result.status === "committed") return {
1727
+ status: "created",
1728
+ record: result.record
1729
+ };
1730
+ return {
1731
+ status: "exists",
1732
+ record: result.record ?? plan.record
1733
+ };
1734
+ },
1735
+ async fork(plan) {
1736
+ const source = state.getExistingStream(plan.sourceId)?.getRecord() ?? null;
1737
+ if (!source || source.lifecycle.softDeleted || compareOffsets(source.currentOffset, plan.precondition.sourceLiveAtOffset) < 0) return { status: "fork-source-gone" };
1738
+ const child = state.getStream(plan.child.id);
1739
+ const result = child.applyMutation({
1740
+ createRecord: plan.child,
1741
+ preconditions: {},
1742
+ messages: plan.initialMessages
1743
+ });
1744
+ if (result.status !== "committed") {
1745
+ const existing = result.record ?? child.getRecord() ?? plan.child;
1746
+ if (existing.lifecycle.forkedFrom === plan.sourceId) await lineage.addEdge(plan.sourceId, plan.child.id);
1747
+ return {
1748
+ status: "exists",
1749
+ record: existing
1750
+ };
1751
+ }
1752
+ await lineage.addEdge(plan.sourceId, plan.child.id);
1753
+ return {
1754
+ status: "created",
1755
+ record: result.record
1756
+ };
1757
+ },
1758
+ delete(plan) {
1759
+ return cascadeReclaim(lineageStore, plan, lineage);
1760
+ }
1761
+ };
1233
1762
  }
1234
1763
 
1235
1764
  //#endregion
@@ -1275,6 +1804,7 @@ var HttpDispatchService = class {
1275
1804
  default: return this.deps.responses.methodNotAllowed();
1276
1805
  }
1277
1806
  } catch (error) {
1807
+ if (isNotSupportedError(error)) return notSupportedResponse(notSupportedFromError(error), this.deps.responses);
1278
1808
  console.error("Error handling request:", error);
1279
1809
  return this.deps.responses.internalError();
1280
1810
  }
@@ -1376,12 +1906,15 @@ var ProducerHeaderParser = class {
1376
1906
  //#endregion
1377
1907
  //#region src/http/read-query-parser.ts
1378
1908
  var ReadQueryParser = class {
1909
+ constructor(isValidOffset$1) {
1910
+ this.isValidOffset = isValidOffset$1;
1911
+ }
1379
1912
  parse(url) {
1380
1913
  const offset = url.searchParams.get("offset") ?? void 0;
1381
1914
  const liveParam = url.searchParams.get("live");
1382
1915
  const cursor = url.searchParams.get("cursor") ?? void 0;
1383
1916
  const live = liveParam === "long-poll" || liveParam === "sse" ? liveParam : void 0;
1384
- if (offset !== void 0 && offset !== "-1" && offset !== "now" && !/^\d+_\d+$/.test(offset)) return {
1917
+ if (offset !== void 0 && offset !== "-1" && offset !== "now" && !this.isValidOffset(offset)) return {
1385
1918
  ok: false,
1386
1919
  response: new Response("Invalid offset format", { status: 400 })
1387
1920
  };
@@ -1586,7 +2119,7 @@ var AppendHttpService = class {
1586
2119
  response: this.deps.responses.badRequest("Invalid producer headers")
1587
2120
  };
1588
2121
  const expectedOffset = request.headers.get("stream-expected-offset") ?? void 0;
1589
- if (expectedOffset !== void 0 && !isValidOffset(expectedOffset)) return {
2122
+ if (expectedOffset !== void 0 && !this.deps.isValidOffset(expectedOffset)) return {
1590
2123
  ok: false,
1591
2124
  response: this.deps.responses.badRequest("Invalid expected offset")
1592
2125
  };
@@ -1642,6 +2175,7 @@ var AppendHttpService = class {
1642
2175
  if (result.conflictReason === "expected-offset") return this.deps.responses.conflict("Expected offset mismatch", { "stream-next-offset": result.offset });
1643
2176
  return this.deps.responses.conflict(result.conflictReason === "content-type" ? "Content-Type mismatch" : "Sequence conflict");
1644
2177
  }
2178
+ case "busy": return this.deps.responses.text("Stream busy, retry later", 503);
1645
2179
  case "stale-epoch": return this.deps.responses.text("Stale producer epoch", 403, { "producer-epoch": String(result.currentEpoch) });
1646
2180
  case "producer-gap": return this.deps.responses.conflict("Producer sequence gap", {
1647
2181
  "producer-expected-seq": String(result.expectedSeq),
@@ -1687,7 +2221,8 @@ var CreateHttpService = class {
1687
2221
  initialData: normalized.initialData,
1688
2222
  closed: parsed.wantClosed,
1689
2223
  forkedFrom: parsed.forkedFromStreamId,
1690
- forkOffset: parsed.forkOffset
2224
+ forkOffset: parsed.forkOffset,
2225
+ forkSubOffset: parsed.forkSubOffset
1691
2226
  });
1692
2227
  if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
1693
2228
  return this.toResponse(result, ctx.request.url);
@@ -1698,6 +2233,7 @@ var CreateHttpService = class {
1698
2233
  const expiresAtHeader = request.headers.get("stream-expires-at");
1699
2234
  const forkedFromHeader = request.headers.get("stream-forked-from");
1700
2235
  const forkOffsetHeader = request.headers.get("stream-fork-offset");
2236
+ const forkSubOffsetHeader = request.headers.get("stream-fork-sub-offset");
1701
2237
  if (ttlHeader && !/^(0|[1-9]\d*)$/.test(ttlHeader)) return {
1702
2238
  ok: false,
1703
2239
  response: this.deps.responses.badRequest("Invalid Stream-TTL format")
@@ -1714,6 +2250,20 @@ var CreateHttpService = class {
1714
2250
  ok: false,
1715
2251
  response: this.deps.responses.badRequest("Stream-Fork-Offset requires Stream-Forked-From")
1716
2252
  };
2253
+ if (forkSubOffsetHeader !== null) {
2254
+ if (!forkedFromHeader) return {
2255
+ ok: false,
2256
+ response: this.deps.responses.badRequest("Stream-Fork-Sub-Offset requires Stream-Forked-From")
2257
+ };
2258
+ if (!/^(0|[1-9]\d*)$/.test(forkSubOffsetHeader)) return {
2259
+ ok: false,
2260
+ response: this.deps.responses.badRequest("Invalid Stream-Fork-Sub-Offset format")
2261
+ };
2262
+ if (parseInt(forkSubOffsetHeader, 10) > 0 && !forkOffsetHeader) return {
2263
+ ok: false,
2264
+ response: this.deps.responses.badRequest("Stream-Fork-Sub-Offset greater than zero requires Stream-Fork-Offset")
2265
+ };
2266
+ }
1717
2267
  const isFork = !!forkedFromHeader;
1718
2268
  return {
1719
2269
  ok: true,
@@ -1722,7 +2272,8 @@ var CreateHttpService = class {
1722
2272
  expiresAt: expiresAtHeader ?? void 0,
1723
2273
  wantClosed: request.headers.get("stream-closed")?.toLowerCase() === "true",
1724
2274
  forkedFromStreamId: forkedFromHeader ? this.deps.path.canonicalizeForkSource(forkedFromHeader) : void 0,
1725
- forkOffset: forkOffsetHeader ?? void 0
2275
+ forkOffset: forkOffsetHeader ?? void 0,
2276
+ forkSubOffset: forkSubOffsetHeader !== null ? parseInt(forkSubOffsetHeader, 10) : void 0
1726
2277
  };
1727
2278
  }
1728
2279
  normalizeInitialData(data, contentType) {
@@ -2059,7 +2610,7 @@ var HttpHandler = class {
2059
2610
  const bodyReader = new RequestBodyReader(options.maxMessageSize ?? 1024 * 1024, responses);
2060
2611
  const bodyCodec = new MessageBodyCodec();
2061
2612
  const producerHeaders = new ProducerHeaderParser();
2062
- const readQuery = new ReadQueryParser();
2613
+ const readQuery = new ReadQueryParser((offset) => options.protocol.isValidOffset(offset));
2063
2614
  const etags = new EtagBuilder();
2064
2615
  const sseEvents = new SseEventEncoder(bodyCodec);
2065
2616
  const longPoll = new LongPollHttpService({
@@ -2084,7 +2635,8 @@ var HttpHandler = class {
2084
2635
  append: new AppendHttpService({
2085
2636
  responses,
2086
2637
  bodyReader,
2087
- producerHeaders
2638
+ producerHeaders,
2639
+ isValidOffset: (offset) => options.protocol.isValidOffset(offset)
2088
2640
  }),
2089
2641
  read: new ReadHttpService({
2090
2642
  responses,
@@ -2128,6 +2680,7 @@ var ReadOnlyHttpDispatchService = class {
2128
2680
  default: return this.deps.responses.methodNotAllowed();
2129
2681
  }
2130
2682
  } catch (error) {
2683
+ if (isNotSupportedError(error)) return notSupportedResponse(notSupportedFromError(error), this.deps.responses);
2131
2684
  console.error("Error handling request:", error);
2132
2685
  return this.deps.responses.internalError();
2133
2686
  }
@@ -2155,7 +2708,7 @@ var ReadOnlyHttpHandler = class {
2155
2708
  const path = new StreamPathService(options.pathPrefix ?? "/");
2156
2709
  const responses = new HttpResponseFactory();
2157
2710
  const bodyCodec = new MessageBodyCodec();
2158
- const readQuery = new ReadQueryParser();
2711
+ const readQuery = new ReadQueryParser((offset) => options.protocol.isValidOffset(offset));
2159
2712
  const etags = new EtagBuilder();
2160
2713
  const sseEvents = new SseEventEncoder(bodyCodec);
2161
2714
  const longPoll = new LongPollHttpService({
@@ -2188,4 +2741,1138 @@ var ReadOnlyHttpHandler = class {
2188
2741
  };
2189
2742
 
2190
2743
  //#endregion
2191
- export { HttpHandler, NotSupportedError, ReadOnlyHttpHandler, StreamProtocol, ZERO_OFFSET, createHttpHandler, createMemoryStreamFactory, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, unsupported };
2744
+ //#region src/client/batch-encoding.ts
2745
+ const decoder = new TextDecoder();
2746
+ /**
2747
+ * Real impedance matching: turn a substrate's `StoredMessage[]` into a single
2748
+ * content-aware delivery batch, matching `MessageBodyCodec` semantics so direct
2749
+ * and remote consumers observe the same payload shape.
2750
+ *
2751
+ * The media type is derived from the stream content type: `application/json`
2752
+ * (parameters ignored) yields a `json` batch, `text/*` a `text` batch, and
2753
+ * everything else (including an absent content type) a `bytes` batch.
2754
+ *
2755
+ * Throws `SyntaxError` on invalid stored JSON; callers map that to a
2756
+ * `parse-error` failure.
2757
+ */
2758
+ function encodeBatch(contentType, messages, meta) {
2759
+ const mediaType = contentType.split(";", 1)[0].trim().toLowerCase();
2760
+ if (mediaType === "application/json") {
2761
+ const body = `[${messages.map((message) => decoder.decode(message.data)).join(",")}]`;
2762
+ return {
2763
+ kind: "json",
2764
+ items: JSON.parse(body),
2765
+ ...meta
2766
+ };
2767
+ }
2768
+ if (mediaType.startsWith("text/")) return {
2769
+ kind: "text",
2770
+ text: messages.map((message) => decoder.decode(message.data)).join(""),
2771
+ ...meta
2772
+ };
2773
+ const length = messages.reduce((total, message) => total + message.data.byteLength, 0);
2774
+ const data = new Uint8Array(length);
2775
+ let position = 0;
2776
+ for (const message of messages) {
2777
+ data.set(message.data, position);
2778
+ position += message.data.byteLength;
2779
+ }
2780
+ return {
2781
+ kind: "bytes",
2782
+ data,
2783
+ ...meta
2784
+ };
2785
+ }
2786
+
2787
+ //#endregion
2788
+ //#region src/client/read-session.ts
2789
+ /**
2790
+ * The single client read-session implementation, shared by every adapter.
2791
+ *
2792
+ * It is a one-consumer, one-batch queue whose producer is backpressured by
2793
+ * iterator delivery. Iteration never throws for operational failures: the
2794
+ * terminal outcome is delivered through {@link ClientReadSession.done}, which
2795
+ * always resolves. Only programmer misuse (double iteration, concurrent
2796
+ * `next()`) throws.
2797
+ */
2798
+ var ClientReadSession = class {
2799
+ done;
2800
+ contentType;
2801
+ startOffset;
2802
+ offset;
2803
+ cursor;
2804
+ upToDate;
2805
+ streamClosed;
2806
+ doneResolve;
2807
+ pending;
2808
+ waiting;
2809
+ ended = false;
2810
+ iterated = false;
2811
+ cancelHook;
2812
+ constructor(options) {
2813
+ this.contentType = options.contentType;
2814
+ this.startOffset = options.startOffset;
2815
+ this.offset = options.offset ?? options.startOffset;
2816
+ this.cursor = options.cursor;
2817
+ this.upToDate = options.upToDate ?? false;
2818
+ this.streamClosed = options.streamClosed ?? false;
2819
+ this.cancelHook = options.onCancel;
2820
+ this.done = new Promise((resolve) => {
2821
+ this.doneResolve = resolve;
2822
+ });
2823
+ }
2824
+ setCancelHook(hook) {
2825
+ this.cancelHook = hook;
2826
+ }
2827
+ [Symbol.asyncIterator]() {
2828
+ if (this.iterated) throw new Error("A stream read session can only be iterated once");
2829
+ this.iterated = true;
2830
+ return this;
2831
+ }
2832
+ next() {
2833
+ if (this.pending) return Promise.resolve(this.acceptPending());
2834
+ if (this.ended) return Promise.resolve({
2835
+ done: true,
2836
+ value: void 0
2837
+ });
2838
+ if (this.waiting) return Promise.reject(new Error("Concurrent iterator.next() calls are invalid"));
2839
+ return new Promise((resolve) => {
2840
+ this.waiting = { resolve };
2841
+ });
2842
+ }
2843
+ return() {
2844
+ this.cancel();
2845
+ return Promise.resolve({
2846
+ done: true,
2847
+ value: void 0
2848
+ });
2849
+ }
2850
+ cancel(reason) {
2851
+ if (this.ended) return;
2852
+ this.cancelHook?.(reason);
2853
+ this.end({ status: "cancelled" });
2854
+ }
2855
+ /** Producer side: hand a batch to the consumer, backpressured until accepted. */
2856
+ async deliver(batch) {
2857
+ if (this.ended) return;
2858
+ if (this.pending) throw new Error("Read session producer exceeded its one-batch buffer");
2859
+ if (this.waiting) {
2860
+ const waiting = this.waiting;
2861
+ this.waiting = void 0;
2862
+ this.updateState(batch);
2863
+ waiting.resolve({
2864
+ done: false,
2865
+ value: batch
2866
+ });
2867
+ return;
2868
+ }
2869
+ await new Promise((accepted) => {
2870
+ this.pending = {
2871
+ batch,
2872
+ accepted
2873
+ };
2874
+ });
2875
+ }
2876
+ /** Producer side: terminate the session with its outcome. Always resolves `done`. */
2877
+ end(result) {
2878
+ if (this.ended) return;
2879
+ this.ended = true;
2880
+ this.pending?.accepted();
2881
+ this.pending = void 0;
2882
+ this.waiting?.resolve({
2883
+ done: true,
2884
+ value: void 0
2885
+ });
2886
+ this.waiting = void 0;
2887
+ this.doneResolve(result);
2888
+ }
2889
+ acceptPending() {
2890
+ const pending = this.pending;
2891
+ this.pending = void 0;
2892
+ this.updateState(pending.batch);
2893
+ pending.accepted();
2894
+ return {
2895
+ done: false,
2896
+ value: pending.batch
2897
+ };
2898
+ }
2899
+ updateState(batch) {
2900
+ this.offset = batch.offset;
2901
+ this.cursor = batch.cursor;
2902
+ this.upToDate = batch.upToDate;
2903
+ this.streamClosed = batch.streamClosed;
2904
+ }
2905
+ };
2906
+
2907
+ //#endregion
2908
+ //#region src/client/direct/results.ts
2909
+ function failure(code, message, options = {}) {
2910
+ return {
2911
+ status: "error",
2912
+ code,
2913
+ message,
2914
+ httpStatus: options.httpStatus,
2915
+ retryable: options.retryable ?? false,
2916
+ cause: options.cause
2917
+ };
2918
+ }
2919
+ function abortedFailure(cause) {
2920
+ return failure("aborted", "Stream operation was aborted", { cause });
2921
+ }
2922
+ function clientClosedFailure() {
2923
+ return failure("client-closed", "Stream protocol client is closed");
2924
+ }
2925
+ /** Maps an unexpected thrown value (not a protocol result) to a failure. */
2926
+ function failureFromThrown(error) {
2927
+ if (error instanceof SyntaxError) return failure("parse-error", error.message, { cause: error });
2928
+ if (isNotSupportedError(error)) return failure("not-supported", error.message, { cause: error });
2929
+ return failure("unknown", "Stream operation failed", { cause: error });
2930
+ }
2931
+ /** Narrows the shared absent/failure statuses of a get/metadata/read result. */
2932
+ function absentResult(result) {
2933
+ if (result.status === "not-found") return { status: "not-found" };
2934
+ if (result.status === "gone") return { status: "gone" };
2935
+ return residualFailure(result);
2936
+ }
2937
+ function mapCreate(result) {
2938
+ if (result.status === "created") return {
2939
+ status: "created",
2940
+ contentType: result.contentType
2941
+ };
2942
+ if (result.status === "exists" || result.status === "conflict") return { status: "conflict" };
2943
+ return residualFailure(result);
2944
+ }
2945
+ function mapAppend(result) {
2946
+ if (result.status === "appended" || result.status === "duplicate") return { status: "appended" };
2947
+ if (result.status === "not-found") return { status: "not-found" };
2948
+ if (result.status === "gone") return { status: "gone" };
2949
+ if (result.status === "conflict") return result.conflictReason === "closed" ? { status: "closed" } : { status: "conflict" };
2950
+ return residualFailure(result);
2951
+ }
2952
+ function mapClose(result) {
2953
+ if (result.status === "appended" || result.status === "duplicate") return {
2954
+ status: "closed",
2955
+ finalOffset: result.offset
2956
+ };
2957
+ if (result.status === "not-found") return { status: "not-found" };
2958
+ if (result.status === "gone") return { status: "gone" };
2959
+ if (result.status === "conflict") return { status: "conflict" };
2960
+ return residualFailure(result);
2961
+ }
2962
+ /** Maps a mid-read terminal protocol result to a read-session failure. */
2963
+ function readFailure(result) {
2964
+ if (result.status === "not-found") return failure("unknown", "Stream not found during read");
2965
+ if (result.status === "gone") return failure("unknown", "Stream is gone during read");
2966
+ return residualFailure(result);
2967
+ }
2968
+ function residualFailure(result) {
2969
+ switch (result.status) {
2970
+ case "not-supported": return failure("not-supported", `Feature is not supported: ${result.feature}`);
2971
+ case "bad-request":
2972
+ case "invalid-epoch-seq": return failure("bad-request", "Invalid stream request");
2973
+ case "busy": return failure("busy", "Stream is busy", { retryable: true });
2974
+ default: return failure("unknown", `Unexpected stream result: ${result.status}`);
2975
+ }
2976
+ }
2977
+
2978
+ //#endregion
2979
+ //#region src/client/direct/read.ts
2980
+ const START = "-1";
2981
+ /**
2982
+ * Resolves a read into a session and drives the catch-up (and optional live)
2983
+ * pump. The pump delivers content-aware batches and never throws into the
2984
+ * consumer: it ends the session with a {@link ReadEndResult}.
2985
+ */
2986
+ async function directRead(client, id, options) {
2987
+ return client.run(options.signal, async (operationSignal) => {
2988
+ const found = await client.streamsy.get(id);
2989
+ if (found.status !== "ok") return absentResult(found);
2990
+ const metadata = await found.stream.metadata();
2991
+ if (metadata.status !== "ok") return absentResult(metadata);
2992
+ const controller = new AbortController();
2993
+ const signal = combineSignals(operationSignal, controller.signal);
2994
+ const session = new ClientReadSession({
2995
+ contentType: metadata.contentType,
2996
+ startOffset: options.offset ?? START,
2997
+ onCancel: (reason) => controller.abort(reason)
2998
+ });
2999
+ pump(found.stream, metadata.contentType, options, signal, session);
3000
+ return {
3001
+ status: "ok",
3002
+ session
3003
+ };
3004
+ });
3005
+ }
3006
+ async function pump(stream, contentType, options, signal, session) {
3007
+ let offset = options.offset ?? START;
3008
+ let cursor;
3009
+ const finish = () => session.end(signal.aborted ? { status: "cancelled" } : { status: "done" });
3010
+ try {
3011
+ while (!signal.aborted) {
3012
+ const result = await stream.read({ offset });
3013
+ if (result.status !== "ok") return session.end(readFailure(result));
3014
+ const batch = encodeBatch(contentType, result.messages, {
3015
+ offset: result.nextOffset,
3016
+ upToDate: result.upToDate,
3017
+ streamClosed: result.closed === true
3018
+ });
3019
+ await session.deliver(batch);
3020
+ offset = batch.offset;
3021
+ if (batch.streamClosed || batch.upToDate) break;
3022
+ }
3023
+ if (options.live !== "long-poll" && options.live !== "sse") return finish();
3024
+ while (!signal.aborted && !session.streamClosed) {
3025
+ const result = await stream.readLive({
3026
+ offset,
3027
+ mode: options.live,
3028
+ cursor,
3029
+ signal
3030
+ });
3031
+ if (result.status !== "ok" && result.status !== "timeout") return session.end(readFailure(result));
3032
+ const batch = encodeBatch(contentType, result.messages, {
3033
+ offset: result.nextOffset,
3034
+ cursor: result.cursor,
3035
+ upToDate: result.upToDate,
3036
+ streamClosed: result.closed === true
3037
+ });
3038
+ await session.deliver(batch);
3039
+ offset = batch.offset;
3040
+ cursor = batch.cursor;
3041
+ if (batch.streamClosed) break;
3042
+ }
3043
+ finish();
3044
+ } catch (error) {
3045
+ if (signal.aborted) session.end({ status: "cancelled" });
3046
+ else session.end(failureFromThrown(error));
3047
+ }
3048
+ }
3049
+
3050
+ //#endregion
3051
+ //#region src/client/direct/handle.ts
3052
+ const encoder = new TextEncoder();
3053
+ /** The direct handle is a thin pass-through over a `StreamProtocolFactory`. */
3054
+ var DirectProtocolHandle = class {
3055
+ id;
3056
+ constructor(client, streamId) {
3057
+ this.client = client;
3058
+ this.id = streamId;
3059
+ }
3060
+ async head(options) {
3061
+ return this.client.run(options?.signal, async () => {
3062
+ const found = await this.client.streamsy.get(this.id);
3063
+ if (found.status !== "ok") return absentResult(found);
3064
+ const metadata = await found.stream.metadata();
3065
+ if (metadata.status !== "ok") return absentResult(metadata);
3066
+ return {
3067
+ status: "ok",
3068
+ contentType: metadata.contentType,
3069
+ offset: metadata.nextOffset,
3070
+ closed: metadata.closed === true
3071
+ };
3072
+ });
3073
+ }
3074
+ async create(options = {}) {
3075
+ return this.client.run(options.signal, async () => {
3076
+ const result = await this.client.streamsy.create(this.id, {
3077
+ contentType: options.contentType,
3078
+ ttlSeconds: options.ttlSeconds,
3079
+ expiresAt: options.expiresAt,
3080
+ initialData: toBytes(options.initialData),
3081
+ closed: options.closed
3082
+ });
3083
+ return mapCreate(result);
3084
+ });
3085
+ }
3086
+ async append(data, options = {}) {
3087
+ return this.client.run(options.signal, async () => {
3088
+ if (options.contentType === void 0) return failure("bad-request", "append requires a contentType");
3089
+ const resolved = await this.resolve();
3090
+ if (!resolved.ok) return resolved.result;
3091
+ const result = await resolved.stream.append({
3092
+ data: toBytes(data),
3093
+ contentType: options.contentType,
3094
+ seq: options.seq
3095
+ });
3096
+ return mapAppend(result);
3097
+ });
3098
+ }
3099
+ async close(options = {}) {
3100
+ return this.client.run(options.signal, async () => {
3101
+ const resolved = await this.resolve();
3102
+ if (!resolved.ok) return resolved.result;
3103
+ let contentType = options.contentType;
3104
+ if (contentType === void 0) {
3105
+ const found = await this.contentTypeFor(resolved.stream);
3106
+ if (!found.ok) return found.result;
3107
+ contentType = found.contentType;
3108
+ }
3109
+ const result = await resolved.stream.append({
3110
+ data: toBytes(options.finalData) ?? new Uint8Array(),
3111
+ contentType,
3112
+ close: true
3113
+ });
3114
+ return mapClose(result);
3115
+ });
3116
+ }
3117
+ async read(options = {}) {
3118
+ return directRead(this.client, this.id, options);
3119
+ }
3120
+ async resolve() {
3121
+ const found = await this.client.streamsy.get(this.id);
3122
+ if (found.status === "ok") return {
3123
+ ok: true,
3124
+ stream: found.stream
3125
+ };
3126
+ return {
3127
+ ok: false,
3128
+ result: absentResult(found)
3129
+ };
3130
+ }
3131
+ async contentTypeFor(stream) {
3132
+ const metadata = await stream.metadata();
3133
+ if (metadata.status === "ok") return {
3134
+ ok: true,
3135
+ contentType: metadata.contentType
3136
+ };
3137
+ return {
3138
+ ok: false,
3139
+ result: absentResult(metadata)
3140
+ };
3141
+ }
3142
+ };
3143
+ function toBytes(value) {
3144
+ return typeof value === "string" ? encoder.encode(value) : value;
3145
+ }
3146
+
3147
+ //#endregion
3148
+ //#region src/client/direct/client.ts
3149
+ /** Structural refinement test: is this client the exact-Streamsy direct adapter? */
3150
+ function hasStreamsyProtocol(client) {
3151
+ return "streamsy" in client;
3152
+ }
3153
+ function directProtocolClient(factory) {
3154
+ return new DirectProtocolClient(factory);
3155
+ }
3156
+ /**
3157
+ * Adapts a `StreamProtocolFactory` to the transport-neutral client seam. It
3158
+ * keeps a single client-level abort controller whose signal is threaded into
3159
+ * every operation and read session; `close()` aborts it and rejects new work.
3160
+ * There is no session registry: sessions observe the abort through their own
3161
+ * signal and end with `{ status: "cancelled" }`.
3162
+ */
3163
+ var DirectProtocolClient = class {
3164
+ streamsy;
3165
+ controller = new AbortController();
3166
+ disposed = false;
3167
+ constructor(factory) {
3168
+ this.streamsy = factory;
3169
+ }
3170
+ stream(streamId) {
3171
+ return new DirectProtocolHandle(this, streamId);
3172
+ }
3173
+ async close(reason) {
3174
+ if (this.disposed) return;
3175
+ this.disposed = true;
3176
+ this.controller.abort(reason);
3177
+ }
3178
+ /**
3179
+ * Runs one operation under the combined client/caller signal, converting a
3180
+ * disposed client, an already-aborted signal, and unexpected throws into
3181
+ * {@link ClientFailure} members. Domain results flow through untouched.
3182
+ */
3183
+ async run(signal, work) {
3184
+ if (this.disposed) return clientClosedFailure();
3185
+ const combined = combineSignals(this.controller.signal, signal);
3186
+ if (combined.aborted) return abortedFailure(combined.reason);
3187
+ try {
3188
+ return await work(combined);
3189
+ } catch (error) {
3190
+ if (combined.aborted) return abortedFailure(combined.reason ?? error);
3191
+ return failureFromThrown(error);
3192
+ }
3193
+ }
3194
+ };
3195
+ function combineSignals(...signals) {
3196
+ const present = signals.filter((signal) => signal !== void 0);
3197
+ if (present.length === 0) return new AbortController().signal;
3198
+ return present.length === 1 ? present[0] : AbortSignal.any(present);
3199
+ }
3200
+
3201
+ //#endregion
3202
+ //#region src/testing/storage-adapter-contract.ts
3203
+ const TEXT_TYPE = "text/plain";
3204
+ const OFFSET_1 = formatCounter(1);
3205
+ /**
3206
+ * Mechanical enforcement of the seam invariant: every argument and result must
3207
+ * survive `structuredClone` (the Durable Object RPC boundary). The wrapper
3208
+ * clones on the way in AND on the way out, so a non-serializable value crossing
3209
+ * the seam throws on every backend — including in-process ones that would
3210
+ * otherwise pass by reference.
3211
+ */
3212
+ const clone = (value) => structuredClone(value);
3213
+ function withSerializedSeam(adapter) {
3214
+ const wrapped = {
3215
+ getRecord: async (streamId) => clone(await adapter.getRecord(clone(streamId))),
3216
+ listMessages: async (streamId, options) => clone(await adapter.listMessages(clone(streamId), clone(options))),
3217
+ getProducerState: async (streamId, producerId) => clone(await adapter.getProducerState(clone(streamId), clone(producerId))),
3218
+ append: async (streamId, plan) => clone(await adapter.append(clone(streamId), clone(plan))),
3219
+ awaitChange: async (streamId, options) => clone(await adapter.awaitChange(clone(streamId), clone(options))),
3220
+ scheduleExpiry: (streamId, at) => adapter.scheduleExpiry(clone(streamId), clone(at)),
3221
+ cancelExpiry: (streamId) => adapter.cancelExpiry(clone(streamId)),
3222
+ create: async (plan) => clone(await adapter.create(clone(plan))),
3223
+ delete: async (plan) => clone(await adapter.delete(clone(plan)))
3224
+ };
3225
+ const fork = adapter.fork;
3226
+ if (fork) wrapped.fork = async (plan) => clone(await fork.call(adapter, clone(plan)));
3227
+ return wrapped;
3228
+ }
3229
+ /** Wrap `makeAdapter` so every case exercises the serializability wrapper. */
3230
+ function serialized(makeAdapter) {
3231
+ return async () => withSerializedSeam(await makeAdapter());
3232
+ }
3233
+ function encode(value) {
3234
+ return new TextEncoder().encode(value);
3235
+ }
3236
+ function assert(condition, message) {
3237
+ if (!condition) throw new Error(`storage-adapter-contract: ${message}`);
3238
+ }
3239
+ function assertStatus(result, expected, label) {
3240
+ if (result.status !== expected) throw new Error(`storage-adapter-contract: ${label} — expected status "${expected}", got "${result.status}"`);
3241
+ }
3242
+ function newRecord(id, forkedFrom) {
3243
+ return {
3244
+ id,
3245
+ config: {
3246
+ contentType: TEXT_TYPE,
3247
+ createdAt: 0
3248
+ },
3249
+ lifecycle: forkedFrom ? {
3250
+ forkedFrom,
3251
+ forkOffset: ZERO_OFFSET
3252
+ } : {},
3253
+ currentOffset: ZERO_OFFSET,
3254
+ counter: 0
3255
+ };
3256
+ }
3257
+ async function currentRecord(adapter, id) {
3258
+ const record = await adapter.getRecord(id);
3259
+ assert(record, `expected record for stream "${id}"`);
3260
+ return record;
3261
+ }
3262
+ /** Build an append plan that advances the tail by `texts.length` messages. */
3263
+ function advancePlan(record, texts) {
3264
+ const allocation = allocate(defaultOffsetGenerator, record.currentOffset, record.counter, texts.length);
3265
+ return {
3266
+ preconditions: {
3267
+ expectedOffset: record.currentOffset,
3268
+ expectedClosed: false
3269
+ },
3270
+ messages: texts.map((value, index) => ({
3271
+ data: encode(value),
3272
+ offset: allocation.offsets[index],
3273
+ timestamp: 0
3274
+ })),
3275
+ recordPatch: {
3276
+ currentOffset: allocation.nextOffset,
3277
+ counter: allocation.endCounter
3278
+ }
3279
+ };
3280
+ }
3281
+ async function appendTexts(adapter, id, texts) {
3282
+ const record = await currentRecord(adapter, id);
3283
+ return adapter.append(id, advancePlan(record, texts));
3284
+ }
3285
+ async function createStream(adapter, id) {
3286
+ const result = await adapter.create({ record: newRecord(id) });
3287
+ assertStatus(result, "created", `create("${id}")`);
3288
+ }
3289
+ /** Bind the adapter's required level-triggered `awaitChange` to a stream id. */
3290
+ function awaitChangeFor(adapter) {
3291
+ return (id, options) => adapter.awaitChange(id, options);
3292
+ }
3293
+ function delay(ms) {
3294
+ return new Promise((resolve) => setTimeout(resolve, ms));
3295
+ }
3296
+ /** Let a freshly-started `awaitChange` register its waiter before we mutate. */
3297
+ function tick() {
3298
+ return new Promise((resolve) => setTimeout(resolve, 0));
3299
+ }
3300
+ /** Resolves `true` if `promise` is still unsettled after `ms`. */
3301
+ function staysPending(promise, ms) {
3302
+ return Promise.race([promise.then(() => false, () => false), delay(ms).then(() => true)]);
3303
+ }
3304
+ function runAppendContract(makeAdapter, harness) {
3305
+ harness.it("append advances the tail and folds close", async () => {
3306
+ const adapter = await makeAdapter();
3307
+ await createStream(adapter, "s");
3308
+ const appended = await appendTexts(adapter, "s", ["a", "b"]);
3309
+ assertStatus(appended, "appended", "append");
3310
+ assert(appended.status === "appended", "append narrows");
3311
+ assert(appended.record.counter === 2, "counter advanced to 2");
3312
+ assert(appended.record.currentOffset === formatCounter(2), "offset advanced");
3313
+ assert((await adapter.listMessages("s")).length === 2, "two messages listable");
3314
+ const record = await currentRecord(adapter, "s");
3315
+ const closed = await adapter.append("s", {
3316
+ preconditions: {
3317
+ expectedOffset: record.currentOffset,
3318
+ expectedClosed: false
3319
+ },
3320
+ messages: [],
3321
+ recordPatch: { lifecycle: {
3322
+ closed: true,
3323
+ closedAt: 0
3324
+ } }
3325
+ });
3326
+ assertStatus(closed, "appended", "close append");
3327
+ assert(closed.status === "appended" && closed.record.lifecycle.closed === true, "closed folded");
3328
+ });
3329
+ harness.it("append rejects a stale expectedOffset with reason 'offset' and writes nothing", async () => {
3330
+ const adapter = await makeAdapter();
3331
+ await createStream(adapter, "s");
3332
+ await appendTexts(adapter, "s", ["a"]);
3333
+ const stale = await adapter.append("s", {
3334
+ preconditions: {
3335
+ expectedOffset: ZERO_OFFSET,
3336
+ expectedClosed: false
3337
+ },
3338
+ messages: [{
3339
+ data: encode("b"),
3340
+ offset: formatCounter(2),
3341
+ timestamp: 0
3342
+ }],
3343
+ recordPatch: {
3344
+ currentOffset: formatCounter(2),
3345
+ counter: 2
3346
+ }
3347
+ });
3348
+ assertStatus(stale, "precondition-failed", "stale offset");
3349
+ assert(stale.status === "precondition-failed" && stale.reason === "offset", "reason offset");
3350
+ const record = await currentRecord(adapter, "s");
3351
+ assert(record.currentOffset === OFFSET_1 && record.counter === 1, "tail unchanged");
3352
+ assert((await adapter.listMessages("s")).length === 1, "no extra message written");
3353
+ });
3354
+ harness.it("append rejects a violated expectedClosed with reason 'closed' and writes nothing", async () => {
3355
+ const adapter = await makeAdapter();
3356
+ await createStream(adapter, "s");
3357
+ const failed = await adapter.append("s", {
3358
+ preconditions: {
3359
+ expectedOffset: ZERO_OFFSET,
3360
+ expectedClosed: true
3361
+ },
3362
+ messages: [{
3363
+ data: encode("a"),
3364
+ offset: OFFSET_1,
3365
+ timestamp: 0
3366
+ }],
3367
+ recordPatch: {
3368
+ currentOffset: OFFSET_1,
3369
+ counter: 1
3370
+ }
3371
+ });
3372
+ assertStatus(failed, "precondition-failed", "closed precondition");
3373
+ assert(failed.status === "precondition-failed" && failed.reason === "closed", "reason closed");
3374
+ const record = await currentRecord(adapter, "s");
3375
+ assert(record.currentOffset === ZERO_OFFSET && record.counter === 0, "tail unchanged");
3376
+ assert((await adapter.listMessages("s")).length === 0, "no message written");
3377
+ });
3378
+ harness.it("append rejects a failed producer CAS with reason 'producer' and writes nothing", async () => {
3379
+ const adapter = await makeAdapter();
3380
+ await createStream(adapter, "s");
3381
+ const seeded = await adapter.append("s", {
3382
+ preconditions: {
3383
+ expectedOffset: ZERO_OFFSET,
3384
+ expectedClosed: false,
3385
+ producer: {
3386
+ producerId: "p",
3387
+ expected: void 0,
3388
+ next: {
3389
+ epoch: 1,
3390
+ lastSeq: 0
3391
+ }
3392
+ }
3393
+ },
3394
+ messages: [{
3395
+ data: encode("a"),
3396
+ offset: OFFSET_1,
3397
+ timestamp: 0
3398
+ }],
3399
+ recordPatch: {
3400
+ currentOffset: OFFSET_1,
3401
+ counter: 1
3402
+ }
3403
+ });
3404
+ assertStatus(seeded, "appended", "seed producer");
3405
+ const record = await currentRecord(adapter, "s");
3406
+ const failed = await adapter.append("s", {
3407
+ preconditions: {
3408
+ expectedOffset: record.currentOffset,
3409
+ expectedClosed: false,
3410
+ producer: {
3411
+ producerId: "p",
3412
+ expected: {
3413
+ epoch: 9,
3414
+ lastSeq: 9
3415
+ },
3416
+ next: {
3417
+ epoch: 2,
3418
+ lastSeq: 0
3419
+ }
3420
+ }
3421
+ },
3422
+ messages: [{
3423
+ data: encode("b"),
3424
+ offset: formatCounter(2),
3425
+ timestamp: 0
3426
+ }],
3427
+ recordPatch: {
3428
+ currentOffset: formatCounter(2),
3429
+ counter: 2
3430
+ }
3431
+ });
3432
+ assertStatus(failed, "precondition-failed", "producer CAS");
3433
+ assert(failed.status === "precondition-failed" && failed.reason === "producer", "reason producer");
3434
+ const after = await currentRecord(adapter, "s");
3435
+ assert(after.currentOffset === OFFSET_1 && after.counter === 1, "tail unchanged on CAS failure");
3436
+ assert((await adapter.listMessages("s")).length === 1, "no message written on CAS failure");
3437
+ const producer = await adapter.getProducerState("s", "p");
3438
+ assert(producer?.epoch === 1 && producer.lastSeq === 0, "producer state unchanged");
3439
+ });
3440
+ harness.it("append rejects an absent-expected producer CAS when the producer already exists", async () => {
3441
+ const adapter = await makeAdapter();
3442
+ await createStream(adapter, "s");
3443
+ const seeded = await adapter.append("s", {
3444
+ preconditions: {
3445
+ expectedOffset: ZERO_OFFSET,
3446
+ expectedClosed: false,
3447
+ producer: {
3448
+ producerId: "p",
3449
+ next: {
3450
+ epoch: 1,
3451
+ lastSeq: 0
3452
+ }
3453
+ }
3454
+ },
3455
+ messages: [{
3456
+ data: encode("a"),
3457
+ offset: OFFSET_1,
3458
+ timestamp: 0
3459
+ }],
3460
+ recordPatch: {
3461
+ currentOffset: OFFSET_1,
3462
+ counter: 1
3463
+ }
3464
+ });
3465
+ assertStatus(seeded, "appended", "seed producer");
3466
+ const record = await currentRecord(adapter, "s");
3467
+ const failed = await adapter.append("s", {
3468
+ preconditions: {
3469
+ expectedOffset: record.currentOffset,
3470
+ expectedClosed: false,
3471
+ producer: {
3472
+ producerId: "p",
3473
+ next: {
3474
+ epoch: 2,
3475
+ lastSeq: 0
3476
+ }
3477
+ }
3478
+ },
3479
+ messages: [{
3480
+ data: encode("b"),
3481
+ offset: formatCounter(2),
3482
+ timestamp: 0
3483
+ }],
3484
+ recordPatch: {
3485
+ currentOffset: formatCounter(2),
3486
+ counter: 2
3487
+ }
3488
+ });
3489
+ assertStatus(failed, "precondition-failed", "absent-expected CAS on existing producer");
3490
+ assert(failed.status === "precondition-failed" && failed.reason === "producer", "reason producer");
3491
+ const producer = await adapter.getProducerState("s", "p");
3492
+ assert(producer?.epoch === 1 && producer.lastSeq === 0, "producer state unchanged");
3493
+ assert((await adapter.listMessages("s")).length === 1, "no message written");
3494
+ });
3495
+ harness.it("append accepts a lifecycle-only TTL touch without advancing the tail", async () => {
3496
+ const adapter = await makeAdapter();
3497
+ await createStream(adapter, "s");
3498
+ const before = await currentRecord(adapter, "s");
3499
+ const touched = await adapter.append("s", {
3500
+ preconditions: {
3501
+ expectedOffset: before.currentOffset,
3502
+ expectedClosed: false
3503
+ },
3504
+ recordPatch: { lifecycle: { expiresAtMs: 1e6 } }
3505
+ });
3506
+ assertStatus(touched, "appended", "touch");
3507
+ assert(touched.status === "appended", "touch narrows");
3508
+ assert(touched.record.currentOffset === before.currentOffset, "touch keeps offset");
3509
+ assert(touched.record.counter === before.counter, "touch keeps counter");
3510
+ assert(touched.record.lifecycle.expiresAtMs === 1e6, "touch renewed deadline");
3511
+ assert((await adapter.listMessages("s")).length === 0, "touch wrote no messages");
3512
+ });
3513
+ }
3514
+ function runReadContract(makeAdapter, harness) {
3515
+ harness.it("listMessages windows by lexicographic offset order: exclusive after, inclusive until", async () => {
3516
+ const adapter = await makeAdapter();
3517
+ await createStream(adapter, "s");
3518
+ const appended = await appendTexts(adapter, "s", [
3519
+ "a",
3520
+ "b",
3521
+ "c",
3522
+ "d"
3523
+ ]);
3524
+ assertStatus(appended, "appended", "seed messages");
3525
+ const all = await adapter.listMessages("s");
3526
+ assert(all.length === 4, "four messages listable");
3527
+ const sorted = all.map((m) => m.offset).toSorted();
3528
+ assert(all.every((m, i) => m.offset === sorted[i]), "messages returned in lexicographic offset order");
3529
+ const afterFirst = await adapter.listMessages("s", { after: formatCounter(1) });
3530
+ assert(afterFirst.length === 3, "after excludes the boundary message");
3531
+ assert(afterFirst[0].offset === formatCounter(2), "after starts past the boundary");
3532
+ const untilThird = await adapter.listMessages("s", { until: formatCounter(3) });
3533
+ assert(untilThird.length === 3, "until includes the boundary message");
3534
+ assert(untilThird[2].offset === formatCounter(3), "until ends at the boundary");
3535
+ const window = await adapter.listMessages("s", {
3536
+ after: formatCounter(1),
3537
+ until: formatCounter(3),
3538
+ limit: 1
3539
+ });
3540
+ assert(window.length === 1 && window[0].offset === formatCounter(2), "window + limit");
3541
+ });
3542
+ }
3543
+ function runAwaitChangeContract(makeAdapter, harness) {
3544
+ harness.it("awaitChange returns 'changed' immediately when the tail already advanced", async () => {
3545
+ const adapter = await makeAdapter();
3546
+ const awaitChange = awaitChangeFor(adapter);
3547
+ await createStream(adapter, "s");
3548
+ await appendTexts(adapter, "s", ["a"]);
3549
+ const result = await awaitChange("s", {
3550
+ fromOffset: ZERO_OFFSET,
3551
+ observedClosed: false,
3552
+ observedSoftDeleted: false,
3553
+ timeoutMs: 1e3
3554
+ });
3555
+ assertStatus(result, "changed", "immediate change");
3556
+ assert(result.snapshot.currentOffset === OFFSET_1, "snapshot reflects the new tail");
3557
+ });
3558
+ harness.it("awaitChange times out with a fresh snapshot when nothing changes", async () => {
3559
+ const adapter = await makeAdapter();
3560
+ const awaitChange = awaitChangeFor(adapter);
3561
+ await createStream(adapter, "s");
3562
+ const record = await currentRecord(adapter, "s");
3563
+ const result = await awaitChange("s", {
3564
+ fromOffset: record.currentOffset,
3565
+ observedClosed: false,
3566
+ observedSoftDeleted: false,
3567
+ timeoutMs: 80
3568
+ });
3569
+ assertStatus(result, "timeout", "timeout");
3570
+ assert(result.snapshot.present === true, "snapshot present");
3571
+ assert(result.snapshot.currentOffset === ZERO_OFFSET, "snapshot at the parked tail");
3572
+ });
3573
+ harness.it("awaitChange wakes a parked waiter on a committing append", async () => {
3574
+ const adapter = await makeAdapter();
3575
+ const awaitChange = awaitChangeFor(adapter);
3576
+ await createStream(adapter, "s");
3577
+ const record = await currentRecord(adapter, "s");
3578
+ const pending = awaitChange("s", {
3579
+ fromOffset: record.currentOffset,
3580
+ observedClosed: false,
3581
+ observedSoftDeleted: false,
3582
+ timeoutMs: 2e3
3583
+ });
3584
+ await tick();
3585
+ await appendTexts(adapter, "s", ["a"]);
3586
+ const result = await pending;
3587
+ assertStatus(result, "changed", "wake on append");
3588
+ assert(result.snapshot.currentOffset === OFFSET_1, "snapshot reflects the append");
3589
+ });
3590
+ harness.it("awaitChange wakes a parked waiter on a close transition", async () => {
3591
+ const adapter = await makeAdapter();
3592
+ const awaitChange = awaitChangeFor(adapter);
3593
+ await createStream(adapter, "s");
3594
+ const record = await currentRecord(adapter, "s");
3595
+ const pending = awaitChange("s", {
3596
+ fromOffset: record.currentOffset,
3597
+ observedClosed: false,
3598
+ observedSoftDeleted: false,
3599
+ timeoutMs: 2e3
3600
+ });
3601
+ await tick();
3602
+ const closed = await adapter.append("s", {
3603
+ preconditions: {
3604
+ expectedOffset: record.currentOffset,
3605
+ expectedClosed: false
3606
+ },
3607
+ messages: [],
3608
+ recordPatch: { lifecycle: {
3609
+ closed: true,
3610
+ closedAt: 0
3611
+ } }
3612
+ });
3613
+ assertStatus(closed, "appended", "close append");
3614
+ const result = await pending;
3615
+ assertStatus(result, "changed", "wake on close");
3616
+ assert(result.snapshot.closed === true, "snapshot reports closed");
3617
+ });
3618
+ harness.it("awaitChange wakes a parked waiter on a soft-delete transition", async () => {
3619
+ const adapter = await makeAdapter();
3620
+ if (!adapter.fork) return;
3621
+ const awaitChange = awaitChangeFor(adapter);
3622
+ await createStream(adapter, "parent");
3623
+ const forked = await adapter.fork({
3624
+ child: newRecord("child", "parent"),
3625
+ sourceId: "parent",
3626
+ precondition: { sourceLiveAtOffset: ZERO_OFFSET }
3627
+ });
3628
+ assertStatus(forked, "created", "fork child");
3629
+ const record = await currentRecord(adapter, "parent");
3630
+ const pending = awaitChange("parent", {
3631
+ fromOffset: record.currentOffset,
3632
+ observedClosed: false,
3633
+ observedSoftDeleted: false,
3634
+ timeoutMs: 2e3
3635
+ });
3636
+ await tick();
3637
+ const deleted = await adapter.delete({
3638
+ streamId: "parent",
3639
+ reason: "delete"
3640
+ });
3641
+ assertStatus(deleted, "retained-soft-deleted", "soft delete parent");
3642
+ const result = await pending;
3643
+ assertStatus(result, "changed", "wake on soft-delete");
3644
+ assert(result.snapshot.softDeleted === true, "snapshot reports soft-deleted");
3645
+ });
3646
+ harness.it("awaitChange wakes a parked waiter on a purge", async () => {
3647
+ const adapter = await makeAdapter();
3648
+ const awaitChange = awaitChangeFor(adapter);
3649
+ await createStream(adapter, "s");
3650
+ const record = await currentRecord(adapter, "s");
3651
+ const pending = awaitChange("s", {
3652
+ fromOffset: record.currentOffset,
3653
+ observedClosed: false,
3654
+ observedSoftDeleted: false,
3655
+ timeoutMs: 2e3
3656
+ });
3657
+ await tick();
3658
+ const deleted = await adapter.delete({
3659
+ streamId: "s",
3660
+ reason: "delete"
3661
+ });
3662
+ assertStatus(deleted, "purged", "purge");
3663
+ const result = await pending;
3664
+ assertStatus(result, "changed", "wake on purge");
3665
+ assert(result.snapshot.present === false, "snapshot reports the record gone");
3666
+ });
3667
+ harness.it("awaitChange treats an offset regression (purge then re-create) as changed", async () => {
3668
+ const adapter = await makeAdapter();
3669
+ const awaitChange = awaitChangeFor(adapter);
3670
+ await createStream(adapter, "s");
3671
+ await appendTexts(adapter, "s", ["a", "b"]);
3672
+ const parked = await currentRecord(adapter, "s");
3673
+ const deleted = await adapter.delete({
3674
+ streamId: "s",
3675
+ reason: "delete"
3676
+ });
3677
+ assertStatus(deleted, "purged", "purge");
3678
+ await createStream(adapter, "s");
3679
+ const result = await awaitChange("s", {
3680
+ fromOffset: parked.currentOffset,
3681
+ observedClosed: false,
3682
+ observedSoftDeleted: false,
3683
+ timeoutMs: 200
3684
+ });
3685
+ assertStatus(result, "changed", "offset regression detected");
3686
+ assert(result.snapshot.currentOffset === ZERO_OFFSET, "snapshot shows the new incarnation");
3687
+ });
3688
+ harness.it("awaitChange survives the lost-notify race (a commit before registration)", async () => {
3689
+ const adapter = await makeAdapter();
3690
+ const awaitChange = awaitChangeFor(adapter);
3691
+ await createStream(adapter, "s");
3692
+ await appendTexts(adapter, "s", ["a"]);
3693
+ const result = await awaitChange("s", {
3694
+ fromOffset: ZERO_OFFSET,
3695
+ observedClosed: false,
3696
+ observedSoftDeleted: false,
3697
+ timeoutMs: 200
3698
+ });
3699
+ assertStatus(result, "changed", "lost-notify re-check");
3700
+ assert(result.snapshot.currentOffset === OFFSET_1, "re-read caught the missed commit");
3701
+ });
3702
+ harness.it("awaitChange ignores a non-advancing wake and resolves on the real advance", async () => {
3703
+ const adapter = await makeAdapter();
3704
+ const awaitChange = awaitChangeFor(adapter);
3705
+ await createStream(adapter, "s");
3706
+ const parked = await currentRecord(adapter, "s");
3707
+ const pending = awaitChange("s", {
3708
+ fromOffset: parked.currentOffset,
3709
+ observedClosed: false,
3710
+ observedSoftDeleted: false,
3711
+ timeoutMs: 4e3
3712
+ });
3713
+ await tick();
3714
+ const touched = await adapter.append("s", {
3715
+ preconditions: {
3716
+ expectedOffset: parked.currentOffset,
3717
+ expectedClosed: false
3718
+ },
3719
+ recordPatch: { lifecycle: { expiresAtMs: 1e6 } }
3720
+ });
3721
+ assertStatus(touched, "appended", "touch");
3722
+ assert(await staysPending(pending, 60), "waiter did not resolve on a non-advancing wake");
3723
+ await appendTexts(adapter, "s", ["a"]);
3724
+ const result = await pending;
3725
+ assertStatus(result, "changed", "resolve on real advance");
3726
+ assert(result.snapshot.currentOffset === OFFSET_1, "snapshot reflects the advance");
3727
+ });
3728
+ }
3729
+ function runLifecycleContract(makeAdapter, harness) {
3730
+ harness.it("create is idempotent (second create returns 'exists')", async () => {
3731
+ const adapter = await makeAdapter();
3732
+ const created = await adapter.create({ record: newRecord("s") });
3733
+ assertStatus(created, "created", "first create");
3734
+ const again = await adapter.create({ record: newRecord("s") });
3735
+ assertStatus(again, "exists", "second create");
3736
+ assert(again.status === "exists" && again.record.id === "s", "exists returns the record");
3737
+ });
3738
+ harness.it("create persists a record that arrives already closed", async () => {
3739
+ const adapter = await makeAdapter();
3740
+ const closedRecord = {
3741
+ ...newRecord("s"),
3742
+ lifecycle: {
3743
+ closed: true,
3744
+ closedAt: 0
3745
+ }
3746
+ };
3747
+ const created = await adapter.create({ record: closedRecord });
3748
+ assertStatus(created, "created", "create closed record");
3749
+ const record = await currentRecord(adapter, "s");
3750
+ assert(record.lifecycle.closed === true, "stream created closed");
3751
+ assert(record.lifecycle.closedAt === 0, "closedAt persisted");
3752
+ });
3753
+ harness.it("fork is capability-by-presence: omitting it is a valid, unsupported configuration", async () => {
3754
+ const adapter = await makeAdapter();
3755
+ if (adapter.fork === void 0) {
3756
+ assert(typeof adapter.create === "function" && typeof adapter.delete === "function", "a forkless adapter still provides the required create/delete intents");
3757
+ return;
3758
+ }
3759
+ assert(typeof adapter.fork === "function", "fork capability is a callable method when present");
3760
+ });
3761
+ harness.it("fork creates a child and is idempotent; a missing source is 'fork-source-gone'", async () => {
3762
+ const adapter = await makeAdapter();
3763
+ if (!adapter.fork) return;
3764
+ await createStream(adapter, "parent");
3765
+ const forked = await adapter.fork({
3766
+ child: newRecord("child", "parent"),
3767
+ sourceId: "parent",
3768
+ precondition: { sourceLiveAtOffset: ZERO_OFFSET }
3769
+ });
3770
+ assertStatus(forked, "created", "fork");
3771
+ assert(await adapter.getRecord("child") !== null, "child materialized");
3772
+ const again = await adapter.fork({
3773
+ child: newRecord("child", "parent"),
3774
+ sourceId: "parent",
3775
+ precondition: { sourceLiveAtOffset: ZERO_OFFSET }
3776
+ });
3777
+ assertStatus(again, "exists", "idempotent fork");
3778
+ assert(again.status === "exists" && again.record.id === "child", "fork exists returns the existing child record");
3779
+ assert(again.status === "exists" && again.record.lifecycle.forkedFrom === "parent", "existing child record carries its lineage");
3780
+ const gone = await adapter.fork({
3781
+ child: newRecord("orphan", "missing"),
3782
+ sourceId: "missing",
3783
+ precondition: { sourceLiveAtOffset: ZERO_OFFSET }
3784
+ });
3785
+ assertStatus(gone, "fork-source-gone", "missing source");
3786
+ });
3787
+ harness.it("delete purges a stream with no dependents", async () => {
3788
+ const adapter = await makeAdapter();
3789
+ await createStream(adapter, "s");
3790
+ const deleted = await adapter.delete({
3791
+ streamId: "s",
3792
+ reason: "delete"
3793
+ });
3794
+ assertStatus(deleted, "purged", "purge");
3795
+ assert(await adapter.getRecord("s") === null, "record gone after purge");
3796
+ });
3797
+ harness.it("delete is 'not-found' for an absent stream", async () => {
3798
+ const adapter = await makeAdapter();
3799
+ const deleted = await adapter.delete({
3800
+ streamId: "missing",
3801
+ reason: "delete"
3802
+ });
3803
+ assertStatus(deleted, "not-found", "not-found");
3804
+ });
3805
+ harness.it("delete soft-deletes an ancestor with dependents, then cascade-purges", async () => {
3806
+ const adapter = await makeAdapter();
3807
+ if (!adapter.fork) return;
3808
+ await createStream(adapter, "parent");
3809
+ const forked = await adapter.fork({
3810
+ child: newRecord("child", "parent"),
3811
+ sourceId: "parent",
3812
+ precondition: { sourceLiveAtOffset: ZERO_OFFSET }
3813
+ });
3814
+ assertStatus(forked, "created", "fork child");
3815
+ const retained = await adapter.delete({
3816
+ streamId: "parent",
3817
+ reason: "delete"
3818
+ });
3819
+ assertStatus(retained, "retained-soft-deleted", "soft delete parent");
3820
+ assert((await adapter.getRecord("parent"))?.lifecycle.softDeleted === true, "parent soft-deleted");
3821
+ const gone = await adapter.delete({
3822
+ streamId: "parent",
3823
+ reason: "delete"
3824
+ });
3825
+ assertStatus(gone, "gone", "re-delete soft-deleted ancestor");
3826
+ const purged = await adapter.delete({
3827
+ streamId: "child",
3828
+ reason: "delete"
3829
+ });
3830
+ assertStatus(purged, "purged", "purge child");
3831
+ assert(await adapter.getRecord("child") === null, "child gone");
3832
+ assert(await adapter.getRecord("parent") === null, "parent cascade-purged");
3833
+ });
3834
+ }
3835
+ function runCancellationContract(makeAdapter, harness) {
3836
+ harness.it("raceAbortAwaitChange resolves timeout-shaped on caller abort without rejecting", async () => {
3837
+ const adapter = await makeAdapter();
3838
+ const awaitChange = awaitChangeFor(adapter);
3839
+ await createStream(adapter, "s");
3840
+ const record = await currentRecord(adapter, "s");
3841
+ const fallback = buildChangeSnapshot(record);
3842
+ const controller = new AbortController();
3843
+ const wait = awaitChange("s", {
3844
+ fromOffset: record.currentOffset,
3845
+ observedClosed: false,
3846
+ observedSoftDeleted: false,
3847
+ timeoutMs: 150
3848
+ });
3849
+ const raced = raceAbortAwaitChange(wait, fallback, controller.signal);
3850
+ controller.abort();
3851
+ const result = await raced;
3852
+ assertStatus(result, "timeout", "aborted race");
3853
+ assert(result.snapshot === fallback, "abort surfaces the caller's fallback snapshot");
3854
+ await wait;
3855
+ });
3856
+ }
3857
+ /**
3858
+ * Register the full storage-adapter contract against `makeAdapter` using the
3859
+ * provided test harness. Wrap in the caller's own `describe` for grouping:
3860
+ *
3861
+ * ```ts
3862
+ * import { it } from "vitest";
3863
+ * describe("memory adapter contract", () => {
3864
+ * runStorageAdapterContract(() => createMemoryStorageAdapter(), { it });
3865
+ * });
3866
+ * ```
3867
+ */
3868
+ function runStorageAdapterContract(makeAdapter, harness) {
3869
+ const make = serialized(makeAdapter);
3870
+ runAppendContract(make, harness);
3871
+ runReadContract(make, harness);
3872
+ runAwaitChangeContract(make, harness);
3873
+ runLifecycleContract(make, harness);
3874
+ runCancellationContract(make, harness);
3875
+ }
3876
+
3877
+ //#endregion
3878
+ export { ClientReadSession, HttpHandler, InvalidGeneratedOffsetError, NotSupportedError, ReadOnlyHttpHandler, StreamProtocol, ZERO_OFFSET, bindStream, buildChangeSnapshot, cascadeReclaim, changeSnapshotDiffers, compareOffsets, copyOnForkReclaim, createHttpHandler, createMemoryStorageAdapter, createReadOnlyHttpHandler, createStreamProtocol, defaultOffsetGenerator, directProtocolClient, hasStreamsyProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, plainPurge, refCountLineage, reverseIndexLineage, runAwaitChangeLoop, runStorageAdapterContract, ttlOnlyReclaim, unsupported };