@streamsy/core 0.2.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 +277 -15
  2. package/dist/index.js +570 -39
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -9,14 +9,10 @@
9
9
  */
10
10
  type StreamId = string;
11
11
  /**
12
- * Public stream offset. **Seam guarantee**: offsets are fixed-width,
13
- * lexicographically ordered strings of the form `<counter:16>_<sub:16>` where
14
- * both parts are zero-padded decimals, so **lexicographic order = offset
15
- * order**. Adapters rely on this to compare and window offsets inside their own
16
- * storage engines (SQL `WHERE offset > ?`, key-range scans, line filtering).
17
- * `compareOffsets` and `ZERO_OFFSET` are exported from the package root.
18
- * Within one stream incarnation an offset only ever advances; a purge followed
19
- * by a re-create restarts the offset sequence.
12
+ * Opaque, case-sensitive stream position. Within one stream incarnation,
13
+ * generated offsets are unique and strictly increasing under ordinary string
14
+ * comparison. Adapters must store, sort, and window them lexicographically;
15
+ * they must not parse or normalize generator-specific structure.
20
16
  */
21
17
  type Offset = string;
22
18
  /**
@@ -63,6 +59,11 @@ interface StreamRecord {
63
59
  config: StreamConfig;
64
60
  lifecycle: StreamLifecycleState;
65
61
  currentOffset: Offset;
62
+ /**
63
+ * Deprecated adapter metadata retained for persisted-record compatibility.
64
+ * Core increments it for message-bearing mutations but never derives or
65
+ * orders offsets from it.
66
+ */
66
67
  counter: number;
67
68
  }
68
69
  /**
@@ -301,8 +302,44 @@ declare function notSupportedFromError(error: NotSupportedError): NotSupportedRe
301
302
  /** Type guard for protocol results that may be a {@link NotSupportedResult}. */
302
303
  declare function isNotSupported(value: unknown): value is NotSupportedResult;
303
304
 
305
+ //#endregion
306
+ //#region src/protocol/helpers/offset-generator.d.ts
307
+ /**
308
+ * Generates opaque offsets for one stream. `next` is called once per message,
309
+ * including every item in a JSON batch. Core verifies every returned value is
310
+ * valid and strictly greater than `previous` before a storage plan is built.
311
+ */
312
+ interface OffsetGenerator {
313
+ /** Tail value for a newly-created empty stream. */
314
+ readonly initialOffset: Offset;
315
+ /** Return the next offset after `previous`. */
316
+ next(previous: Offset): Offset;
317
+ /** Accept client-supplied lexical boundaries produced by this scheme. */
318
+ isValid(offset: string): boolean;
319
+ }
320
+ declare const ZERO_OFFSET: Offset;
321
+ /** Protocol-level constraints that apply to every generated offset scheme. */
322
+
323
+ declare function compareOffsets(a: Offset, b: Offset): number;
324
+ /** The backwards-compatible fixed-width counter generator used by default. */
325
+ declare const defaultOffsetGenerator: OffsetGenerator;
326
+ declare class InvalidGeneratedOffsetError extends Error {
327
+ constructor(message: string);
328
+ }
329
+
304
330
  //#endregion
305
331
  //#region src/types/protocol.d.ts
332
+ /** Allocate a batch without interpreting the generator's opaque offset format. */
333
+ interface CommitEvent {
334
+ streamId: StreamId;
335
+ offset: string;
336
+ closed: boolean;
337
+ softDeleted: boolean;
338
+ }
339
+ type AfterCommitHook = (commit: CommitEvent) => void;
340
+ interface CommitObservable {
341
+ onAfterCommit(hook: AfterCommitHook): () => void;
342
+ }
306
343
  interface CreateOptions {
307
344
  contentType?: string;
308
345
  ttlSeconds?: number;
@@ -499,7 +536,9 @@ type ProtocolGetResult = {
499
536
  } | {
500
537
  status: "gone";
501
538
  } | NotSupportedResult;
502
- interface StreamProtocolFactory {
539
+ interface StreamProtocolFactory extends CommitObservable {
540
+ readonly offsetGenerator: OffsetGenerator;
541
+ isValidOffset(offset: string): boolean;
503
542
  create(streamId: string, options: CreateOptions): Promise<CreateResult>;
504
543
  get(streamId: string): Promise<ProtocolGetResult>;
505
544
  }
@@ -519,16 +558,14 @@ interface BoundStream {
519
558
  }
520
559
  declare function bindStream(adapter: StorageAdapter, id: StreamId): BoundStream;
521
560
 
522
- //#endregion
523
- //#region src/protocol/helpers/offset-generator.d.ts
524
- declare const ZERO_OFFSET: Offset;
525
- declare function compareOffsets(a: Offset, b: Offset): number;
526
-
527
561
  //#endregion
528
562
  //#region src/protocol.d.ts
529
563
  interface StreamProtocolOptions {
530
564
  clock?: Clock;
565
+ /** Long-poll timeout in milliseconds. Defaults to 30 seconds. */
531
566
  longPollTimeoutMs?: number;
567
+ /** Opaque offset scheme; defaults to Streamsy's fixed-width counter format. */
568
+ offsetGenerator?: OffsetGenerator;
532
569
  }
533
570
  interface StreamProtocolDeps extends StreamProtocolOptions {
534
571
  storage: {
@@ -542,14 +579,19 @@ declare class StreamProtocol implements StreamProtocolFactory {
542
579
  private longPollTimeoutMs;
543
580
  private expiryPolicy;
544
581
  private recordFactory;
582
+ readonly offsetGenerator: OffsetGenerator;
583
+ private hooks;
545
584
  constructor(deps: StreamProtocolDeps);
585
+ isValidOffset(offset: string): boolean;
546
586
  create(streamId: string, options: CreateOptions): Promise<CreateResult>;
547
587
  get(streamId: string): Promise<ProtocolGetResult>;
588
+ onAfterCommit(hook: AfterCommitHook): () => void;
548
589
  /** Called by adapter schedulers/alarms; core decides whether expiry applies. */
549
590
  handleScheduledExpiry(streamId: string): Promise<void>;
550
591
  private boundProtocolStream;
551
592
  /** Bind the flat adapter to one id for ergonomic core-side per-stream calls. */
552
593
  private storageStream;
594
+ private emitAfterCommit;
553
595
  }
554
596
 
555
597
  //#endregion
@@ -668,6 +710,226 @@ declare class ReadOnlyHttpHandler implements HttpHandlerInterface {
668
710
  fetch(request: Request): Promise<Response>;
669
711
  }
670
712
 
713
+ //#endregion
714
+ //#region src/client/types.d.ts
715
+ type StreamOffset = string;
716
+ type JsonPrimitive = null | boolean | number | string;
717
+ type JsonValue = JsonPrimitive | {
718
+ readonly [key: string]: JsonValue;
719
+ } | readonly JsonValue[];
720
+ interface ClientRequestOptions {
721
+ signal?: AbortSignal;
722
+ }
723
+ /**
724
+ * The single client-only failure member. It covers transport/auth/abort and
725
+ * other cross-cutting outcomes so per-operation unions stay small and the
726
+ * direct adapter can pass protocol results through with minimal narrowing.
727
+ */
728
+ type ClientErrorCode = "transport" | "unauthorized" | "forbidden" | "rate-limited" | "bad-request" | "busy" | "parse-error" | "not-supported" | "aborted" | "client-closed" | "unknown";
729
+ interface ClientFailure {
730
+ status: "error";
731
+ code: ClientErrorCode;
732
+ message: string;
733
+ httpStatus?: number;
734
+ retryable: boolean;
735
+ cause?: unknown;
736
+ }
737
+ interface CreateStreamOptions extends ClientRequestOptions {
738
+ contentType?: string;
739
+ ttlSeconds?: number;
740
+ expiresAt?: string;
741
+ initialData?: Uint8Array | string;
742
+ closed?: boolean;
743
+ }
744
+ interface AppendStreamOptions extends ClientRequestOptions {
745
+ /** Required where the substrate requires it (direct append). */
746
+ contentType?: string;
747
+ seq?: string;
748
+ }
749
+ interface CloseStreamOptions extends ClientRequestOptions {
750
+ contentType?: string;
751
+ finalData?: Uint8Array | string;
752
+ }
753
+ type ClientHeadResult = {
754
+ status: "ok";
755
+ contentType?: string;
756
+ /** Current tail/read-resume token when supplied by the substrate. */
757
+ offset?: StreamOffset;
758
+ closed: boolean;
759
+ etag?: string;
760
+ cacheControl?: string;
761
+ } | {
762
+ status: "not-found";
763
+ } | {
764
+ status: "gone";
765
+ } | ClientFailure;
766
+ type ClientCreateResult = {
767
+ status: "created";
768
+ contentType?: string;
769
+ } | {
770
+ status: "conflict";
771
+ } | ClientFailure;
772
+ type ClientAppendResult = {
773
+ status: "appended";
774
+ } | {
775
+ status: "not-found";
776
+ } | {
777
+ status: "gone";
778
+ } | {
779
+ status: "closed";
780
+ } | {
781
+ status: "conflict";
782
+ } | ClientFailure;
783
+ type ClientCloseResult = {
784
+ status: "closed";
785
+ finalOffset: StreamOffset;
786
+ } | {
787
+ status: "not-found";
788
+ } | {
789
+ status: "gone";
790
+ } | {
791
+ status: "conflict";
792
+ } | ClientFailure;
793
+ type ClientReadResult<T extends JsonValue = JsonValue> = {
794
+ status: "ok";
795
+ session: StreamReadSession<T>;
796
+ } | {
797
+ status: "not-found";
798
+ } | {
799
+ status: "gone";
800
+ } | ClientFailure;
801
+ type ClientLiveMode = false | "long-poll" | "sse";
802
+ interface ReadStreamOptions extends ClientRequestOptions {
803
+ /** After-exclusive token. Omission means the start of the stream. */
804
+ offset?: StreamOffset;
805
+ /** false is catch-up only. Live modes continue until EOF, cancel, or error. */
806
+ live?: ClientLiveMode;
807
+ }
808
+ interface StreamBatchMeta {
809
+ /** Pass this unchanged as the next read's offset. */
810
+ offset: StreamOffset;
811
+ cursor?: string;
812
+ upToDate: boolean;
813
+ streamClosed: boolean;
814
+ }
815
+ interface JsonStreamBatch<T extends JsonValue = JsonValue> extends StreamBatchMeta {
816
+ kind: "json";
817
+ items: readonly T[];
818
+ }
819
+ interface TextStreamBatch extends StreamBatchMeta {
820
+ kind: "text";
821
+ text: string;
822
+ }
823
+ interface ByteStreamBatch extends StreamBatchMeta {
824
+ kind: "bytes";
825
+ data: Uint8Array;
826
+ }
827
+ type StreamBatch<T extends JsonValue = JsonValue> = JsonStreamBatch<T> | TextStreamBatch | ByteStreamBatch;
828
+ /** Terminal outcome of a read session. Delivered through `done`, never thrown. */
829
+ type ReadEndResult = {
830
+ status: "done";
831
+ } | {
832
+ status: "cancelled";
833
+ } | ClientFailure;
834
+ /**
835
+ * A cancellable session of content-aware batches. Iteration yields batches and
836
+ * NEVER throws for operational failures; the terminal outcome is a result
837
+ * object resolved through {@link StreamReadSession.done}.
838
+ */
839
+ interface StreamReadSession<T extends JsonValue = JsonValue> extends AsyncIterable<StreamBatch<T>> {
840
+ readonly contentType?: string;
841
+ readonly startOffset?: StreamOffset;
842
+ /** Latest batch metadata after that batch has been delivered. */
843
+ readonly offset: StreamOffset;
844
+ readonly cursor?: string;
845
+ readonly upToDate: boolean;
846
+ readonly streamClosed: boolean;
847
+ cancel(reason?: unknown): void;
848
+ /** Always resolves, never rejects. */
849
+ readonly done: Promise<ReadEndResult>;
850
+ }
851
+ interface StreamProtocolHandle {
852
+ readonly id: string;
853
+ head(options?: ClientRequestOptions): Promise<ClientHeadResult>;
854
+ /** Create-only. An existing stream is a `conflict`, never success. */
855
+ create(options?: CreateStreamOptions): Promise<ClientCreateResult>;
856
+ /** `contentType` is required in `options` where the substrate requires it. */
857
+ append(data: Uint8Array | string, options?: AppendStreamOptions): Promise<ClientAppendResult>;
858
+ /** Permanently close the stream, optionally appending finalData atomically. */
859
+ close(options?: CloseStreamOptions): Promise<ClientCloseResult>;
860
+ read<T extends JsonValue = JsonValue>(options?: ReadStreamOptions): Promise<ClientReadResult<T>>;
861
+ }
862
+ interface StreamProtocolClient {
863
+ /** Cold handle creation: no I/O. Repeated calls need not return the same object. */
864
+ stream(streamId: string): StreamProtocolHandle;
865
+ /** Cancel all sessions created by this client and reject future operations. */
866
+ close(reason?: unknown): Promise<void>;
867
+ }
868
+ interface StreamsyProtocolClient extends StreamProtocolClient {
869
+ /** Exact local Streamsy semantics; absent from the official adapter. */
870
+ readonly streamsy: StreamProtocolFactory;
871
+ }
872
+
873
+ //#endregion
874
+ //#region src/client/direct/client.d.ts
875
+ /** Structural refinement test: is this client the exact-Streamsy direct adapter? */
876
+ declare function hasStreamsyProtocol(client: StreamProtocolClient): client is StreamsyProtocolClient;
877
+ declare function directProtocolClient(factory: StreamProtocolFactory): StreamsyProtocolClient;
878
+
879
+ //#endregion
880
+ //#region src/client/read-session.d.ts
881
+ /**
882
+ * Adapts a `StreamProtocolFactory` to the transport-neutral client seam. It
883
+ * keeps a single client-level abort controller whose signal is threaded into
884
+ * every operation and read session; `close()` aborts it and rejects new work.
885
+ * There is no session registry: sessions observe the abort through their own
886
+ * signal and end with `{ status: "cancelled" }`.
887
+ */
888
+ /**
889
+ * The single client read-session implementation, shared by every adapter.
890
+ *
891
+ * It is a one-consumer, one-batch queue whose producer is backpressured by
892
+ * iterator delivery. Iteration never throws for operational failures: the
893
+ * terminal outcome is delivered through {@link ClientReadSession.done}, which
894
+ * always resolves. Only programmer misuse (double iteration, concurrent
895
+ * `next()`) throws.
896
+ */
897
+ declare class ClientReadSession<T extends JsonValue = JsonValue> implements StreamReadSession<T>, AsyncIterator<StreamBatch<T>> {
898
+ readonly done: Promise<ReadEndResult>;
899
+ readonly contentType?: string;
900
+ readonly startOffset?: string;
901
+ offset: string;
902
+ cursor?: string;
903
+ upToDate: boolean;
904
+ streamClosed: boolean;
905
+ private doneResolve;
906
+ private pending?;
907
+ private waiting?;
908
+ private ended;
909
+ private iterated;
910
+ private cancelHook?;
911
+ constructor(options: {
912
+ contentType?: string;
913
+ startOffset: string;
914
+ offset?: string;
915
+ cursor?: string;
916
+ upToDate?: boolean;
917
+ streamClosed?: boolean;
918
+ onCancel?: (reason?: unknown) => void;
919
+ });
920
+ setCancelHook(hook: (reason?: unknown) => void): void;
921
+ [Symbol.asyncIterator](): AsyncIterator<StreamBatch<T>>;
922
+ next(): Promise<IteratorResult<StreamBatch<T>>>;
923
+ return(): Promise<IteratorResult<StreamBatch<T>>>;
924
+ cancel(reason?: unknown): void;
925
+ /** Producer side: hand a batch to the consumer, backpressured until accepted. */
926
+ deliver(batch: StreamBatch<T>): Promise<void>;
927
+ /** Producer side: terminate the session with its outcome. Always resolves `done`. */
928
+ end(result: ReadEndResult): void;
929
+ private acceptPending;
930
+ private updateState;
931
+ }
932
+
671
933
  //#endregion
672
934
  //#region src/protocol/helpers/change-snapshot.d.ts
673
935
  /** Build the serializable, change-relevant snapshot of a (possibly absent) record. */
@@ -789,4 +1051,4 @@ declare function copyOnForkReclaim(): LineagePolicy;
789
1051
  declare function ttlOnlyReclaim(): LineagePolicy;
790
1052
 
791
1053
  //#endregion
792
- export { AppendConflictReason, AppendOptions, AppendPlan, AppendResult, AwaitChangeLoopDeps, AwaitChangeOptions, AwaitChangeResult, BoundStream, Clock, CreateConflictReason, CreateOptions, CreatePlan, CreateResult, DeletePlan, DeleteResult, DependentsQuery, ForkPlan, HttpHandler, HttpHandlerInterface, HttpHandlerOptions, LineagePolicy, LineageStore, ListMessagesOptions, MakeStorageAdapter, MemoryStorageAdapterOptions, MetadataResult, NotSupportedError, NotSupportedResult, Offset, ProducerOptions, ProducerState, ProtocolGetResult, ProtocolStream, ReadLiveOptions, ReadLiveResult, ReadOnlyHttpHandler, ReadOnlyHttpHandlerOptions, ReadOptions, ReadResult, StorageAdapter, StorageAdapterContractHarness, StorageAppendResult, StorageCreateResult, StorageDeleteResult, StorageForkResult, StoredMessage, StreamAppender, StreamChangeSnapshot, StreamConfig, StreamExpiryScheduler, StreamId, StreamLifecycleState, StreamLiveWaiter, StreamProtocol, StreamProtocolDeps, StreamProtocolFactory, StreamProtocolOptions, StreamReader, StreamRecord, StreamRecordPatch, ZERO_OFFSET, bindStream, buildChangeSnapshot, cascadeReclaim, changeSnapshotDiffers, compareOffsets, copyOnForkReclaim, createHttpHandler, createMemoryStorageAdapter, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, plainPurge, refCountLineage, reverseIndexLineage, runAwaitChangeLoop, runStorageAdapterContract, ttlOnlyReclaim, unsupported };
1054
+ export { AfterCommitHook, AppendConflictReason, AppendOptions, AppendPlan, AppendResult, AppendStreamOptions, AwaitChangeLoopDeps, AwaitChangeOptions, AwaitChangeResult, BoundStream, ByteStreamBatch, ClientAppendResult, ClientCloseResult, ClientCreateResult, ClientErrorCode, ClientFailure, ClientHeadResult, ClientLiveMode, ClientReadResult, ClientReadSession, ClientRequestOptions, Clock, CloseStreamOptions, CommitEvent, CommitObservable, CreateConflictReason, CreateOptions, CreatePlan, CreateResult, CreateStreamOptions, DeletePlan, DeleteResult, DependentsQuery, ForkPlan, HttpHandler, HttpHandlerInterface, HttpHandlerOptions, InvalidGeneratedOffsetError, JsonPrimitive, JsonStreamBatch, JsonValue, LineagePolicy, LineageStore, ListMessagesOptions, MakeStorageAdapter, MemoryStorageAdapterOptions, MetadataResult, NotSupportedError, NotSupportedResult, Offset, OffsetGenerator, ProducerOptions, ProducerState, ProtocolGetResult, ProtocolStream, ReadEndResult, ReadLiveOptions, ReadLiveResult, ReadOnlyHttpHandler, ReadOnlyHttpHandlerOptions, ReadOptions, ReadResult, ReadStreamOptions, StorageAdapter, StorageAdapterContractHarness, StorageAppendResult, StorageCreateResult, StorageDeleteResult, StorageForkResult, StoredMessage, StreamAppender, StreamBatch, StreamBatchMeta, StreamChangeSnapshot, StreamConfig, StreamExpiryScheduler, StreamId, StreamLifecycleState, StreamLiveWaiter, StreamOffset, StreamProtocol, StreamProtocolClient, StreamProtocolDeps, StreamProtocolFactory, StreamProtocolHandle, StreamProtocolOptions, StreamReadSession, StreamReader, StreamRecord, StreamRecordPatch, StreamsyProtocolClient, TextStreamBatch, 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 };
package/dist/index.js CHANGED
@@ -97,9 +97,14 @@ function frameMessages(data, contentType) {
97
97
  //#endregion
98
98
  //#region src/protocol/helpers/offset-generator.ts
99
99
  const ZERO_OFFSET = `${"0".repeat(16)}_${"0".repeat(16)}`;
100
- const OFFSET_REGEX = /^\d{1,16}_\d{1,16}$/;
101
- function isValidOffset(offset) {
102
- return OFFSET_REGEX.test(offset);
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);
103
108
  }
104
109
  function compareOffsets(a, b) {
105
110
  return a === b ? 0 : a < b ? -1 : 1;
@@ -110,16 +115,42 @@ function formatCounter(counter) {
110
115
  function parseCounter(offset) {
111
116
  return parseInt(offset.split("_")[0] ?? "0", 10);
112
117
  }
113
- function allocate(counter, count) {
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) {
114
136
  const offsets = [];
115
- for (let i = 1; i <= count; i++) offsets.push(formatCounter(counter + i));
116
- const endCounter = counter + count;
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
+ }
117
145
  return {
118
- endCounter,
146
+ endCounter: counter + count,
119
147
  offsets,
120
- nextOffset: count > 0 ? formatCounter(endCounter) : formatCounter(counter)
148
+ nextOffset: previous
121
149
  };
122
150
  }
151
+ function assertValidOffsetGenerator(generator) {
152
+ if (!isValidOffset(generator, generator.initialOffset)) throw new InvalidGeneratedOffsetError("Offset generator has an invalid initialOffset");
153
+ }
123
154
 
124
155
  //#endregion
125
156
  //#region src/protocol/helpers/producer-idempotency-service.ts
@@ -282,7 +313,7 @@ var AppendService = class {
282
313
  return this.commitDecision(record, processed, options, producerState, producerValidation, wantClose);
283
314
  }
284
315
  commitDecision(record, data, options, producerState, producerValidation, wantClose) {
285
- const allocation = allocate(record.counter, data.length);
316
+ const allocation = allocate(this.deps.offsets, record.currentOffset, record.counter, data.length);
286
317
  const now = this.deps.clock.now();
287
318
  const messages = data.map((bytes, i) => ({
288
319
  data: bytes,
@@ -433,7 +464,7 @@ var LiveReadService = class {
433
464
  cursor: generateCursor(this.deps.clock, options.cursor)
434
465
  };
435
466
  }
436
- const fromOffset = isValidOffset(options.offset) ? options.offset : ZERO_OFFSET;
467
+ const fromOffset = isValidOffset(this.deps.offsets, options.offset) ? options.offset : this.deps.offsets.initialOffset;
437
468
  const immediate = await this.deps.readOwn(fromOffset);
438
469
  if (immediate.messages.length > 0) return {
439
470
  status: "ok",
@@ -593,7 +624,7 @@ var CreateStreamService = class {
593
624
  };
594
625
  if (options.forkedFrom) return { kind: "fork" };
595
626
  const contentType = options.contentType ?? "application/octet-stream";
596
- const initialMessages = this.initialMessages(options.initialData, contentType, 0);
627
+ const initialMessages = this.initialMessages(options.initialData, contentType, this.deps.offsets.initialOffset, 0);
597
628
  const wantClosed = options.closed === true;
598
629
  const newRecord$1 = this.deps.newRecord(contentType, options);
599
630
  const finalRecord = this.withInitialTail(newRecord$1, initialMessages, wantClosed);
@@ -633,9 +664,9 @@ var CreateStreamService = class {
633
664
  closed: existing.lifecycle.closed === true
634
665
  };
635
666
  }
636
- initialMessages(initialData, contentType, startCounter) {
667
+ initialMessages(initialData, contentType, previousOffset, startCounter) {
637
668
  const framed = initialData ? frameMessages(initialData, contentType) : [];
638
- const allocation = allocate(startCounter, framed.length);
669
+ const allocation = allocate(this.deps.offsets, previousOffset, startCounter, framed.length);
639
670
  const now = this.deps.clock.now();
640
671
  return framed.map((data, i) => ({
641
672
  data,
@@ -644,11 +675,11 @@ var CreateStreamService = class {
644
675
  }));
645
676
  }
646
677
  withInitialTail(record, initialMessages, closed) {
647
- const allocation = allocate(record.counter, initialMessages.length);
678
+ const lastMessage = initialMessages[initialMessages.length - 1];
648
679
  return {
649
680
  ...record,
650
- currentOffset: allocation.nextOffset,
651
- counter: allocation.endCounter,
681
+ currentOffset: lastMessage?.offset ?? record.currentOffset,
682
+ counter: record.counter + initialMessages.length,
652
683
  lifecycle: {
653
684
  ...record.lifecycle,
654
685
  ...closed ? {
@@ -694,7 +725,7 @@ var ForkPlanBuilder = class {
694
725
  }
695
726
  };
696
727
  const forkOffset = options.forkOffset ?? source.currentOffset;
697
- if (!isValidOffset(forkOffset)) return {
728
+ if (!isValidOffset(this.deps.offsets, forkOffset)) return {
698
729
  kind: "terminal",
699
730
  result: {
700
731
  status: "bad-request",
@@ -703,7 +734,7 @@ var ForkPlanBuilder = class {
703
734
  errorMessage: "Invalid Stream-Fork-Offset format"
704
735
  }
705
736
  };
706
- if (compareOffsets(forkOffset, ZERO_OFFSET) < 0 || compareOffsets(forkOffset, source.currentOffset) > 0) return {
737
+ if (compareOffsets(forkOffset, this.deps.offsets.initialOffset) < 0 || compareOffsets(forkOffset, source.currentOffset) > 0) return {
707
738
  kind: "terminal",
708
739
  result: {
709
740
  status: "bad-request",
@@ -744,7 +775,7 @@ var ForkPlanBuilder = class {
744
775
  forkOffset,
745
776
  ...subOffset !== void 0 && subOffset > 0 ? { forkSubOffset: subOffset } : {}
746
777
  });
747
- const initialMessages = this.initialMessages(prefix.messages, options.initialData, contentType, baseRecord.counter);
778
+ const initialMessages = this.initialMessages(prefix.messages, options.initialData, contentType, baseRecord.currentOffset, baseRecord.counter);
748
779
  const child = this.withInitialTail(baseRecord, initialMessages);
749
780
  const plan = {
750
781
  child,
@@ -800,9 +831,9 @@ var ForkPlanBuilder = class {
800
831
  messages: [first.data.subarray(0, subOffset)]
801
832
  };
802
833
  }
803
- initialMessages(prefix, initialData, contentType, startCounter) {
834
+ initialMessages(prefix, initialData, contentType, previousOffset, startCounter) {
804
835
  const framed = [...prefix, ...initialData ? frameMessages(initialData, contentType) : []];
805
- const allocation = allocate(startCounter, framed.length);
836
+ const allocation = allocate(this.deps.offsets, previousOffset, startCounter, framed.length);
806
837
  const now = this.deps.clock.now();
807
838
  return framed.map((data, i) => ({
808
839
  data,
@@ -811,11 +842,11 @@ var ForkPlanBuilder = class {
811
842
  }));
812
843
  }
813
844
  withInitialTail(record, initialMessages) {
814
- const allocation = allocate(record.counter, initialMessages.length);
845
+ const lastMessage = initialMessages[initialMessages.length - 1];
815
846
  return {
816
847
  ...record,
817
- currentOffset: allocation.nextOffset,
818
- counter: allocation.endCounter
848
+ currentOffset: lastMessage?.offset ?? record.currentOffset,
849
+ counter: record.counter + initialMessages.length
819
850
  };
820
851
  }
821
852
  };
@@ -895,15 +926,15 @@ var StreamRecordFactory = class {
895
926
  ...fork?.forkSubOffset !== void 0 && fork.forkSubOffset > 0 ? { forkSubOffset: fork.forkSubOffset } : {},
896
927
  expiresAtMs: this.deps.expiryPolicy.computeExpiresAtMs(config)
897
928
  },
898
- currentOffset: forkOffset ?? ZERO_OFFSET,
899
- counter: forkOffset ? parseCounter(forkOffset) : 0
929
+ currentOffset: forkOffset ?? this.deps.offsets.initialOffset,
930
+ counter: 0
900
931
  };
901
932
  }
902
933
  };
903
934
 
904
935
  //#endregion
905
936
  //#region src/protocol.ts
906
- const LONG_POLL_TIMEOUT_MS = 1500;
937
+ const LONG_POLL_TIMEOUT_MS = 3e4;
907
938
  const MAX_COMMIT_ATTEMPTS = 8;
908
939
  const MAX_NO_PROGRESS_ATTEMPTS = 8;
909
940
  function createStreamProtocol(deps) {
@@ -943,21 +974,27 @@ var ProtocolStream = class {
943
974
  resolve: deps.resolveStorageStream,
944
975
  expiryPolicy: deps.expiryPolicy
945
976
  });
946
- this.appendService = new AppendService({ clock: deps.clock });
977
+ this.appendService = new AppendService({
978
+ clock: deps.clock,
979
+ offsets: deps.offsets
980
+ });
947
981
  this.readService = new ReadService({ readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset) });
948
982
  this.liveReadService = new LiveReadService({
949
983
  store: liveReadStore(deps.storage),
950
984
  clock: deps.clock,
951
985
  longPollTimeoutMs: deps.longPollTimeoutMs,
986
+ offsets: deps.offsets,
952
987
  readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset),
953
988
  readOwn: (after) => messageReader.readOwn(after)
954
989
  });
955
990
  this.createService = new CreateStreamService({
956
991
  clock: deps.clock,
992
+ offsets: deps.offsets,
957
993
  newRecord: (contentType, opts) => deps.recordFactory.newRecord(deps.storage.id, contentType, opts, void 0)
958
994
  });
959
995
  this.forkPlanBuilder = new ForkPlanBuilder({
960
996
  clock: deps.clock,
997
+ offsets: deps.offsets,
961
998
  newRecord: (streamId, contentType, opts, fork) => deps.recordFactory.newRecord(streamId, contentType, opts, fork)
962
999
  });
963
1000
  }
@@ -969,6 +1006,7 @@ var ProtocolStream = class {
969
1006
  const commit = await this.deps.adapter.create(decision.plan);
970
1007
  if (commit.status === "exists") return this.createService.resultForExisting(commit.record, options);
971
1008
  await runAfterCommit(decision.afterCommit, this.deps.storage);
1009
+ this.deps.emitAfterCommit(commit.record);
972
1010
  return decision.toResult(commit.record);
973
1011
  }
974
1012
  async append(options) {
@@ -983,6 +1021,7 @@ var ProtocolStream = class {
983
1021
  const out = await this.deps.storage.append(decision.plan);
984
1022
  if (out.status === "appended") {
985
1023
  await runAfterCommit(decision.afterCommit, this.deps.storage);
1024
+ this.deps.emitAfterCommit(out.record);
986
1025
  return decision.toResult(out.record);
987
1026
  }
988
1027
  lastRecord = out.record;
@@ -995,7 +1034,7 @@ var ProtocolStream = class {
995
1034
  offset: lastRecord.currentOffset
996
1035
  };
997
1036
  } else {
998
- const previousOffset = decision.plan.preconditions.expectedOffset ?? ZERO_OFFSET;
1037
+ const previousOffset = decision.plan.preconditions.expectedOffset ?? this.deps.offsets.initialOffset;
999
1038
  const madeProgress = compareOffsets(lastRecord.currentOffset, previousOffset) > 0;
1000
1039
  noProgressAttempts = madeProgress ? 0 : noProgressAttempts + 1;
1001
1040
  if (noProgressAttempts >= MAX_NO_PROGRESS_ATTEMPTS) return { status: "busy" };
@@ -1044,7 +1083,7 @@ var ProtocolStream = class {
1044
1083
  const subOffset = options.forkSubOffset;
1045
1084
  if (subOffset === void 0 || subOffset <= 0 || !source) return void 0;
1046
1085
  const forkOffset = options.forkOffset ?? source.currentOffset;
1047
- if (!isValidOffset(forkOffset)) return void 0;
1086
+ if (!isValidOffset(this.deps.offsets, forkOffset)) return void 0;
1048
1087
  const reader = new StreamMessageReader({
1049
1088
  stream: sourceStream,
1050
1089
  resolve: this.deps.resolveStorageStream,
@@ -1070,6 +1109,7 @@ var ProtocolStream = class {
1070
1109
  errorMessage: `Source stream not found: ${sourceId}`
1071
1110
  };
1072
1111
  await runAfterCommit(decision.afterCommit, this.deps.storage);
1112
+ this.deps.emitAfterCommit(commit.record);
1073
1113
  return decision.toResult(commit.record);
1074
1114
  }
1075
1115
  };
@@ -1078,9 +1118,13 @@ var StreamProtocol = class {
1078
1118
  longPollTimeoutMs;
1079
1119
  expiryPolicy;
1080
1120
  recordFactory;
1121
+ offsetGenerator;
1122
+ hooks = new Set();
1081
1123
  constructor(deps) {
1082
1124
  this.deps = deps;
1083
1125
  this.clock = deps.clock ?? systemClock;
1126
+ this.offsetGenerator = deps.offsetGenerator ?? defaultOffsetGenerator;
1127
+ assertValidOffsetGenerator(this.offsetGenerator);
1084
1128
  this.longPollTimeoutMs = deps.longPollTimeoutMs ?? LONG_POLL_TIMEOUT_MS;
1085
1129
  this.expiryPolicy = new ExpiryPolicy({
1086
1130
  resolve: (id) => this.storageStream(id),
@@ -1089,9 +1133,13 @@ var StreamProtocol = class {
1089
1133
  });
1090
1134
  this.recordFactory = new StreamRecordFactory({
1091
1135
  clock: this.clock,
1092
- expiryPolicy: this.expiryPolicy
1136
+ expiryPolicy: this.expiryPolicy,
1137
+ offsets: this.offsetGenerator
1093
1138
  });
1094
1139
  }
1140
+ isValidOffset(offset) {
1141
+ return isValidOffset(this.offsetGenerator, offset);
1142
+ }
1095
1143
  async create(streamId, options) {
1096
1144
  const storage = this.storageStream(streamId);
1097
1145
  const stream = this.boundProtocolStream(storage);
@@ -1112,6 +1160,12 @@ var StreamProtocol = class {
1112
1160
  stream: this.boundProtocolStream(storage)
1113
1161
  };
1114
1162
  }
1163
+ onAfterCommit(hook) {
1164
+ this.hooks.add(hook);
1165
+ return () => {
1166
+ this.hooks.delete(hook);
1167
+ };
1168
+ }
1115
1169
  /** Called by adapter schedulers/alarms; core decides whether expiry applies. */
1116
1170
  async handleScheduledExpiry(streamId) {
1117
1171
  const storage = this.storageStream(streamId);
@@ -1135,13 +1189,28 @@ var StreamProtocol = class {
1135
1189
  longPollTimeoutMs: this.longPollTimeoutMs,
1136
1190
  expiryPolicy: this.expiryPolicy,
1137
1191
  recordFactory: this.recordFactory,
1138
- resolveStorageStream: (id) => this.storageStream(id)
1192
+ resolveStorageStream: (id) => this.storageStream(id),
1193
+ emitAfterCommit: (record) => this.emitAfterCommit(record),
1194
+ offsets: this.offsetGenerator
1139
1195
  });
1140
1196
  }
1141
1197
  /** Bind the flat adapter to one id for ergonomic core-side per-stream calls. */
1142
1198
  storageStream(streamId) {
1143
1199
  return bindStream(this.deps.storage.adapter, streamId);
1144
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
+ }
1145
1214
  };
1146
1215
 
1147
1216
  //#endregion
@@ -1837,12 +1906,15 @@ var ProducerHeaderParser = class {
1837
1906
  //#endregion
1838
1907
  //#region src/http/read-query-parser.ts
1839
1908
  var ReadQueryParser = class {
1909
+ constructor(isValidOffset$1) {
1910
+ this.isValidOffset = isValidOffset$1;
1911
+ }
1840
1912
  parse(url) {
1841
1913
  const offset = url.searchParams.get("offset") ?? void 0;
1842
1914
  const liveParam = url.searchParams.get("live");
1843
1915
  const cursor = url.searchParams.get("cursor") ?? void 0;
1844
1916
  const live = liveParam === "long-poll" || liveParam === "sse" ? liveParam : void 0;
1845
- 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 {
1846
1918
  ok: false,
1847
1919
  response: new Response("Invalid offset format", { status: 400 })
1848
1920
  };
@@ -2047,7 +2119,7 @@ var AppendHttpService = class {
2047
2119
  response: this.deps.responses.badRequest("Invalid producer headers")
2048
2120
  };
2049
2121
  const expectedOffset = request.headers.get("stream-expected-offset") ?? void 0;
2050
- if (expectedOffset !== void 0 && !isValidOffset(expectedOffset)) return {
2122
+ if (expectedOffset !== void 0 && !this.deps.isValidOffset(expectedOffset)) return {
2051
2123
  ok: false,
2052
2124
  response: this.deps.responses.badRequest("Invalid expected offset")
2053
2125
  };
@@ -2538,7 +2610,7 @@ var HttpHandler = class {
2538
2610
  const bodyReader = new RequestBodyReader(options.maxMessageSize ?? 1024 * 1024, responses);
2539
2611
  const bodyCodec = new MessageBodyCodec();
2540
2612
  const producerHeaders = new ProducerHeaderParser();
2541
- const readQuery = new ReadQueryParser();
2613
+ const readQuery = new ReadQueryParser((offset) => options.protocol.isValidOffset(offset));
2542
2614
  const etags = new EtagBuilder();
2543
2615
  const sseEvents = new SseEventEncoder(bodyCodec);
2544
2616
  const longPoll = new LongPollHttpService({
@@ -2563,7 +2635,8 @@ var HttpHandler = class {
2563
2635
  append: new AppendHttpService({
2564
2636
  responses,
2565
2637
  bodyReader,
2566
- producerHeaders
2638
+ producerHeaders,
2639
+ isValidOffset: (offset) => options.protocol.isValidOffset(offset)
2567
2640
  }),
2568
2641
  read: new ReadHttpService({
2569
2642
  responses,
@@ -2635,7 +2708,7 @@ var ReadOnlyHttpHandler = class {
2635
2708
  const path = new StreamPathService(options.pathPrefix ?? "/");
2636
2709
  const responses = new HttpResponseFactory();
2637
2710
  const bodyCodec = new MessageBodyCodec();
2638
- const readQuery = new ReadQueryParser();
2711
+ const readQuery = new ReadQueryParser((offset) => options.protocol.isValidOffset(offset));
2639
2712
  const etags = new EtagBuilder();
2640
2713
  const sseEvents = new SseEventEncoder(bodyCodec);
2641
2714
  const longPoll = new LongPollHttpService({
@@ -2667,6 +2740,464 @@ var ReadOnlyHttpHandler = class {
2667
2740
  }
2668
2741
  };
2669
2742
 
2743
+ //#endregion
2744
+ //#region src/client/batch-encoding.ts
2745
+ const decoder = new TextDecoder();
2746
+ /**
2747
+ * Real impedance matching: turn a substrate's `StoredMessage[]` into a single
2748
+ * content-aware delivery batch, matching `MessageBodyCodec` semantics so direct
2749
+ * and remote consumers observe the same payload shape.
2750
+ *
2751
+ * The media type is derived from the stream content type: `application/json`
2752
+ * (parameters ignored) yields a `json` batch, `text/*` a `text` batch, and
2753
+ * everything else (including an absent content type) a `bytes` batch.
2754
+ *
2755
+ * Throws `SyntaxError` on invalid stored JSON; callers map that to a
2756
+ * `parse-error` failure.
2757
+ */
2758
+ function encodeBatch(contentType, messages, meta) {
2759
+ const mediaType = contentType.split(";", 1)[0].trim().toLowerCase();
2760
+ if (mediaType === "application/json") {
2761
+ const body = `[${messages.map((message) => decoder.decode(message.data)).join(",")}]`;
2762
+ return {
2763
+ kind: "json",
2764
+ items: JSON.parse(body),
2765
+ ...meta
2766
+ };
2767
+ }
2768
+ if (mediaType.startsWith("text/")) return {
2769
+ kind: "text",
2770
+ text: messages.map((message) => decoder.decode(message.data)).join(""),
2771
+ ...meta
2772
+ };
2773
+ const length = messages.reduce((total, message) => total + message.data.byteLength, 0);
2774
+ const data = new Uint8Array(length);
2775
+ let position = 0;
2776
+ for (const message of messages) {
2777
+ data.set(message.data, position);
2778
+ position += message.data.byteLength;
2779
+ }
2780
+ return {
2781
+ kind: "bytes",
2782
+ data,
2783
+ ...meta
2784
+ };
2785
+ }
2786
+
2787
+ //#endregion
2788
+ //#region src/client/read-session.ts
2789
+ /**
2790
+ * The single client read-session implementation, shared by every adapter.
2791
+ *
2792
+ * It is a one-consumer, one-batch queue whose producer is backpressured by
2793
+ * iterator delivery. Iteration never throws for operational failures: the
2794
+ * terminal outcome is delivered through {@link ClientReadSession.done}, which
2795
+ * always resolves. Only programmer misuse (double iteration, concurrent
2796
+ * `next()`) throws.
2797
+ */
2798
+ var ClientReadSession = class {
2799
+ done;
2800
+ contentType;
2801
+ startOffset;
2802
+ offset;
2803
+ cursor;
2804
+ upToDate;
2805
+ streamClosed;
2806
+ doneResolve;
2807
+ pending;
2808
+ waiting;
2809
+ ended = false;
2810
+ iterated = false;
2811
+ cancelHook;
2812
+ constructor(options) {
2813
+ this.contentType = options.contentType;
2814
+ this.startOffset = options.startOffset;
2815
+ this.offset = options.offset ?? options.startOffset;
2816
+ this.cursor = options.cursor;
2817
+ this.upToDate = options.upToDate ?? false;
2818
+ this.streamClosed = options.streamClosed ?? false;
2819
+ this.cancelHook = options.onCancel;
2820
+ this.done = new Promise((resolve) => {
2821
+ this.doneResolve = resolve;
2822
+ });
2823
+ }
2824
+ setCancelHook(hook) {
2825
+ this.cancelHook = hook;
2826
+ }
2827
+ [Symbol.asyncIterator]() {
2828
+ if (this.iterated) throw new Error("A stream read session can only be iterated once");
2829
+ this.iterated = true;
2830
+ return this;
2831
+ }
2832
+ next() {
2833
+ if (this.pending) return Promise.resolve(this.acceptPending());
2834
+ if (this.ended) return Promise.resolve({
2835
+ done: true,
2836
+ value: void 0
2837
+ });
2838
+ if (this.waiting) return Promise.reject(new Error("Concurrent iterator.next() calls are invalid"));
2839
+ return new Promise((resolve) => {
2840
+ this.waiting = { resolve };
2841
+ });
2842
+ }
2843
+ return() {
2844
+ this.cancel();
2845
+ return Promise.resolve({
2846
+ done: true,
2847
+ value: void 0
2848
+ });
2849
+ }
2850
+ cancel(reason) {
2851
+ if (this.ended) return;
2852
+ this.cancelHook?.(reason);
2853
+ this.end({ status: "cancelled" });
2854
+ }
2855
+ /** Producer side: hand a batch to the consumer, backpressured until accepted. */
2856
+ async deliver(batch) {
2857
+ if (this.ended) return;
2858
+ if (this.pending) throw new Error("Read session producer exceeded its one-batch buffer");
2859
+ if (this.waiting) {
2860
+ const waiting = this.waiting;
2861
+ this.waiting = void 0;
2862
+ this.updateState(batch);
2863
+ waiting.resolve({
2864
+ done: false,
2865
+ value: batch
2866
+ });
2867
+ return;
2868
+ }
2869
+ await new Promise((accepted) => {
2870
+ this.pending = {
2871
+ batch,
2872
+ accepted
2873
+ };
2874
+ });
2875
+ }
2876
+ /** Producer side: terminate the session with its outcome. Always resolves `done`. */
2877
+ end(result) {
2878
+ if (this.ended) return;
2879
+ this.ended = true;
2880
+ this.pending?.accepted();
2881
+ this.pending = void 0;
2882
+ this.waiting?.resolve({
2883
+ done: true,
2884
+ value: void 0
2885
+ });
2886
+ this.waiting = void 0;
2887
+ this.doneResolve(result);
2888
+ }
2889
+ acceptPending() {
2890
+ const pending = this.pending;
2891
+ this.pending = void 0;
2892
+ this.updateState(pending.batch);
2893
+ pending.accepted();
2894
+ return {
2895
+ done: false,
2896
+ value: pending.batch
2897
+ };
2898
+ }
2899
+ updateState(batch) {
2900
+ this.offset = batch.offset;
2901
+ this.cursor = batch.cursor;
2902
+ this.upToDate = batch.upToDate;
2903
+ this.streamClosed = batch.streamClosed;
2904
+ }
2905
+ };
2906
+
2907
+ //#endregion
2908
+ //#region src/client/direct/results.ts
2909
+ function failure(code, message, options = {}) {
2910
+ return {
2911
+ status: "error",
2912
+ code,
2913
+ message,
2914
+ httpStatus: options.httpStatus,
2915
+ retryable: options.retryable ?? false,
2916
+ cause: options.cause
2917
+ };
2918
+ }
2919
+ function abortedFailure(cause) {
2920
+ return failure("aborted", "Stream operation was aborted", { cause });
2921
+ }
2922
+ function clientClosedFailure() {
2923
+ return failure("client-closed", "Stream protocol client is closed");
2924
+ }
2925
+ /** Maps an unexpected thrown value (not a protocol result) to a failure. */
2926
+ function failureFromThrown(error) {
2927
+ if (error instanceof SyntaxError) return failure("parse-error", error.message, { cause: error });
2928
+ if (isNotSupportedError(error)) return failure("not-supported", error.message, { cause: error });
2929
+ return failure("unknown", "Stream operation failed", { cause: error });
2930
+ }
2931
+ /** Narrows the shared absent/failure statuses of a get/metadata/read result. */
2932
+ function absentResult(result) {
2933
+ if (result.status === "not-found") return { status: "not-found" };
2934
+ if (result.status === "gone") return { status: "gone" };
2935
+ return residualFailure(result);
2936
+ }
2937
+ function mapCreate(result) {
2938
+ if (result.status === "created") return {
2939
+ status: "created",
2940
+ contentType: result.contentType
2941
+ };
2942
+ if (result.status === "exists" || result.status === "conflict") return { status: "conflict" };
2943
+ return residualFailure(result);
2944
+ }
2945
+ function mapAppend(result) {
2946
+ if (result.status === "appended" || result.status === "duplicate") return { status: "appended" };
2947
+ if (result.status === "not-found") return { status: "not-found" };
2948
+ if (result.status === "gone") return { status: "gone" };
2949
+ if (result.status === "conflict") return result.conflictReason === "closed" ? { status: "closed" } : { status: "conflict" };
2950
+ return residualFailure(result);
2951
+ }
2952
+ function mapClose(result) {
2953
+ if (result.status === "appended" || result.status === "duplicate") return {
2954
+ status: "closed",
2955
+ finalOffset: result.offset
2956
+ };
2957
+ if (result.status === "not-found") return { status: "not-found" };
2958
+ if (result.status === "gone") return { status: "gone" };
2959
+ if (result.status === "conflict") return { status: "conflict" };
2960
+ return residualFailure(result);
2961
+ }
2962
+ /** Maps a mid-read terminal protocol result to a read-session failure. */
2963
+ function readFailure(result) {
2964
+ if (result.status === "not-found") return failure("unknown", "Stream not found during read");
2965
+ if (result.status === "gone") return failure("unknown", "Stream is gone during read");
2966
+ return residualFailure(result);
2967
+ }
2968
+ function residualFailure(result) {
2969
+ switch (result.status) {
2970
+ case "not-supported": return failure("not-supported", `Feature is not supported: ${result.feature}`);
2971
+ case "bad-request":
2972
+ case "invalid-epoch-seq": return failure("bad-request", "Invalid stream request");
2973
+ case "busy": return failure("busy", "Stream is busy", { retryable: true });
2974
+ default: return failure("unknown", `Unexpected stream result: ${result.status}`);
2975
+ }
2976
+ }
2977
+
2978
+ //#endregion
2979
+ //#region src/client/direct/read.ts
2980
+ const START = "-1";
2981
+ /**
2982
+ * Resolves a read into a session and drives the catch-up (and optional live)
2983
+ * pump. The pump delivers content-aware batches and never throws into the
2984
+ * consumer: it ends the session with a {@link ReadEndResult}.
2985
+ */
2986
+ async function directRead(client, id, options) {
2987
+ return client.run(options.signal, async (operationSignal) => {
2988
+ const found = await client.streamsy.get(id);
2989
+ if (found.status !== "ok") return absentResult(found);
2990
+ const metadata = await found.stream.metadata();
2991
+ if (metadata.status !== "ok") return absentResult(metadata);
2992
+ const controller = new AbortController();
2993
+ const signal = combineSignals(operationSignal, controller.signal);
2994
+ const session = new ClientReadSession({
2995
+ contentType: metadata.contentType,
2996
+ startOffset: options.offset ?? START,
2997
+ onCancel: (reason) => controller.abort(reason)
2998
+ });
2999
+ pump(found.stream, metadata.contentType, options, signal, session);
3000
+ return {
3001
+ status: "ok",
3002
+ session
3003
+ };
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
+
2670
3201
  //#endregion
2671
3202
  //#region src/testing/storage-adapter-contract.ts
2672
3203
  const TEXT_TYPE = "text/plain";
@@ -2730,7 +3261,7 @@ async function currentRecord(adapter, id) {
2730
3261
  }
2731
3262
  /** Build an append plan that advances the tail by `texts.length` messages. */
2732
3263
  function advancePlan(record, texts) {
2733
- const allocation = allocate(record.counter, texts.length);
3264
+ const allocation = allocate(defaultOffsetGenerator, record.currentOffset, record.counter, texts.length);
2734
3265
  return {
2735
3266
  preconditions: {
2736
3267
  expectedOffset: record.currentOffset,
@@ -3344,4 +3875,4 @@ function runStorageAdapterContract(makeAdapter, harness) {
3344
3875
  }
3345
3876
 
3346
3877
  //#endregion
3347
- export { HttpHandler, NotSupportedError, ReadOnlyHttpHandler, StreamProtocol, ZERO_OFFSET, bindStream, buildChangeSnapshot, cascadeReclaim, changeSnapshotDiffers, compareOffsets, copyOnForkReclaim, createHttpHandler, createMemoryStorageAdapter, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, plainPurge, refCountLineage, reverseIndexLineage, runAwaitChangeLoop, runStorageAdapterContract, ttlOnlyReclaim, unsupported };
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@streamsy/core",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Public protocol and HTTP facades for Streamsy durable streams.",
5
5
  "homepage": "https://github.com/gingerhendrix/streamsy#readme",
6
6
  "bugs": {