@streamsy/core 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,193 @@
1
+ import { Context, Data, Effect, Option, Predicate, Record, Schema } from "effect";
2
+ // src/fault.ts
3
+ var StorageFault = class extends Schema.TaggedError()("StorageFault", {
4
+ operation: Schema.String,
5
+ message: Schema.String,
6
+ retryable: Schema.Boolean,
7
+ cause: Schema.optionalKey(Schema.Defect())
8
+ }) {};
9
+ var EncodeFault = class extends Schema.TaggedError()("EncodeFault", {
10
+ message: Schema.String,
11
+ cause: Schema.optionalKey(Schema.Defect())
12
+ }) {};
13
+ var DecodeFault = class extends Schema.TaggedError()("DecodeFault", {
14
+ message: Schema.String,
15
+ cause: Schema.optionalKey(Schema.Defect())
16
+ }) {};
17
+ /** Failures of the remote boundary; protocol rejections have their own typed errors. */
18
+ var TransportFault = class extends Schema.TaggedError()("TransportFault", {
19
+ operation: Schema.String,
20
+ reason: Schema.Literals([
21
+ "request",
22
+ "response",
23
+ "decode",
24
+ "configuration"
25
+ ]),
26
+ /** HTTP status of the response, when available. */
27
+ status: Schema.optionalKey(Schema.Int),
28
+ message: Schema.String,
29
+ cause: Schema.optionalKey(Schema.Defect())
30
+ }) {
31
+ /** Failed requests, 429s and 5xx responses can succeed later. */
32
+ get retryable() {
33
+ return this.reason === "request" || this.status !== void 0 && (this.status === 429 || this.status >= 500);
34
+ }
35
+ };
36
+ const StreamsFault = Schema.Union([StorageFault, TransportFault]);
37
+ /** A storage or transport failure, as opposed to a protocol rejection. */
38
+ const isStreamsFault = Schema.is(StreamsFault);
39
+ /** A storage or transport failure that can succeed later. */
40
+ const isRetryableFault = (error) => isStreamsFault(error) && error.retryable;
41
+ // src/internal/owner.ts
42
+ /** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
43
+ const ForeignOwnerType = Symbol.for("@streamsy/core/internal/ForeignOwner");
44
+ var ForeignOwner = class extends Data.TaggedError("ForeignOwner") {
45
+ stream;
46
+ [ForeignOwnerType] = true;
47
+ constructor(stream, knownOwner) {
48
+ super({ message: knownOwner ? `Stream write to ${stream} does not share the checkpoint owner` : `Cannot establish a storage owner for ${stream}; the exposed Storage does not own the protocol wires` });
49
+ this.stream = stream;
50
+ }
51
+ };
52
+ const isForeignOwner = (value) => Predicate.hasProperty(value, ForeignOwnerType) && value[ForeignOwnerType] === true;
53
+ const OwnerMetadata = Symbol.for("@streamsy/core/internal/CommitOwner");
54
+ const attachOwner = (value, owner) => Object.defineProperty(value, OwnerMetadata, {
55
+ value: owner,
56
+ enumerable: false
57
+ });
58
+ const ownerOf = (value) => {
59
+ if (!(OwnerMetadata in value)) return value;
60
+ const owner = value[OwnerMetadata];
61
+ return Predicate.isObjectKeyword(owner) ? owner : value;
62
+ };
63
+ const CurrentOwner = Context.Reference("@streamsy/core/internal/CurrentOwner", { defaultValue: () => void 0 });
64
+ const checkWriteOwner = (owner, id, knownOwner) => Effect.flatMap(CurrentOwner, (expected) => expected === void 0 || expected === owner ? Effect.void : Effect.die(new ForeignOwner(id, knownOwner)));
65
+ const Metadata = Symbol.for("@streamsy/core/internal/StorageOwner");
66
+ const attachStorage = (wire, storage) => Object.defineProperty(wire, Metadata, {
67
+ value: storage,
68
+ enumerable: false
69
+ });
70
+ const storageOf = (wire) => {
71
+ if (!(Metadata in wire)) return void 0;
72
+ return wire[Metadata];
73
+ };
74
+ // src/toolkit/route-internal.ts
75
+ /** Ids are canonical relative paths, the same rule the remote Layer enforces. */
76
+ function isCanonicalIdSegment(value) {
77
+ if (value.length === 0 || value === "." || value === "..") return false;
78
+ return !/[%?#/\\]/.test(value);
79
+ }
80
+ function compileSegments(template) {
81
+ if (template.length === 0) throw new RangeError("a stream route template must name at least one segment");
82
+ if (template.startsWith("/")) throw new RangeError("a stream route template is relative and cannot start with a slash");
83
+ if (/[?#*]/.test(template)) throw new RangeError("a stream route template cannot contain a query, fragment, or wildcard");
84
+ const names = [];
85
+ const segments = [];
86
+ for (const part of template.split("/")) {
87
+ if (part.length === 0) throw new RangeError("a stream route template cannot contain an empty segment");
88
+ if (!part.startsWith(":")) {
89
+ if (!isCanonicalIdSegment(part)) throw new RangeError(`a stream route literal segment is not a canonical id segment: ${part}`);
90
+ segments.push({
91
+ kind: "literal",
92
+ value: part
93
+ });
94
+ continue;
95
+ }
96
+ const name = part.slice(1);
97
+ if (name.length === 0) throw new RangeError("a stream route parameter needs a name");
98
+ if (names.includes(name)) throw new RangeError(`duplicate stream route parameter: ${name}`);
99
+ names.push(name);
100
+ segments.push({
101
+ kind: "parameter",
102
+ name
103
+ });
104
+ }
105
+ return {
106
+ template,
107
+ segments: Object.freeze(segments),
108
+ names: Object.freeze(names)
109
+ };
110
+ }
111
+ /**
112
+ * True when two template routes can both match one id.
113
+ *
114
+ * Lengths must agree, and every position must be either an equal literal pair
115
+ * or a parameter on at least one side. A parameter is treated as matching any
116
+ * segment, so a codec-constrained parameter can report an overlap it would
117
+ * never actually match. A custom route carries no template and is never
118
+ * checked; HTTP dispatch uses declaration order and the first match wins.
119
+ */
120
+ function templatesOverlap(left, right) {
121
+ if (left.length === 0 || right.length === 0) return false;
122
+ const a = compileSegments(left).segments;
123
+ const b = compileSegments(right).segments;
124
+ if (a.length !== b.length) return false;
125
+ for (const [index, segment] of a.entries()) {
126
+ const other = b[index];
127
+ if (!other || segment.kind === "parameter" || other.kind === "parameter") continue;
128
+ if (segment.value !== other.value) return false;
129
+ }
130
+ return true;
131
+ }
132
+ // src/toolkit/state-wire.ts
133
+ const upsertOperation = Schema.Union([
134
+ Schema.Literal("upsert"),
135
+ Schema.Literal("insert").transform("upsert"),
136
+ Schema.Literal("update").transform("upsert")
137
+ ]);
138
+ const headers = {
139
+ offset: Schema.optionalKey(Schema.String),
140
+ txid: Schema.optionalKey(Schema.String),
141
+ timestamp: Schema.optionalKey(Schema.String),
142
+ from: Schema.optionalKey(Schema.String)
143
+ };
144
+ const changeCodec = (type, value) => Schema.Union([Schema.Struct({
145
+ type,
146
+ key: Schema.String,
147
+ value,
148
+ headers: Schema.Struct({
149
+ operation: upsertOperation,
150
+ ...headers
151
+ })
152
+ }), Schema.Struct({
153
+ type,
154
+ key: Schema.String,
155
+ old_value: Schema.optionalKey(value),
156
+ headers: Schema.Struct({
157
+ operation: Schema.Literal("delete"),
158
+ ...headers
159
+ })
160
+ })]);
161
+ const controlCodec = Schema.Struct({ headers: Schema.Struct({
162
+ control: Schema.Literals([
163
+ "snapshot-start",
164
+ "snapshot-end",
165
+ "reset"
166
+ ]),
167
+ offset: Schema.optionalKey(Schema.String)
168
+ }) });
169
+ const rawChange = changeCodec(Schema.String, Schema.Unknown);
170
+ /** Decode the State envelope while keeping row values in their wire form. */
171
+ const decodeStateWire = Schema.decodeEffect(Schema.fromJsonString(Schema.Union([controlCodec, rawChange])));
172
+ // src/toolkit/read-message.ts
173
+ const parseJson = Schema.decodeOption(Schema.fromJsonString(Schema.Unknown));
174
+ const decodeChange = Schema.decodeUnknownOption(rawChange);
175
+ const isUndeclaredChange = (address, json) => {
176
+ if (!("collections" in address) || !Predicate.isObject(address.collections)) return false;
177
+ if ("strict" in address && address.strict === true) return false;
178
+ const parsed = parseJson(json);
179
+ if (Option.isNone(parsed)) return false;
180
+ const value = parsed.value;
181
+ if (Predicate.hasProperty(value, "headers") && Predicate.hasProperty(value.headers, "control")) return false;
182
+ const change = decodeChange(value);
183
+ return Option.isSome(change) && !Record.has(address.collections, change.value.type);
184
+ };
185
+ /** A decoded message, or None for a change outside a non-strict State address's collections. */
186
+ const decodeMessage = (address, message, index) => {
187
+ const wire = Predicate.isTagged(address, "Json") ? new TextDecoder().decode(message.data) : message.data;
188
+ return Schema.decodeEffect(address.codec)(wire).pipe(Effect.asSome, Effect.catch((cause) => Predicate.isString(wire) && isUndeclaredChange(address, wire) ? Effect.succeedNone : Effect.fail(new DecodeFault({
189
+ message: `Cannot decode ${address.id} at read message ${index}`,
190
+ cause
191
+ }))));
192
+ };
193
+ export { StorageFault as _, compileSegments as a, isRetryableFault as b, CurrentOwner as c, checkWriteOwner as d, isForeignOwner as f, EncodeFault as g, DecodeFault as h, decodeStateWire as i, attachOwner as l, storageOf as m, changeCodec as n, isCanonicalIdSegment as o, ownerOf as p, controlCodec as r, templatesOverlap as s, decodeMessage as t, attachStorage as u, StreamsFault as v, isStreamsFault as x, TransportFault as y };
@@ -1,10 +1,12 @@
1
- import { O as StreamsReader, jt as TransportFault, k as StreamsWriter } from "../projection-marks-BEZv8qDJ.js";
2
- import { D as Group, E as Any, O as Identifiers } from "../index-BtVxu6VJ.js";
1
+ import { R as StreamsReader, Vt as TransportFault, z as StreamsWriter } from "../projection-marks-DcO_5VNd.js";
2
+ import { D as Group, E as Any, O as Identifiers } from "../index-D-n48qXe.js";
3
3
  import { Layer } from "effect";
4
4
  import { HttpClient, HttpClientRequest } from "effect/http";
5
5
  interface Options {
6
6
  readonly baseUrl: string;
7
7
  readonly headers?: Readonly<Record<string, string>>;
8
+ /** Transport for live reads. Defaults to long-poll. */
9
+ readonly live?: "long-poll" | "sse";
8
10
  /** Explicit deployment contract, never inferred from a successful append. */
9
11
  readonly capabilities?: {
10
12
  readonly expectedOffset?: boolean;
@@ -14,7 +16,7 @@ interface Options {
14
16
  declare namespace streams_d_exports {
15
17
  export { Options, TransportFault, layer, layerProtocol };
16
18
  }
17
- /** Generic reader and writer over HTTP for the protocol tier. HttpClient and the calling fiber own request lifetimes. */
19
+ /** Generic reader and writer over HTTP for the protocol tier. */
18
20
  declare const layerProtocol: (options: Options) => Layer.Layer<StreamsReader | StreamsWriter, TransportFault, HttpClient.HttpClient>;
19
21
  /** Remote streams have no local change feed. */
20
22
  declare function layer<const Keys extends ReadonlyArray<Any>>(group: Group<Keys>, options: Options): Layer.Layer<Identifiers<Keys>, TransportFault, HttpClient.HttpClient>;
@@ -1,8 +1,10 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-D8jQpDG7.js";
2
- import { A as StreamBusy, D as OffsetMismatch, E as NotSupported, F as StreamsReader, I as StreamsWriter, K as TransportFault, M as StreamGone, N as StreamNotFound, O as ProducerGap, S as InvalidCreateRequest, T as InvalidReadRequest, _ as CreateResult, b as ForkSourceNotFound, g as AppendResult, j as StreamClosed, k as StaleEpoch, n as bind, rt as StreamId, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict } from "../streamsy-HKC10a_V.js";
3
- import { n as validateCreateOptions } from "../create-validation-DzLxKiux.js";
4
- import { Array, Context, DateTime, Effect, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
2
+ import { A as StreamBusy, B as isValid, D as OffsetMismatch, E as NotSupported, F as StreamsReader, I as StreamsWriter, M as StreamGone, N as StreamNotFound, O as ProducerGap, S as InvalidCreateRequest, T as InvalidReadRequest, X as StreamId, _ as CreateResult, b as ForkSourceNotFound, g as AppendResult, j as StreamClosed, k as StaleEpoch, n as bind, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict } from "../streamsy-IBFULoEr.js";
3
+ import { y as TransportFault } from "../read-message-CGHhOCMc.js";
4
+ import { n as validateCreateOptions } from "../create-validation-C_aJJm5u.js";
5
+ import { Array, Context, DateTime, Effect, Exit, Fiber, Layer, Option, Pull, Schema, Scope, Semaphore, Stream } from "effect";
5
6
  import { HttpClient, HttpClientRequest } from "effect/http";
7
+ import { Sse } from "effect/encoding";
6
8
  // src/remote/request.ts
7
9
  function requests(options) {
8
10
  const base = new URL(options.baseUrl);
@@ -30,7 +32,7 @@ function requests(options) {
30
32
  readNext: (id, input) => {
31
33
  const params = {
32
34
  offset: input.offset,
33
- live: "long-poll"
35
+ live: options.live ?? "long-poll"
34
36
  };
35
37
  if (input.cursor !== void 0) params.cursor = input.cursor;
36
38
  return HttpClientRequest.setUrlParams(make("GET", id), params);
@@ -71,7 +73,6 @@ function requests(options) {
71
73
  * a field the direct Layer returns, the decoder reports what the wire has.
72
74
  */
73
75
  const INTEGER = /^(0|[1-9]\d*)$/;
74
- const OFFSET = /^\d{16}_\d{16}$/;
75
76
  const CONTENT_TYPE = /^[^\s/;]+\/[^\s;]+(?:;.*)?$/;
76
77
  const failure = (operation, reason, message, cause, status) => status === void 0 ? new TransportFault({
77
78
  operation,
@@ -98,7 +99,7 @@ const cursor = (response) => header(response, "stream-cursor") ?? "";
98
99
  const optionalOffset = (operation, response) => {
99
100
  const value = header(response, "stream-next-offset");
100
101
  if (value === void 0) return Effect.as(Effect.void, void 0);
101
- if (!OFFSET.test(value)) return Effect.fail(failure(operation, "response", `Invalid stream-next-offset header: ${value}`, void 0, response.status));
102
+ if (!isValid(value)) return Effect.fail(failure(operation, "response", `Invalid stream-next-offset header: ${value}`, void 0, response.status));
102
103
  return Effect.succeed(value);
103
104
  };
104
105
  const offset = (operation, response) => optionalOffset(operation, response).pipe(Effect.filterOrFail((value) => value !== void 0, () => failure(operation, "response", "Missing stream-next-offset header", void 0, response.status)));
@@ -141,10 +142,12 @@ const unexpected = (operation, response) => bodyText(operation, response).pipe(E
141
142
  */
142
143
  const readMessages = (operation, response, bytes) => {
143
144
  if (bytes.byteLength === 0) return Effect.succeed([]);
144
- return contentType(operation, response).pipe(Effect.flatMap((value) => {
145
- if (value.split(";")[0]?.trim().toLowerCase() === "application/json") return text(operation, bytes).pipe(Effect.flatMap((decoded) => jsonMessages(operation, decoded)));
146
- return Effect.succeed([{ data: bytes }]);
147
- }));
145
+ return contentType(operation, response).pipe(Effect.flatMap((value) => decodeMessages(operation, value, bytes)));
146
+ };
147
+ const decodeMessages = (operation, mediaType, bytes) => {
148
+ if (bytes.byteLength === 0) return Effect.succeed([]);
149
+ if (mediaType.split(";")[0]?.trim().toLowerCase() === "application/json") return text(operation, bytes).pipe(Effect.flatMap((decoded) => jsonMessages(operation, decoded)));
150
+ return Effect.succeed([{ data: bytes }]);
148
151
  };
149
152
  const jsonArray = Schema.fromJsonString(Schema.Array(Schema.Unknown));
150
153
  const jsonMessages = (operation, decoded) => Schema.decodeEffect(jsonArray)(decoded).pipe(Effect.mapError((cause) => failure(operation, "decode", "Read body is not a JSON array", cause)), Effect.map((items) => Array.map(items, (item) => ({ data: new TextEncoder().encode(JSON.stringify(item)) }))));
@@ -257,6 +260,8 @@ const append = (operation, response, context) => Effect.gen(function* () {
257
260
  if (response.status === 409) return yield* appendConflict(operation, response, context);
258
261
  return yield* unexpected(operation, response);
259
262
  });
263
+ /** A missing or unknown `stream-conflict-reason` gives no reason. */
264
+ const conflictReason = (value) => value === "sequence" || value === "content-type" ? value : void 0;
260
265
  const appendConflict = (operation, response, context) => Effect.gen(function* () {
261
266
  const expectedSeq = yield* integer(operation, "producer-expected-seq", header(response, "producer-expected-seq"));
262
267
  const receivedSeq = yield* integer(operation, "producer-received-seq", header(response, "producer-received-seq"));
@@ -276,9 +281,15 @@ const appendConflict = (operation, response, context) => Effect.gen(function* ()
276
281
  expected: context.expectedOffset,
277
282
  actual: offset
278
283
  });
279
- return yield* new AppendConflict({
284
+ const reason = conflictReason(header(response, "stream-conflict-reason"));
285
+ const message = yield* bodyText(operation, response);
286
+ return yield* reason === void 0 ? new AppendConflict({
280
287
  id: context.id,
281
- message: yield* bodyText(operation, response)
288
+ message
289
+ }) : new AppendConflict({
290
+ id: context.id,
291
+ reason,
292
+ message
282
293
  });
283
294
  });
284
295
  const read = (operation, response, context) => Effect.gen(function* () {
@@ -345,13 +356,120 @@ const remove = (operation, response, context) => Effect.gen(function* () {
345
356
  if (response.status === 503) return yield* new StreamBusy({ id: context.id });
346
357
  return yield* unexpected(operation, response);
347
358
  });
359
+ // src/remote/sse-response.ts
360
+ const operation = "readNext";
361
+ const control = Schema.fromJsonString(Schema.Struct({
362
+ streamNextOffset: Schema.String.check(Schema.makeFilter(isValid)),
363
+ streamCursor: Schema.optionalKey(Schema.String),
364
+ streamClosed: Schema.optionalKey(Schema.Boolean),
365
+ upToDate: Schema.optionalKey(Schema.Boolean)
366
+ }));
367
+ const encoder = new TextEncoder();
368
+ const isTransportFault = Schema.is(TransportFault);
369
+ const sseContentType = (contentType) => contentType.split(";")[0]?.trim().toLowerCase() === "text/event-stream";
370
+ const batches = (response, contentType) => Effect.gen(function* () {
371
+ const encoding = header(response, "stream-sse-data-encoding");
372
+ if (encoding !== void 0 && encoding.toLowerCase() !== "base64") return yield* failure(operation, "response", `Unsupported SSE data encoding: ${encoding}`);
373
+ const bytes = (data) => encoding === void 0 ? Effect.succeed(encoder.encode(data)) : Schema.decodeEffect(Schema.Uint8ArrayFromBase64)(data).pipe(Effect.mapError((cause) => failure(operation, "decode", "Invalid base64 in SSE data", cause)));
374
+ return { pull: (yield* response.stream.pipe(Stream.mapError((cause) => failure(operation, "request", "Cannot read SSE response body", cause)), Stream.decodeText(), Stream.pipeThroughChannel(Sse.decode({ maxEventSize: Infinity })), Stream.mapError((cause) => isTransportFault(cause) ? cause : failure(operation, "decode", "Invalid SSE response body", cause)), Stream.mapAccum(() => [], (data, event) => {
375
+ if (event.event === "control") return [[], [{
376
+ data,
377
+ control: event.data
378
+ }]];
379
+ if (event.event === "data") data.push(event.data);
380
+ return [data, []];
381
+ }), Stream.rechunk(1), Stream.mapEffect((frame) => Effect.gen(function* () {
382
+ const position = yield* Schema.decodeEffect(control)(frame.control).pipe(Effect.mapError((cause) => failure(operation, "decode", "Invalid SSE control", cause)));
383
+ const messages = yield* Effect.forEach(frame.data, (data) => bytes(data).pipe(Effect.flatMap((body) => decodeMessages(operation, contentType, body)))).pipe(Effect.map(Array.flatten));
384
+ const closed = position.streamClosed === true;
385
+ return {
386
+ contentType,
387
+ messages,
388
+ timedOut: frame.data.length === 0,
389
+ nextOffset: position.streamNextOffset,
390
+ cursor: position.streamCursor ?? "",
391
+ upToDate: closed || position.upToDate === true,
392
+ closed
393
+ };
394
+ })), Stream.toPull)).pipe(Pull.catchDone(() => Effect.fail(failure(operation, "request", "SSE response ended before the next control"))), Effect.map(([batch]) => batch)) };
395
+ });
396
+ // src/remote/sse.ts
397
+ const idleTimeout = "30 seconds";
398
+ const discard = (slot) => Effect.suspend(() => {
399
+ const connection = slot.connection;
400
+ slot.connection = void 0;
401
+ return connection === void 0 ? Effect.void : Scope.close(connection.scope, Exit.void);
402
+ });
403
+ /** Serialize pulls by stream. A caller at a different position gets a fresh connection. */
404
+ const sseReadNext = (owner, open) => {
405
+ const slots = /* @__PURE__ */ new Map();
406
+ const acquire = (id) => Effect.gen(function* () {
407
+ let slot = slots.get(id);
408
+ if (slot === void 0) {
409
+ slot = {
410
+ lock: Semaphore.makeUnsafe(1),
411
+ users: 0
412
+ };
413
+ slots.set(id, slot);
414
+ }
415
+ slot.users += 1;
416
+ const idle = slot.idle;
417
+ slot.idle = void 0;
418
+ if (idle?.fiber !== void 0) yield* Fiber.interrupt(idle.fiber);
419
+ return slot;
420
+ });
421
+ const release = (id, slot) => Effect.gen(function* () {
422
+ slot.users -= 1;
423
+ if (slot.users > 0) return;
424
+ if (slot.connection === void 0) {
425
+ slots.delete(id);
426
+ return;
427
+ }
428
+ const idle = {};
429
+ slot.idle = idle;
430
+ idle.fiber = yield* Effect.sleep(idleTimeout).pipe(Effect.andThen(Effect.suspend(() => {
431
+ if (slot.idle !== idle) return Effect.void;
432
+ slots.delete(id);
433
+ return discard(slot);
434
+ })), Effect.forkIn(owner, { uninterruptible: false }));
435
+ });
436
+ const fresh = (id, input, slot) => Effect.gen(function* () {
437
+ const connection = yield* Scope.fork(owner).pipe(Effect.map((scope) => ({
438
+ scope,
439
+ ...input
440
+ })), Effect.tap((opened) => Effect.sync(() => {
441
+ slot.connection = opened;
442
+ })), Effect.uninterruptible);
443
+ const opened = yield* open(id, input).pipe(Effect.provideService(Scope.Scope, connection.scope));
444
+ if (!("pull" in opened)) return opened;
445
+ connection.pull = opened.pull;
446
+ return yield* opened.pull;
447
+ });
448
+ const read = (id, input, slot) => Effect.gen(function* () {
449
+ const connection = slot.connection;
450
+ if (connection?.pull !== void 0 && connection.offset === input.offset && (input.cursor === void 0 || connection.cursor === input.cursor)) {
451
+ const batch = yield* connection.pull.pipe(Effect.catchTag("TransportFault", (fault) => fault.retryable ? Effect.void : Effect.fail(fault)));
452
+ if (batch !== void 0) return batch;
453
+ }
454
+ yield* discard(slot);
455
+ return yield* fresh(id, input, slot);
456
+ }).pipe(Effect.onExit((exit) => {
457
+ const connection = slot.connection;
458
+ if (Exit.isFailure(exit) || exit.value.closed || connection?.pull === void 0) return discard(slot);
459
+ return Effect.sync(() => {
460
+ connection.offset = exit.value.nextOffset;
461
+ connection.cursor = exit.value.cursor;
462
+ });
463
+ }));
464
+ return (id, input) => Effect.acquireUseRelease(acquire(id), (slot) => slot.lock.withPermit(read(id, input, slot)), (slot) => release(id, slot));
465
+ };
348
466
  // src/remote/streams.ts
349
467
  var streams_exports = /* @__PURE__ */ __exportAll({
350
468
  TransportFault: () => TransportFault,
351
469
  layer: () => layer,
352
470
  layerProtocol: () => layerProtocol
353
471
  });
354
- /** Generic reader and writer over HTTP for the protocol tier. HttpClient and the calling fiber own request lifetimes. */
472
+ /** Generic reader and writer over HTTP for the protocol tier. */
355
473
  const layerProtocol = (options) => Layer.effectContext(Effect.gen(function* () {
356
474
  const client = HttpClient.withScope(yield* HttpClient.HttpClient);
357
475
  const owner = yield* Scope.Scope;
@@ -364,7 +482,8 @@ const layerProtocol = (options) => Layer.effectContext(Effect.gen(function* () {
364
482
  cause
365
483
  })
366
484
  });
367
- const execute = (operation, make, decode) => Effect.gen(function* () {
485
+ const owned = (body) => body.pipe(Effect.forkIn(owner), Effect.flatMap((fiber) => Fiber.join(fiber).pipe(Effect.ensuring(Fiber.interrupt(fiber)))));
486
+ const send = (operation, make) => Effect.gen(function* () {
368
487
  const input = yield* Effect.try({
369
488
  try: make,
370
489
  catch: (cause) => new TransportFault({
@@ -374,23 +493,34 @@ const layerProtocol = (options) => Layer.effectContext(Effect.gen(function* () {
374
493
  cause
375
494
  })
376
495
  });
377
- return yield* decode(operation, yield* client.execute(input).pipe(Effect.mapError((cause) => new TransportFault({
496
+ return yield* client.execute(input).pipe(Effect.mapError((cause) => new TransportFault({
378
497
  operation,
379
498
  reason: "request",
380
499
  message: "HTTP request failed",
381
500
  cause
382
- }))));
383
- }).pipe(Effect.scoped, Effect.forkIn(owner), Effect.flatMap((fiber) => Fiber.join(fiber).pipe(Effect.ensuring(Fiber.interrupt(fiber)))));
501
+ })));
502
+ });
503
+ const execute = (operation, make, decode) => owned(Effect.scoped(send(operation, make).pipe(Effect.flatMap((response) => decode(operation, response)))));
504
+ const head$1 = (id) => execute("head", () => request.head(id), (operation, response) => head(operation, response, { id }));
505
+ const decodeNext = (response, id) => Effect.gen(function* () {
506
+ const originalType = response.status === 204 && header(response, "content-type") === void 0 ? (yield* head$1(id)).contentType : void 0;
507
+ return yield* readNext("readNext", response, {
508
+ id,
509
+ contentType: originalType
510
+ });
511
+ });
512
+ const sse = options.live === "sse" ? sseReadNext(owner, (id, input) => Effect.gen(function* () {
513
+ const response = yield* send("readNext", () => request.readNext(id, input));
514
+ if (response.status !== 200) return yield* decodeNext(response, id);
515
+ const mediaType = yield* contentType("readNext", response);
516
+ if (!sseContentType(mediaType)) return yield* failure("readNext", "response", `Expected an SSE response, received ${mediaType}`);
517
+ const meta = yield* head$1(id);
518
+ return yield* batches(response, meta.contentType);
519
+ })) : void 0;
384
520
  const reader = {
385
- head: (id) => execute("head", () => request.head(id), (operation, response) => head(operation, response, { id })),
521
+ head: head$1,
386
522
  read: (id, input) => execute("read", () => request.read(id, input), (operation, response) => read(operation, response, { id })),
387
- readNext: (id, input) => execute("readNext", () => request.readNext(id, input), (operation, response) => Effect.gen(function* () {
388
- const contentType = response.status === 204 && header(response, "content-type") === void 0 ? (yield* reader.head(id)).contentType : void 0;
389
- return yield* readNext(operation, response, {
390
- id,
391
- contentType
392
- });
393
- }))
523
+ readNext: (id, input) => sse === void 0 ? execute("readNext", () => request.readNext(id, input), (_, response) => decodeNext(response, id)) : owned(sse(id, input))
394
524
  };
395
525
  return Context.make(StreamsReader, reader).pipe(Context.add(StreamsWriter, {
396
526
  create: (id, input) => validateCreateOptions(id, input).pipe(Effect.andThen(execute("create", () => request.create(id, input), (operation, response) => create(operation, response, {
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { l as ownerOf, n as isCanonicalIdSegment, r as templatesOverlap, s as checkWriteOwner, t as compileSegments, u as storageOf } from "./route-internal-DNL0oGTN.js";
2
+ import { a as compileSegments, b as isRetryableFault, d as checkWriteOwner, g as EncodeFault, m as storageOf, n as changeCodec, o as isCanonicalIdSegment, p as ownerOf, r as controlCodec, s as templatesOverlap, t as decodeMessage } from "./read-message-CGHhOCMc.js";
3
3
  import { Array, Context, Data, Duration, Effect, Layer, Option, Predicate, Record, Result, Schedule, Schema, Stream } from "effect";
4
4
  // src/schema/index.ts
5
5
  const StreamId = Schema.String.pipe(Schema.brand("StreamId"));
@@ -65,45 +65,6 @@ const RecordPatch = Schema.Struct({
65
65
  "lastSeq"
66
66
  ])))
67
67
  });
68
- // src/fault.ts
69
- var StorageFault = class extends Schema.TaggedError()("StorageFault", {
70
- operation: Schema.String,
71
- message: Schema.String,
72
- retryable: Schema.Boolean,
73
- cause: Schema.optionalKey(Schema.Defect())
74
- }) {};
75
- var EncodeFault = class extends Schema.TaggedError()("EncodeFault", {
76
- message: Schema.String,
77
- cause: Schema.optionalKey(Schema.Defect())
78
- }) {};
79
- var DecodeFault = class extends Schema.TaggedError()("DecodeFault", {
80
- message: Schema.String,
81
- cause: Schema.optionalKey(Schema.Defect())
82
- }) {};
83
- /** Failures of the remote boundary; protocol rejections have their own typed errors. */
84
- var TransportFault = class extends Schema.TaggedError()("TransportFault", {
85
- operation: Schema.String,
86
- reason: Schema.Literals([
87
- "request",
88
- "response",
89
- "decode",
90
- "configuration"
91
- ]),
92
- /** HTTP status of the response, when available. */
93
- status: Schema.optionalKey(Schema.Int),
94
- message: Schema.String,
95
- cause: Schema.optionalKey(Schema.Defect())
96
- }) {
97
- /** Failed requests, 429s and 5xx responses can succeed later. */
98
- get retryable() {
99
- return this.reason === "request" || this.status !== void 0 && (this.status === 429 || this.status >= 500);
100
- }
101
- };
102
- const StreamsFault = Schema.Union([StorageFault, TransportFault]);
103
- /** A storage or transport failure, as opposed to a protocol rejection. */
104
- const isStreamsFault = Schema.is(StreamsFault);
105
- /** A storage or transport failure that can succeed later. */
106
- const isRetryableFault = (error) => isStreamsFault(error) && error.retryable;
107
68
  // src/offset/index.ts
108
69
  const ZERO_OFFSET = Offset.make(`${"0".repeat(16)}_${"0".repeat(16)}`);
109
70
  const isValid = (offset) => /^\d{16}_\d{16}$/.test(offset);
@@ -151,6 +112,12 @@ var OffsetMismatch = class extends Schema.TaggedError()("OffsetMismatch", {
151
112
  };
152
113
  var AppendConflict = class extends Schema.TaggedError()("AppendConflict", {
153
114
  id: StreamId,
115
+ /**
116
+ * `sequence` when the `Stream-Seq` does not sort after the last one, `content-type` when the
117
+ * content type differs. Absent when the cause is unknown, for example from a server that does
118
+ * not send `stream-conflict-reason`.
119
+ */
120
+ reason: Schema.optionalKey(Schema.Literals(["sequence", "content-type"])),
154
121
  message: Schema.String
155
122
  }) {};
156
123
  var StreamBusy = class extends Schema.TaggedError()("StreamBusy", { id: StreamId }) {
@@ -277,44 +244,10 @@ function json$2(id, options) {
277
244
  * of setting them to `undefined`.
278
245
  */
279
246
  function stateChange(options) {
280
- const upsertOperation = Schema.Union([
281
- Schema.Literal("upsert"),
282
- Schema.Literal("insert").transform("upsert"),
283
- Schema.Literal("update").transform("upsert")
284
- ]);
285
- const headers = {
286
- offset: Schema.optionalKey(Schema.String),
287
- txid: Schema.optionalKey(Schema.String),
288
- timestamp: Schema.optionalKey(Schema.String),
289
- from: Schema.optionalKey(Schema.String)
290
- };
291
- return Schema.Union([Schema.Struct({
292
- type: Schema.Literal(options.type),
293
- key: Schema.String,
294
- value: options.schema,
295
- headers: Schema.Struct({
296
- operation: upsertOperation,
297
- ...headers
298
- })
299
- }), Schema.Struct({
300
- type: Schema.Literal(options.type),
301
- key: Schema.String,
302
- old_value: Schema.optionalKey(options.schema),
303
- headers: Schema.Struct({
304
- operation: Schema.Literal("delete"),
305
- ...headers
306
- })
307
- })]);
247
+ return changeCodec(Schema.Literal(options.type), options.schema);
308
248
  }
309
249
  /** The codec for a State control message. It needs no services. */
310
- const stateControl = Schema.Struct({ headers: Schema.Struct({
311
- control: Schema.Literals([
312
- "snapshot-start",
313
- "snapshot-end",
314
- "reset"
315
- ]),
316
- offset: Schema.optionalKey(Schema.String)
317
- }) });
250
+ const stateControl = controlCodec;
318
251
  /** True for a control message. A change has `headers.operation` and no `headers.control`. */
319
252
  const isControl = (event) => Predicate.hasProperty(event.headers, "control");
320
253
  /** True for an upsert or delete change. */
@@ -336,6 +269,7 @@ const snapshotEnd = (options = {}) => control("snapshot-end", options);
336
269
  * key is the `type` on the wire; each entry gives the value schema and the value
337
270
  * field that becomes the event `key`. The codec also decodes and encodes the
338
271
  * State control messages `snapshot-start`, `snapshot-end` and `reset`.
272
+ * Typed reads skip changes to undeclared collections unless `strict` is true.
339
273
  */
340
274
  function state$2(id, options) {
341
275
  const codecs = Array.map(Record.toEntries(options.collections), ([type, collection]) => stateChange({
@@ -343,12 +277,14 @@ function state$2(id, options) {
343
277
  type
344
278
  }));
345
279
  const address = json$2(id, { schema: Schema.Union([...codecs, stateControl]) });
346
- return new JsonAddress({
280
+ const stateAddress = new JsonAddress({
347
281
  id: address.id,
348
282
  contentType: address.contentType,
349
283
  codec: address.codec,
350
284
  collections: options.collections
351
285
  });
286
+ if (options.strict !== void 0) Object.assign(stateAddress, { strict: options.strict });
287
+ return stateAddress;
352
288
  }
353
289
  /** Items from one bytes append are joined into one stored message. */
354
290
  function bytes$2(id, options = {}) {
@@ -521,11 +457,9 @@ function concatBytes(parts) {
521
457
  return result;
522
458
  }
523
459
  const decode = Effect.fn("Streams.decode")(function* (address, result) {
460
+ const items = yield* Effect.forEach(result.messages, (message, index) => decodeMessage(address, message, index));
524
461
  return {
525
- items: yield* Effect.forEach(result.messages, (message, index) => Schema.decodeEffect(address.codec)(Predicate.isTagged(address, "Json") ? new TextDecoder().decode(message.data) : message.data).pipe(Effect.mapError((cause) => new DecodeFault({
526
- message: `Cannot decode ${address.id} at read message ${index}`,
527
- cause
528
- })))),
462
+ items: Array.getSomes(items),
529
463
  nextOffset: result.nextOffset,
530
464
  upToDate: result.upToDate,
531
465
  closed: result.closed
@@ -627,7 +561,8 @@ const capAt30Seconds = Schedule.modifyDelay(({ duration }) => Effect.succeed(Dur
627
561
  /** Same shape as `Projection.follow`'s default; kept as a copy until a third user appears. */
628
562
  const defaultFollowRetry = Schedule.exponential("200 millis").pipe(capAt30Seconds, Schedule.jittered, capAt30Seconds);
629
563
  /**
630
- * Catch up, then wait one readNext at a time, filtering empty open batches.
564
+ * Catch up, then wait one readNext at a time. A page with stored messages
565
+ * advances the reader even when all of its State changes are skipped.
631
566
  * A read that fails with a retryable transport or storage fault is retried from the same
632
567
  * offset, so a restart or network drop yields each item once.
633
568
  */
@@ -660,7 +595,7 @@ function follow(address, options = {}) {
660
595
  live: batch.upToDate,
661
596
  cursor
662
597
  };
663
- return [batch.items.length > 0 || batch.closed ? [batch] : [], batch.closed ? Option.none() : Option.some(next)];
598
+ return [result.messages.length > 0 || batch.closed ? [batch] : [], batch.closed ? Option.none() : Option.some(next)];
664
599
  }));
665
600
  }));
666
601
  }
@@ -794,4 +729,4 @@ function group(...keys) {
794
729
  checkStreams(keys);
795
730
  return Object.freeze({ streams: Object.freeze(keys) });
796
731
  }
797
- export { ProducerState as $, StreamBusy as A, isValid as B, InvalidEpochSeq as C, OffsetMismatch as D, NotSupported as E, StreamsReader as F, StreamsFault as G, DecodeFault as H, StreamsWriter as I, isStreamsFault as J, TransportFault as K, Storage as L, StreamGone as M, StreamNotFound as N, ProducerGap as O, isProtocolError as P, ProducerId as Q, ZERO_OFFSET as R, InvalidCreateRequest as S, InvalidReadRequest as T, EncodeFault as U, next as V, StorageFault as W, MessageWindow as X, ChangeSnapshot as Y, Offset as Z, CreateResult as _, custom as a, StreamRecord as at, ForkSourceNotFound as b, state as c, address_exports as d, RecordPatch as et, isControl as f, AppendResult as g, stateControl as h, checkStreams as i, StreamLifecycle as it, StreamClosed as j, StaleEpoch as k, streams_exports as l, stateChange as m, bind as n, StreamConfig as nt, group as o, isUpsert as p, isRetryableFault as q, bytes as r, StreamId as rt, json as s, Wildcard as t, StoredMessage as tt, route_exports as u, AppendConflict as v, InvalidForkRequest as w, InvalidAppendRequest as x, CreateConflict as y, compare as z };
732
+ export { StreamBusy as A, isValid as B, InvalidEpochSeq as C, OffsetMismatch as D, NotSupported as E, StreamsReader as F, ProducerId as G, ChangeSnapshot as H, StreamsWriter as I, StoredMessage as J, ProducerState as K, Storage as L, StreamGone as M, StreamNotFound as N, ProducerGap as O, isProtocolError as P, StreamRecord as Q, ZERO_OFFSET as R, InvalidCreateRequest as S, InvalidReadRequest as T, MessageWindow as U, next as V, Offset as W, StreamId as X, StreamConfig as Y, StreamLifecycle as Z, CreateResult as _, custom as a, ForkSourceNotFound as b, state as c, address_exports as d, isControl as f, AppendResult as g, stateControl as h, checkStreams as i, StreamClosed as j, StaleEpoch as k, streams_exports as l, stateChange as m, bind as n, group as o, isUpsert as p, RecordPatch as q, bytes as r, json as s, Wildcard as t, route_exports as u, AppendConflict as v, InvalidForkRequest as w, InvalidAppendRequest as x, CreateConflict as y, compare as z };
@@ -1,5 +1,5 @@
1
- import { E as StorageCapabilities, O as StreamsReader, gt as ChangeSnapshot, h as Storage, k as StreamsWriter, wt as StreamId } from "../projection-marks-BEZv8qDJ.js";
2
- import { K as MemoryOptions, q as ProtocolOptions } from "../index-BtVxu6VJ.js";
1
+ import { E as StorageCapabilities, Et as ChangeSnapshot, Pt as StreamId, R as StreamsReader, h as Storage, z as StreamsWriter } from "../projection-marks-DcO_5VNd.js";
2
+ import { K as MemoryOptions, q as ProtocolOptions } from "../index-D-n48qXe.js";
3
3
  import { Context, Effect, Layer } from "effect";
4
4
  interface StorageContractOptions {
5
5
  readonly name: string;