@streamsy/core 0.2.1 → 0.5.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,846 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { i as checkWriteOwner, o as ownerOf, s as storageOf } from "./owner-BWQ2KvC_.js";
3
+ import { Array, Context, Data, Duration, Effect, Layer, Option, Predicate, Record, Result, Schedule, Schema, Stream } from "effect";
4
+ // src/schema/index.ts
5
+ const StreamId = Schema.String.pipe(Schema.brand("StreamId"));
6
+ const Offset = Schema.String.pipe(Schema.check(Schema.isPattern(/^\d{16}_\d{16}$/)), Schema.brand("Offset"));
7
+ const ProducerId = Schema.String.pipe(Schema.brand("ProducerId"));
8
+ const StreamConfig = Schema.Struct({
9
+ contentType: Schema.String,
10
+ ttlSeconds: Schema.optionalKey(Schema.Finite),
11
+ expiresAt: Schema.optionalKey(Schema.String),
12
+ createdAt: Schema.Finite
13
+ });
14
+ const StreamLifecycle = Schema.Struct({
15
+ lastSeq: Schema.optionalKey(Schema.String),
16
+ closed: Schema.Boolean,
17
+ closedAt: Schema.optionalKey(Schema.Finite),
18
+ forkedFrom: Schema.optionalKey(StreamId),
19
+ forkOffset: Schema.optionalKey(Offset),
20
+ forkSubOffset: Schema.optionalKey(Schema.Finite),
21
+ softDeleted: Schema.Boolean,
22
+ expiresAtMs: Schema.optionalKey(Schema.Finite)
23
+ });
24
+ const StreamRecord = Schema.Struct({
25
+ id: StreamId,
26
+ config: StreamConfig,
27
+ lifecycle: StreamLifecycle,
28
+ currentOffset: Offset
29
+ });
30
+ const StoredMessage = Schema.Struct({
31
+ offset: Offset,
32
+ timestamp: Schema.Finite,
33
+ data: Schema.Uint8Array
34
+ });
35
+ const ProducerState = Schema.Struct({
36
+ epoch: Schema.Finite,
37
+ lastSeq: Schema.Finite
38
+ });
39
+ const MessageWindow = Schema.Struct({
40
+ after: Schema.optionalKey(Offset),
41
+ until: Schema.optionalKey(Offset),
42
+ limit: Schema.optionalKey(Schema.Finite)
43
+ });
44
+ const ChangeSnapshot = Schema.Struct({
45
+ present: Schema.Boolean,
46
+ currentOffset: Offset,
47
+ closed: Schema.Boolean,
48
+ softDeleted: Schema.Boolean
49
+ });
50
+ const RecordPatch = Schema.Struct({
51
+ currentOffset: Schema.optionalKey(Offset),
52
+ config: Schema.optionalKey(Schema.Struct({
53
+ ttlSeconds: Schema.optionalKey(Schema.Finite),
54
+ expiresAt: Schema.optionalKey(Schema.String)
55
+ })),
56
+ lifecycle: Schema.optionalKey(Schema.Struct({
57
+ ...StreamLifecycle.fields,
58
+ closed: Schema.optionalKey(Schema.Boolean),
59
+ softDeleted: Schema.optionalKey(Schema.Boolean)
60
+ })),
61
+ clear: Schema.optionalKey(Schema.Array(Schema.Literals([
62
+ "ttlSeconds",
63
+ "expiresAt",
64
+ "expiresAtMs",
65
+ "lastSeq"
66
+ ])))
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
+ // src/offset/index.ts
108
+ const ZERO_OFFSET = Offset.make(`${"0".repeat(16)}_${"0".repeat(16)}`);
109
+ const isValid = (offset) => /^\d{16}_\d{16}$/.test(offset);
110
+ const compare = (a, b) => a === b ? 0 : a < b ? -1 : 1;
111
+ const parse = (offset) => BigInt(offset.slice(0, 16));
112
+ /** Fixed-width successor; bigint preserves all sixteen decimal digits. */
113
+ function next(previous) {
114
+ const value = parse(previous) + 1n;
115
+ if (value > 9999999999999999n) throw new RangeError("Offset exhausted");
116
+ return Offset.make(`${String(value).padStart(16, "0")}_${"0".repeat(16)}`);
117
+ }
118
+ // src/storage/storage.ts
119
+ var Storage = class extends Context.Service()("@streamsy/core/Storage") {};
120
+ // src/protocol/tags.ts
121
+ var StreamsReader = class extends Context.Service()("@streamsy/core/StreamsReader") {};
122
+ var StreamsWriter = class extends Context.Service()("@streamsy/core/StreamsWriter") {};
123
+ // src/protocol/errors.ts
124
+ /** Protocol rejections. Optional create reasons reflect the public HTTP wire's loss of detail. */
125
+ var StreamNotFound = class extends Schema.TaggedError()("StreamNotFound", { id: StreamId }) {
126
+ get message() {
127
+ return `Stream ${this.id} was not found`;
128
+ }
129
+ };
130
+ var StreamGone = class extends Schema.TaggedError()("StreamGone", { id: StreamId }) {
131
+ get message() {
132
+ return `Stream ${this.id} was deleted`;
133
+ }
134
+ };
135
+ var StreamClosed = class extends Schema.TaggedError()("StreamClosed", {
136
+ id: StreamId,
137
+ offset: Schema.String
138
+ }) {
139
+ get message() {
140
+ return `Stream ${this.id} is closed at ${this.offset}`;
141
+ }
142
+ };
143
+ var OffsetMismatch = class extends Schema.TaggedError()("OffsetMismatch", {
144
+ id: StreamId,
145
+ expected: Schema.String,
146
+ actual: Schema.String
147
+ }) {
148
+ get message() {
149
+ return `Stream ${this.id} is at ${this.actual}, not at the expected ${this.expected}`;
150
+ }
151
+ };
152
+ var AppendConflict = class extends Schema.TaggedError()("AppendConflict", {
153
+ id: StreamId,
154
+ message: Schema.String
155
+ }) {};
156
+ var StreamBusy = class extends Schema.TaggedError()("StreamBusy", { id: StreamId }) {
157
+ get message() {
158
+ return `Stream ${this.id} is busy; try again`;
159
+ }
160
+ };
161
+ var StaleEpoch = class extends Schema.TaggedError()("StaleEpoch", {
162
+ id: StreamId,
163
+ currentEpoch: Schema.Finite
164
+ }) {
165
+ get message() {
166
+ return `Producer epoch is stale on ${this.id}; the current epoch is ${this.currentEpoch}`;
167
+ }
168
+ };
169
+ var ProducerGap = class extends Schema.TaggedError()("ProducerGap", {
170
+ id: StreamId,
171
+ expectedSeq: Schema.Finite,
172
+ receivedSeq: Schema.Finite
173
+ }) {
174
+ get message() {
175
+ return `Producer sequence gap on ${this.id}: expected ${this.expectedSeq}, received ${this.receivedSeq}`;
176
+ }
177
+ };
178
+ var InvalidEpochSeq = class extends Schema.TaggedError()("InvalidEpochSeq", { id: StreamId }) {
179
+ get message() {
180
+ return `Invalid producer epoch or sequence on ${this.id}`;
181
+ }
182
+ };
183
+ var InvalidAppendRequest = class extends Schema.TaggedError()("InvalidAppendRequest", {
184
+ id: StreamId,
185
+ message: Schema.String
186
+ }) {};
187
+ var CreateConflict = class extends Schema.TaggedError()("CreateConflict", {
188
+ id: StreamId,
189
+ reason: Schema.optionalKey(Schema.Literals([
190
+ "config-mismatch",
191
+ "soft-deleted",
192
+ "fork-content-type",
193
+ "fork-source-soft-deleted"
194
+ ])),
195
+ message: Schema.String
196
+ }) {};
197
+ var ForkSourceNotFound = class extends Schema.TaggedError()("ForkSourceNotFound", {
198
+ id: StreamId,
199
+ source: StreamId
200
+ }) {
201
+ get message() {
202
+ return `Fork source ${this.source} of ${this.id} was not found`;
203
+ }
204
+ };
205
+ var InvalidForkRequest = class extends Schema.TaggedError()("InvalidForkRequest", {
206
+ id: StreamId,
207
+ message: Schema.String
208
+ }) {};
209
+ var NotSupported = class extends Schema.TaggedError()("NotSupported", {
210
+ id: StreamId,
211
+ feature: Schema.String
212
+ }) {
213
+ get message() {
214
+ return `Stream ${this.id} does not support ${this.feature}`;
215
+ }
216
+ };
217
+ var InvalidReadRequest = class extends Schema.TaggedError()("InvalidReadRequest", {
218
+ id: StreamId,
219
+ message: Schema.String
220
+ }) {};
221
+ /** Exhaustive record of every protocol tag, checked against the union it must cover. */
222
+ const protocolErrorTags = {
223
+ InvalidReadRequest: true,
224
+ StreamNotFound: true,
225
+ StreamGone: true,
226
+ StreamClosed: true,
227
+ OffsetMismatch: true,
228
+ AppendConflict: true,
229
+ StreamBusy: true,
230
+ StaleEpoch: true,
231
+ ProducerGap: true,
232
+ InvalidEpochSeq: true,
233
+ InvalidAppendRequest: true,
234
+ CreateConflict: true,
235
+ ForkSourceNotFound: true,
236
+ InvalidForkRequest: true,
237
+ NotSupported: true
238
+ };
239
+ /** The HTTP edge answers every protocol rejection through one mapper, so it needs one guard. */
240
+ const isProtocolError = (error) => Record.has(protocolErrorTags, error._tag);
241
+ // src/protocol/results.ts
242
+ /** Constructors and matchers for the protocol results above. */
243
+ const CreateResult = Data.taggedEnum();
244
+ const AppendResult = Data.taggedEnum();
245
+ // src/toolkit/route-internal.ts
246
+ /** Ids are canonical relative paths, the same rule the remote Layer enforces. */
247
+ function isCanonicalIdSegment(value) {
248
+ if (value.length === 0 || value === "." || value === "..") return false;
249
+ return !/[%?#/\\]/.test(value);
250
+ }
251
+ function compileSegments(template) {
252
+ if (template.length === 0) throw new RangeError("a stream route template must name at least one segment");
253
+ if (template.startsWith("/")) throw new RangeError("a stream route template is relative and cannot start with a slash");
254
+ if (/[?#*]/.test(template)) throw new RangeError("a stream route template cannot contain a query, fragment, or wildcard");
255
+ const names = [];
256
+ const segments = [];
257
+ for (const part of template.split("/")) {
258
+ if (part.length === 0) throw new RangeError("a stream route template cannot contain an empty segment");
259
+ if (!part.startsWith(":")) {
260
+ if (!isCanonicalIdSegment(part)) throw new RangeError(`a stream route literal segment is not a canonical id segment: ${part}`);
261
+ segments.push({
262
+ kind: "literal",
263
+ value: part
264
+ });
265
+ continue;
266
+ }
267
+ const name = part.slice(1);
268
+ if (name.length === 0) throw new RangeError("a stream route parameter needs a name");
269
+ if (names.includes(name)) throw new RangeError(`duplicate stream route parameter: ${name}`);
270
+ names.push(name);
271
+ segments.push({
272
+ kind: "parameter",
273
+ name
274
+ });
275
+ }
276
+ return {
277
+ template,
278
+ segments: Object.freeze(segments),
279
+ names: Object.freeze(names)
280
+ };
281
+ }
282
+ /**
283
+ * True when two template routes can both match one id.
284
+ *
285
+ * Lengths must agree, and every position must be either an equal literal pair
286
+ * or a parameter on at least one side. A parameter is treated as matching any
287
+ * segment, so a codec-constrained parameter can report an overlap it would
288
+ * never actually match. A custom route carries no template and is never
289
+ * checked; HTTP dispatch uses declaration order and the first match wins.
290
+ */
291
+ function templatesOverlap(left, right) {
292
+ if (left.length === 0 || right.length === 0) return false;
293
+ const a = compileSegments(left).segments;
294
+ const b = compileSegments(right).segments;
295
+ if (a.length !== b.length) return false;
296
+ for (const [index, segment] of a.entries()) {
297
+ const other = b[index];
298
+ if (!other || segment.kind === "parameter" || other.kind === "parameter") continue;
299
+ if (segment.value !== other.value) return false;
300
+ }
301
+ return true;
302
+ }
303
+ // src/toolkit/address.ts
304
+ var address_exports = /* @__PURE__ */ __exportAll({
305
+ bytes: () => bytes$2,
306
+ isChange: () => isChange,
307
+ isControl: () => isControl,
308
+ json: () => json$2,
309
+ reset: () => reset,
310
+ snapshotEnd: () => snapshotEnd,
311
+ snapshotStart: () => snapshotStart,
312
+ state: () => state$2,
313
+ stateChange: () => stateChange,
314
+ stateControl: () => stateControl
315
+ });
316
+ /** The address constructors. Each class owns the `_tag` of one address kind. */
317
+ const JsonAddress = Data.TaggedClass("Json");
318
+ const BytesAddress = Data.TaggedClass("Bytes");
319
+ function json$2(id, options) {
320
+ return new JsonAddress({
321
+ id: StreamId.make(id),
322
+ contentType: "application/json",
323
+ codec: Schema.fromJsonString(Schema.toCodecJson(options.schema))
324
+ });
325
+ }
326
+ /**
327
+ * A codec for the upsert and delete change events of one collection.
328
+ * `state` composes one of these per collection. Omit optional headers instead
329
+ * of setting them to `undefined`.
330
+ */
331
+ function stateChange(options) {
332
+ const upsertOperation = Schema.Union([
333
+ Schema.Literal("upsert"),
334
+ Schema.Literal("insert").transform("upsert"),
335
+ Schema.Literal("update").transform("upsert")
336
+ ]);
337
+ const headers = {
338
+ offset: Schema.optionalKey(Schema.String),
339
+ txid: Schema.optionalKey(Schema.String),
340
+ timestamp: Schema.optionalKey(Schema.String),
341
+ from: Schema.optionalKey(Schema.String)
342
+ };
343
+ return Schema.Union([Schema.Struct({
344
+ type: Schema.Literal(options.type),
345
+ key: Schema.String,
346
+ value: options.schema,
347
+ headers: Schema.Struct({
348
+ operation: upsertOperation,
349
+ ...headers
350
+ })
351
+ }), Schema.Struct({
352
+ type: Schema.Literal(options.type),
353
+ key: Schema.String,
354
+ old_value: Schema.optionalKey(options.schema),
355
+ headers: Schema.Struct({
356
+ operation: Schema.Literal("delete"),
357
+ ...headers
358
+ })
359
+ })]);
360
+ }
361
+ /** The codec for a State control message. It needs no services. */
362
+ const stateControl = Schema.Struct({ headers: Schema.Struct({
363
+ control: Schema.Literals([
364
+ "snapshot-start",
365
+ "snapshot-end",
366
+ "reset"
367
+ ]),
368
+ offset: Schema.optionalKey(Schema.String)
369
+ }) });
370
+ /** True for a control message. A change has `headers.operation` and no `headers.control`. */
371
+ const isControl = (event) => Predicate.hasProperty(event.headers, "control");
372
+ /** True for an upsert or delete change. */
373
+ const isChange = (event) => !isControl(event);
374
+ const control = (name, options) => ({ headers: options.offset === void 0 ? { control: name } : {
375
+ control: name,
376
+ offset: options.offset
377
+ } });
378
+ /** A `reset` control. A reader should clear its materialized state and apply what follows. */
379
+ const reset = (options = {}) => control("reset", options);
380
+ /** A `snapshot-start` control. The changes up to `snapshot-end` form a complete snapshot. */
381
+ const snapshotStart = (options = {}) => control("snapshot-start", options);
382
+ /** A `snapshot-end` control. It closes the snapshot that `snapshot-start` opened. */
383
+ const snapshotEnd = (options = {}) => control("snapshot-end", options);
384
+ /**
385
+ * A stream of Durable State events for several collections. Each record
386
+ * key is the `type` on the wire; each entry gives the value schema and the value
387
+ * field that becomes the event `key`. The codec also decodes and encodes the
388
+ * State control messages `snapshot-start`, `snapshot-end` and `reset`.
389
+ */
390
+ function state$2(id, options) {
391
+ const codecs = Array.map(Record.toEntries(options.collections), ([type, collection]) => stateChange({
392
+ schema: collection.schema,
393
+ type
394
+ }));
395
+ const address = json$2(id, { schema: Schema.Union([...codecs, stateControl]) });
396
+ return new JsonAddress({
397
+ id: address.id,
398
+ contentType: address.contentType,
399
+ codec: address.codec,
400
+ collections: options.collections
401
+ });
402
+ }
403
+ /** Items from one bytes append are joined into one stored message. */
404
+ function bytes$2(id, options = {}) {
405
+ return new BytesAddress({
406
+ id: StreamId.make(id),
407
+ contentType: options.contentType ?? "application/octet-stream",
408
+ codec: Schema.Uint8Array
409
+ });
410
+ }
411
+ // src/toolkit/route.ts
412
+ var route_exports = /* @__PURE__ */ __exportAll({
413
+ bytes: () => bytes$1,
414
+ custom: () => custom$1,
415
+ json: () => json$1,
416
+ state: () => state$1
417
+ });
418
+ /** The route constructor. It owns the `StreamRoute` tag of every route. */
419
+ const Route = Data.TaggedClass("StreamRoute");
420
+ function pathSchema(codecs) {
421
+ return Schema.Struct(codecs);
422
+ }
423
+ function decodeParams(codecs, raw) {
424
+ const decoded = {};
425
+ for (const name of Record.keys(codecs)) {
426
+ const value = raw[name];
427
+ const codec = codecs[name];
428
+ if (value === void 0 || codec === void 0) return Option.none();
429
+ const result = Schema.decodeOption(codec)(value);
430
+ if (Option.isNone(result)) return Option.none();
431
+ decoded[name] = result.value;
432
+ }
433
+ return Option.some(decoded);
434
+ }
435
+ function matchTemplate(segments, codecs, id) {
436
+ const actual = id.split("/");
437
+ if (actual.length !== segments.length) return Option.none();
438
+ const raw = {};
439
+ for (const [index, segment] of segments.entries()) {
440
+ const value = actual[index];
441
+ if (value === void 0) return Option.none();
442
+ if (segment.kind === "literal") {
443
+ if (value !== segment.value) return Option.none();
444
+ continue;
445
+ }
446
+ if (!isCanonicalIdSegment(value)) return Option.none();
447
+ raw[segment.name] = value;
448
+ }
449
+ return decodeParams(codecs, raw);
450
+ }
451
+ function buildId(template, segments, codecs, params) {
452
+ const record = params;
453
+ const built = Array.map(segments, (segment) => {
454
+ if (segment.kind === "literal") return segment.value;
455
+ const codec = codecs[segment.name];
456
+ const value = record[segment.name];
457
+ if (codec === void 0 || value === void 0) throw new RangeError(`stream route ${template} has no value for parameter: ${segment.name}`);
458
+ const text = Option.getOrUndefined(Schema.encodeOption(codec)(value));
459
+ if (text === void 0) throw new RangeError(`stream route ${template} parameter ${segment.name} cannot encode to an id segment`);
460
+ if (!isCanonicalIdSegment(text)) throw new RangeError(`stream route ${template} parameter ${segment.name} is not a canonical id segment: ${text}`);
461
+ return text;
462
+ });
463
+ return StreamId.make(Array.join(built, "/"));
464
+ }
465
+ /**
466
+ * The codec record and the template must name the same parameters. The type
467
+ * check covers the common case; this backstop covers a widened template.
468
+ */
469
+ function checkTemplateParams(template, names, codecs) {
470
+ for (const name of names) if (codecs[name] === void 0) throw new RangeError(`stream route ${template} has no codec for parameter: ${name}`);
471
+ for (const name of Record.keys(codecs)) if (!names.includes(name)) throw new RangeError(`stream route codec is absent from the template: ${name}`);
472
+ }
473
+ function json$1(template, options) {
474
+ const { segments, names } = compileSegments(template);
475
+ const codecs = options.params;
476
+ checkTemplateParams(template, names, codecs);
477
+ return new Route({
478
+ template,
479
+ paramSchema: pathSchema(codecs),
480
+ match: (id) => Option.isSome(matchTemplate(segments, codecs, id)),
481
+ parse: (id) => matchTemplate(segments, codecs, id),
482
+ address: (params) => json$2(buildId(template, segments, codecs, params), options)
483
+ });
484
+ }
485
+ function state$1(template, options) {
486
+ const { segments, names } = compileSegments(template);
487
+ const codecs = options.params;
488
+ checkTemplateParams(template, names, codecs);
489
+ return new Route({
490
+ template,
491
+ paramSchema: pathSchema(codecs),
492
+ match: (id) => Option.isSome(matchTemplate(segments, codecs, id)),
493
+ parse: (id) => matchTemplate(segments, codecs, id),
494
+ collections: options.collections,
495
+ address: (params) => state$2(buildId(template, segments, codecs, params), options)
496
+ });
497
+ }
498
+ function bytes$1(template, options) {
499
+ const { segments, names } = compileSegments(template);
500
+ const codecs = options.params;
501
+ checkTemplateParams(template, names, codecs);
502
+ return new Route({
503
+ template,
504
+ paramSchema: pathSchema(codecs),
505
+ match: (id) => Option.isSome(matchTemplate(segments, codecs, id)),
506
+ parse: (id) => matchTemplate(segments, codecs, id),
507
+ address: (params) => bytes$2(buildId(template, segments, codecs, params), { contentType: options.contentType ?? "application/octet-stream" })
508
+ });
509
+ }
510
+ /** Escape hatch for a grammar a template cannot express, such as a regex stream. */
511
+ function custom$1(options) {
512
+ return new Route({
513
+ template: "",
514
+ match: (id) => Option.isSome(options.parse(id)),
515
+ parse: options.parse,
516
+ address: options.address
517
+ });
518
+ }
519
+ // src/toolkit/streams.ts
520
+ var streams_exports = /* @__PURE__ */ __exportAll({
521
+ append: () => append,
522
+ collect: () => collect,
523
+ create: () => create,
524
+ decide: () => decide,
525
+ fold: () => fold,
526
+ follow: () => follow,
527
+ head: () => head,
528
+ items: () => items,
529
+ read: () => read,
530
+ remove: () => remove,
531
+ session: () => session
532
+ });
533
+ const create = Effect.fn("Streams.create")(function* (address, options = {}) {
534
+ return yield* (yield* StreamsWriter).create(address.id, {
535
+ ...options,
536
+ contentType: address.contentType
537
+ });
538
+ });
539
+ /** Whether these options can lead to this rejection. Any other rejection is a host bug. */
540
+ const possibleFor = (options, error) => Predicate.isTagged(error, "InvalidAppendRequest") || Predicate.isTagged(error, "InvalidEpochSeq") ? false : Predicate.isTagged(error, "OffsetMismatch") ? options.expectedOffset !== void 0 : Predicate.isTagged(error, "StaleEpoch") || Predicate.isTagged(error, "ProducerGap") ? options.producer !== void 0 : true;
541
+ /**
542
+ * Append items to one stream. The error type lists only the rejections that the
543
+ * options make possible; a host that answers another one dies.
544
+ */
545
+ const append = Effect.fn("Streams.append")(function* (address, items, options) {
546
+ const callOptions = options ?? {};
547
+ const list = items;
548
+ const encoded = yield* Effect.forEach(list, (item) => Schema.encodeEffect(address.codec)(item).pipe(Effect.mapError((cause) => new EncodeFault({
549
+ message: `Cannot encode ${address.id}`,
550
+ cause
551
+ }))));
552
+ for (const item of encoded) if (Predicate.isUint8Array(item) && item.byteLength === 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Cannot append an empty bytes item to ${address.id}`));
553
+ const data = list.length === 0 && callOptions.close ? /* @__PURE__ */ new Uint8Array() : Predicate.isTagged(address, "Json") ? new TextEncoder().encode(`[${Array.join(Array.map(encoded, String), ",")}]`) : concatBytes(encoded);
554
+ const possible = (error) => possibleFor(callOptions, error);
555
+ const appended = (yield* StreamsWriter).append(address.id, {
556
+ ...callOptions,
557
+ data,
558
+ contentType: address.contentType
559
+ });
560
+ return yield* Effect.catchIf(appended, possible, Effect.fail, Effect.die);
561
+ });
562
+ function concatBytes(parts) {
563
+ const arrays = Array.map(parts, (part) => Predicate.isString(part) ? new TextEncoder().encode(part) : part);
564
+ const result = new Uint8Array(Array.reduce(arrays, 0, (size, part) => size + part.byteLength));
565
+ let offset = 0;
566
+ for (const part of arrays) {
567
+ result.set(part, offset);
568
+ offset += part.byteLength;
569
+ }
570
+ return result;
571
+ }
572
+ const decode = Effect.fn("Streams.decode")(function* (address, result) {
573
+ return {
574
+ 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({
575
+ message: `Cannot decode ${address.id} at read message ${index}`,
576
+ cause
577
+ })))),
578
+ nextOffset: result.nextOffset,
579
+ upToDate: result.upToDate,
580
+ closed: result.closed
581
+ };
582
+ });
583
+ function read(address, options = {}) {
584
+ return Stream.unwrap(Effect.gen(function* () {
585
+ const reader = yield* StreamsReader;
586
+ return Stream.paginate(options.offset, (offset) => Effect.gen(function* () {
587
+ const batch = yield* decode(address, yield* reader.read(address.id, {
588
+ ...options,
589
+ offset
590
+ }));
591
+ return [[batch], batch.upToDate ? Option.none() : Option.some(batch.nextOffset)];
592
+ }));
593
+ }));
594
+ }
595
+ /**
596
+ * Read the stream up to its tail and fold every item into one value. Pass
597
+ * `options.offset` to fold on from a tail that an earlier fold returned.
598
+ */
599
+ const fold = Effect.fn("Streams.fold")(function* (address, initial, f, options = {}) {
600
+ return yield* read(address, options).pipe(Stream.runFold(() => ({
601
+ state: initial(),
602
+ offset: options.offset ?? ZERO_OFFSET
603
+ }), (folded, batch) => {
604
+ let state = folded.state;
605
+ for (const item of batch.items) state = f(state, item);
606
+ return {
607
+ state,
608
+ offset: batch.nextOffset
609
+ };
610
+ }));
611
+ });
612
+ /** Read the stream up to its tail and return its items. */
613
+ const collect = Effect.fn("Streams.collect")(function* (address, options = {}) {
614
+ const { state, offset } = yield* fold(address, () => [], (items, item) => {
615
+ items.push(item);
616
+ return items;
617
+ }, options);
618
+ return {
619
+ items: state,
620
+ offset
621
+ };
622
+ });
623
+ /** Up to three retries after a lost race, so at most four appends per call. */
624
+ const defaultDecideRetry = Schedule.recurs(3);
625
+ /**
626
+ * Read, decide, append. Fold the stream to its tail, decide from the state, and
627
+ * append with `expectedOffset` set to the tail that was read. After an
628
+ * `OffsetMismatch`, fold on from that tail and decide again while `retry` allows;
629
+ * then fail with the last `OffsetMismatch`. Transport faults are not retried: a
630
+ * lost reply may hide an append that landed.
631
+ */
632
+ const decide = Effect.fn("Streams.decide")(function* (address, spec) {
633
+ let folded;
634
+ const attempt = Effect.gen(function* () {
635
+ const last = folded;
636
+ folded = last === void 0 ? yield* fold(address, spec.initial, spec.fold) : yield* fold(address, () => last.state, spec.fold, { offset: last.offset });
637
+ const { state, offset } = folded;
638
+ const { value, items } = yield* spec.decide(state, { offset });
639
+ if (!Array.isReadonlyArrayNonEmpty(items)) return {
640
+ value,
641
+ offset,
642
+ appended: false
643
+ };
644
+ return {
645
+ value,
646
+ offset: (yield* append(address, items, { expectedOffset: offset }).pipe(Effect.catchTag("OffsetMismatch", (mismatch) => Effect.fail(new LostRace(mismatch))))).offset,
647
+ appended: true
648
+ };
649
+ });
650
+ return yield* retryLostRace(attempt, spec.retry ?? defaultDecideRetry);
651
+ });
652
+ /**
653
+ * Marks the `OffsetMismatch` of a decide loop's own append. Only this error is
654
+ * retried: an `OffsetMismatch` that the caller's `decide` raises is its own
655
+ * failure and passes through.
656
+ */
657
+ var LostRace = class {
658
+ mismatch;
659
+ constructor(mismatch) {
660
+ this.mismatch = mismatch;
661
+ }
662
+ };
663
+ /**
664
+ * Retry `attempt` after a `LostRace` while `schedule` allows, then fail with the
665
+ * last `OffsetMismatch`. `retry` steps its schedule with every error it sees, so
666
+ * every other outcome passes the retry as a `Result` and is raised after.
667
+ */
668
+ const retryLostRace = Effect.fnUntraced(function* (attempt, schedule) {
669
+ const outcome = yield* attempt.pipe(Effect.matchEffect({
670
+ onFailure: (error) => error instanceof LostRace ? Effect.fail(error.mismatch) : Effect.succeed(Result.fail(error)),
671
+ onSuccess: (value) => Effect.succeed(Result.succeed(value))
672
+ }), Effect.retry(schedule));
673
+ return yield* Effect.fromResult(outcome);
674
+ });
675
+ const capAt30Seconds = Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.millis(Math.min(3e4, Duration.toMillis(duration)))));
676
+ /** Same shape as `Projection.follow`'s default; kept as a copy until a third user appears. */
677
+ const defaultFollowRetry = Schedule.exponential("200 millis").pipe(capAt30Seconds, Schedule.jittered, capAt30Seconds);
678
+ /**
679
+ * Catch up, then wait one readNext at a time, filtering empty open batches.
680
+ * A read that fails with a retryable transport or storage fault is retried from the same
681
+ * offset, so a restart or network drop yields each item once.
682
+ */
683
+ function follow(address, options = {}) {
684
+ const { retry = defaultFollowRetry, ...readOptions } = options;
685
+ const retrying = (reading) => reading.pipe(Effect.tapError((error) => isRetryableFault(error) ? Effect.logWarning("Streams.follow retry", error) : Effect.void), Effect.retry({
686
+ while: isRetryableFault,
687
+ schedule: retry
688
+ }));
689
+ return Stream.unwrap(Effect.gen(function* () {
690
+ const reader = yield* StreamsReader;
691
+ const initial = {
692
+ offset: readOptions.offset,
693
+ live: false,
694
+ cursor: void 0
695
+ };
696
+ const live = (state) => reader.readNext(address.id, {
697
+ offset: state.offset ?? "-1",
698
+ cursor: state.cursor
699
+ }).pipe(Effect.map((result) => [result, result.cursor]));
700
+ const catchUp = (state) => reader.read(address.id, {
701
+ ...readOptions,
702
+ offset: state.offset
703
+ }).pipe(Effect.map((result) => [result, state.cursor]));
704
+ return Stream.paginate(initial, (state) => Effect.gen(function* () {
705
+ const [result, cursor] = yield* retrying(state.live ? live(state) : catchUp(state));
706
+ const batch = yield* decode(address, result);
707
+ const next = {
708
+ offset: batch.nextOffset,
709
+ live: batch.upToDate,
710
+ cursor
711
+ };
712
+ return [batch.items.length > 0 || batch.closed ? [batch] : [], batch.closed ? Option.none() : Option.some(next)];
713
+ }));
714
+ }));
715
+ }
716
+ const items = (batches) => batches.pipe(Stream.flatMap((batch) => Stream.fromIterable(batch.items)));
717
+ const session = Effect.fn("Streams.session")(function* (address, options) {
718
+ return yield* (yield* StreamsReader).readNext(address.id, options);
719
+ });
720
+ const head = Effect.fn("Streams.head")(function* (address) {
721
+ return yield* (yield* StreamsReader).head(address.id);
722
+ });
723
+ const remove = Effect.fn("Streams.remove")(function* (address) {
724
+ return yield* (yield* StreamsWriter).remove(address.id);
725
+ });
726
+ // src/toolkit/streamsy.ts
727
+ const templateOf = (route) => {
728
+ if (!("template" in route)) return void 0;
729
+ const template = route.template;
730
+ if (!Predicate.isString(template)) return void 0;
731
+ return template.length > 0 ? template : void 0;
732
+ };
733
+ /** Template streams must have disjoint id grammars. Custom routes use declaration order. */
734
+ function checkNoOverlap(routes) {
735
+ const templates = Array.flatMap(routes, (route) => {
736
+ const template = templateOf(route);
737
+ return template === void 0 ? [] : [template];
738
+ });
739
+ for (const [index, template] of templates.entries()) for (const other of templates.slice(index + 1)) if (templatesOverlap(template, other)) throw new RangeError(`stream route templates overlap: ${template} and ${other}`);
740
+ }
741
+ /** Build a stream service over one protocol graph's wires, with the ownership guard on writes. */
742
+ function wireApi(route, services) {
743
+ const storage = storageOf(services.writer);
744
+ const owner = storage === void 0 ? services.writer : ownerOf(storage);
745
+ const write = (id, run) => checkWriteOwner(owner, id, storage !== void 0).pipe(Effect.andThen(Effect.suspend(run)));
746
+ const own = (id, run) => Effect.suspend(() => route.match(id) ? run() : Effect.die(/* @__PURE__ */ new RangeError(`${id} is outside stream ${route.template}`)));
747
+ const wire = {
748
+ head: (id) => own(id, () => services.reader.head(id)),
749
+ read: (id, options) => own(id, () => services.reader.read(id, options)),
750
+ readNext: (id, options) => own(id, () => services.reader.readNext(id, options)),
751
+ create: (id, options) => write(id, () => own(id, () => options?.forkedFrom === void 0 ? services.writer.create(id, options) : route.match(options.forkedFrom) ? services.writer.create(id, options) : Effect.fail(new ForkSourceNotFound({
752
+ id,
753
+ source: StreamId.make(options.forkedFrom)
754
+ })))),
755
+ fork: (id, source, options) => write(id, () => own(id, () => route.match(source) ? services.writer.fork(id, source, options) : Effect.fail(new ForkSourceNotFound({
756
+ id,
757
+ source
758
+ })))),
759
+ append: (id, options) => write(id, () => own(id, () => services.writer.append(id, options))),
760
+ remove: (id) => write(id, () => own(id, () => services.writer.remove(id)))
761
+ };
762
+ const context = Context.make(StreamsReader, wire).pipe(Context.add(StreamsWriter, wire));
763
+ return {
764
+ owner,
765
+ route,
766
+ wire,
767
+ create: (params, options) => create(route.address(params), options).pipe(Effect.provide(context)),
768
+ append: (params, items, options) => append(route.address(params), items, options).pipe(Effect.provide(context)),
769
+ read: (params, options) => read(route.address(params), options).pipe(Stream.provideContext(context)),
770
+ fold: (params, initial, f, options) => fold(route.address(params), initial, f, options).pipe(Effect.provide(context)),
771
+ collect: (params, options) => collect(route.address(params), options).pipe(Effect.provide(context)),
772
+ decide: (params, spec) => decide(route.address(params), spec).pipe(Effect.provide(context)),
773
+ follow: (params, options) => follow(route.address(params), options).pipe(Stream.provideContext(context)),
774
+ session: (params, options) => wire.readNext(route.address(params).id, options),
775
+ head: (params) => wire.head(route.address(params).id),
776
+ remove: (params) => wire.remove(route.address(params).id),
777
+ fork: (params, source, options) => wire.fork(route.address(params).id, route.address(source).id, {
778
+ ...options,
779
+ contentType: route.address(params).contentType
780
+ })
781
+ };
782
+ }
783
+ /**
784
+ * Names are global Context identities, including across separate providers.
785
+ * Use an application namespace for distinct streams. Reusing a name intentionally
786
+ * aliases the service; providers cannot detect collisions in other Layer graphs.
787
+ * Wildcard is reserved for the built-in catch-all and its intentional aliases.
788
+ */
789
+ function define() {
790
+ return (name, route) => {
791
+ const key = `@streamsy/core/Stream/${name}`;
792
+ const service = Context.Service()(key);
793
+ const declared = Object.defineProperty(service, metadataKey, { value: {
794
+ route,
795
+ make: (services) => wireApi(route, services)
796
+ } });
797
+ return Object.assign(declared, route, { at: (params) => {
798
+ return Object.assign(route.address(params), { stream: service });
799
+ } });
800
+ };
801
+ }
802
+ const json = () => (name, ...args) => define()(name, json$1(...args));
803
+ const state = () => (name, ...args) => define()(name, state$1(...args));
804
+ const bytes = () => (name, ...args) => define()(name, bytes$1(...args));
805
+ const custom = () => (name, options) => define()(name, custom$1(options));
806
+ const metadataKey = Symbol.for("@streamsy/core/Stream/metadata");
807
+ function declaration(key) {
808
+ const value = key[metadataKey];
809
+ if (value === void 0) throw new TypeError(`Unknown stream declaration: ${key.key}`);
810
+ return value;
811
+ }
812
+ var Wildcard = class extends define()("Wildcard", custom$1({
813
+ parse: (id) => Option.some({ id }),
814
+ address: ({ id }) => bytes$2(id)
815
+ })) {};
816
+ function checkStreams(keys) {
817
+ const templates = /* @__PURE__ */ new Set();
818
+ const names = /* @__PURE__ */ new Set();
819
+ for (const [index, key] of keys.entries()) {
820
+ if (names.has(key.key)) throw new RangeError(`duplicate stream name: ${key.key}`);
821
+ names.add(key.key);
822
+ if (key.template !== "" && templates.has(key.template)) throw new RangeError(`duplicate stream template: ${key.template}`);
823
+ templates.add(key.template);
824
+ if (key.key === Wildcard.key && index !== keys.length - 1) throw new RangeError("Wildcard must be last");
825
+ }
826
+ checkNoOverlap(Array.map(keys, (key) => declaration(key).route));
827
+ }
828
+ function bind(source, streams) {
829
+ const keys = streams.streams;
830
+ checkStreams(keys);
831
+ const bindContext = (wires, storage) => {
832
+ if (storage !== void 0 && (storageOf(wires.reader) !== storage || storageOf(wires.writer) !== storage)) throw new RangeError("The exposed Storage does not own the protocol wires");
833
+ let context = Context.empty();
834
+ for (const key of keys) context = Context.add(context, key, declaration(key).make(wires));
835
+ return context;
836
+ };
837
+ return source.pipe(Layer.flatMap((context) => Layer.syncContext(() => bindContext({
838
+ reader: Context.get(context, StreamsReader),
839
+ writer: Context.get(context, StreamsWriter)
840
+ }, Option.getOrUndefined(Context.getOption(context, Storage))))));
841
+ }
842
+ function group(...keys) {
843
+ checkStreams(keys);
844
+ return Object.freeze({ streams: Object.freeze(keys) });
845
+ }
846
+ export { StreamLifecycle as $, StreamsReader as A, StreamsFault as B, ProducerGap as C, StreamGone as D, StreamClosed as E, isValid as F, MessageWindow as G, isRetryableFault as H, next as I, ProducerState as J, Offset as K, DecodeFault as L, Storage as M, ZERO_OFFSET as N, StreamNotFound as O, compare as P, StreamId as Q, EncodeFault as R, OffsetMismatch as S, StreamBusy as T, isStreamsFault as U, TransportFault as V, ChangeSnapshot as W, StoredMessage as X, RecordPatch as Y, StreamConfig as Z, InvalidAppendRequest as _, custom as a, InvalidReadRequest as b, state as c, address_exports as d, StreamRecord as et, AppendResult as f, ForkSourceNotFound as g, CreateConflict as h, checkStreams as i, StreamsWriter as j, isProtocolError as k, streams_exports as l, AppendConflict as m, bind as n, group as o, CreateResult as p, ProducerId as q, bytes as r, json as s, Wildcard as t, route_exports as u, InvalidEpochSeq as v, StaleEpoch as w, NotSupported as x, InvalidForkRequest as y, StorageFault as z };