@streamsy/core 0.16.0 → 0.17.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.
@@ -1,9 +1,15 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.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";
2
+ import { I as isRetryableFault, M as InvalidStreamParams, a as compileSegments, c as templatesOverlap, f as checkWriteOwner, i as wireControlCodec, j as EncodeFault, k as StorageOwner, l as resolveParams, o as isCanonicalIdSegment, r as wireChangeCodec, s as isSingletonRoute, t as decodeMessage, u as throwInvalidStreamParams, y as newOwnerId } from "./read-message-DP1UpEFl.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"));
6
- const Offset = Schema.String.pipe(Schema.check(Schema.isPattern(/^\d{16}_\d{16}$/)), Schema.brand("Offset"));
6
+ /**
7
+ * A position in a stream, as any Durable Streams server issues it. Offsets are opaque: compare
8
+ * them, but do not parse them. The read sentinels `-1` and `now` are not offsets.
9
+ */
10
+ const Offset = Schema.String.pipe(Schema.check(Schema.isNonEmpty({ expected: "a non-empty offset" }), Schema.makeFilter((value) => value !== "-1" && value !== "now", { expected: "an offset, not the sentinel -1 or now" })), Schema.brand("Offset"));
11
+ /** The offset format that Streamsy storage issues. Every `StreamsyOffset` is an `Offset`. */
12
+ const StreamsyOffset = Offset.pipe(Schema.check(Schema.isPattern(/^\d{16}_\d{16}$/)), Schema.brand("StreamsyOffset"));
7
13
  const ProducerId = Schema.String.pipe(Schema.brand("ProducerId"));
8
14
  const StreamConfig = Schema.Struct({
9
15
  contentType: Schema.String,
@@ -16,7 +22,7 @@ const StreamLifecycle = Schema.Struct({
16
22
  closed: Schema.Boolean,
17
23
  closedAt: Schema.optionalKey(Schema.Finite),
18
24
  forkedFrom: Schema.optionalKey(StreamId),
19
- forkOffset: Schema.optionalKey(Offset),
25
+ forkOffset: Schema.optionalKey(StreamsyOffset),
20
26
  forkSubOffset: Schema.optionalKey(Schema.Finite),
21
27
  softDeleted: Schema.Boolean,
22
28
  expiresAtMs: Schema.optionalKey(Schema.Finite)
@@ -25,10 +31,10 @@ const StreamRecord = Schema.Struct({
25
31
  id: StreamId,
26
32
  config: StreamConfig,
27
33
  lifecycle: StreamLifecycle,
28
- currentOffset: Offset
34
+ currentOffset: StreamsyOffset
29
35
  });
30
36
  const StoredMessage = Schema.Struct({
31
- offset: Offset,
37
+ offset: StreamsyOffset,
32
38
  timestamp: Schema.Finite,
33
39
  data: Schema.Uint8Array
34
40
  });
@@ -37,18 +43,18 @@ const ProducerState = Schema.Struct({
37
43
  lastSeq: Schema.Finite
38
44
  });
39
45
  const MessageWindow = Schema.Struct({
40
- after: Schema.optionalKey(Offset),
41
- until: Schema.optionalKey(Offset),
46
+ after: Schema.optionalKey(StreamsyOffset),
47
+ until: Schema.optionalKey(StreamsyOffset),
42
48
  limit: Schema.optionalKey(Schema.Finite)
43
49
  });
44
50
  const ChangeSnapshot = Schema.Struct({
45
51
  present: Schema.Boolean,
46
- currentOffset: Offset,
52
+ currentOffset: StreamsyOffset,
47
53
  closed: Schema.Boolean,
48
54
  softDeleted: Schema.Boolean
49
55
  });
50
56
  const RecordPatch = Schema.Struct({
51
- currentOffset: Schema.optionalKey(Offset),
57
+ currentOffset: Schema.optionalKey(StreamsyOffset),
52
58
  config: Schema.optionalKey(Schema.Struct({
53
59
  ttlSeconds: Schema.optionalKey(Schema.Finite),
54
60
  expiresAt: Schema.optionalKey(Schema.String)
@@ -66,18 +72,20 @@ const RecordPatch = Schema.Struct({
66
72
  ])))
67
73
  });
68
74
  // src/offset/index.ts
69
- const ZERO_OFFSET = Offset.make(`${"0".repeat(16)}_${"0".repeat(16)}`);
70
- const isValid = (offset) => /^\d{16}_\d{16}$/.test(offset);
75
+ const ZERO_OFFSET = StreamsyOffset.make(`${"0".repeat(16)}_${"0".repeat(16)}`);
76
+ /** Whether `offset` is an opaque `Offset`: non-empty and not the read sentinels `-1` or `now`. */
77
+ const isValid = Schema.is(Offset);
78
+ /** Whether `offset` has the format that Streamsy storage issues. Servers check this. */
79
+ const isStreamsyOffset = Schema.is(StreamsyOffset);
80
+ /** Lexicographic order. The Durable Streams protocol guarantees it for offsets of one stream. */
71
81
  const compare = (a, b) => a === b ? 0 : a < b ? -1 : 1;
72
82
  const parse = (offset) => BigInt(offset.slice(0, 16));
73
83
  /** Fixed-width successor; bigint preserves all sixteen decimal digits. */
74
84
  function next(previous) {
75
85
  const value = parse(previous) + 1n;
76
86
  if (value > 9999999999999999n) throw new RangeError("Offset exhausted");
77
- return Offset.make(`${String(value).padStart(16, "0")}_${"0".repeat(16)}`);
87
+ return StreamsyOffset.make(`${String(value).padStart(16, "0")}_${"0".repeat(16)}`);
78
88
  }
79
- // src/storage/storage.ts
80
- var Storage = class extends Context.Service()("@streamsy/core/Storage") {};
81
89
  // src/protocol/tags.ts
82
90
  var StreamsReader = class extends Context.Service()("@streamsy/core/StreamsReader") {};
83
91
  var StreamsWriter = class extends Context.Service()("@streamsy/core/StreamsWriter") {};
@@ -95,7 +103,7 @@ var StreamGone = class extends Schema.TaggedError()("StreamGone", { id: StreamId
95
103
  };
96
104
  var StreamClosed = class extends Schema.TaggedError()("StreamClosed", {
97
105
  id: StreamId,
98
- offset: Schema.String
106
+ offset: Offset
99
107
  }) {
100
108
  get message() {
101
109
  return `Stream ${this.id} is closed at ${this.offset}`;
@@ -103,8 +111,8 @@ var StreamClosed = class extends Schema.TaggedError()("StreamClosed", {
103
111
  };
104
112
  var OffsetMismatch = class extends Schema.TaggedError()("OffsetMismatch", {
105
113
  id: StreamId,
106
- expected: Schema.String,
107
- actual: Schema.String
114
+ expected: Offset,
115
+ actual: Offset
108
116
  }) {
109
117
  get message() {
110
118
  return `Stream ${this.id} is at ${this.actual}, not at the expected ${this.expected}`;
@@ -214,56 +222,200 @@ const isProtocolError = (error) => Record.has(protocolErrorTags, error._tag);
214
222
  /** Constructors and matchers for the protocol results above. */
215
223
  const CreateResult = Data.taggedEnum();
216
224
  const AppendResult = Data.taggedEnum();
217
- // src/toolkit/address.ts
218
- var address_exports = /* @__PURE__ */ __exportAll({
219
- bytes: () => bytes$2,
225
+ // src/toolkit/durable-state.ts
226
+ var durable_state_exports = /* @__PURE__ */ __exportAll({
227
+ changeCodec: () => changeCodec,
228
+ changes: () => changes,
229
+ controlCodec: () => controlCodec,
220
230
  isChange: () => isChange,
221
231
  isControl: () => isControl,
222
232
  isUpsert: () => isUpsert,
223
- json: () => json$2,
233
+ materialize: () => materialize,
234
+ materialized: () => materialized,
235
+ remove: () => remove$1,
224
236
  reset: () => reset,
225
237
  snapshotEnd: () => snapshotEnd,
226
238
  snapshotStart: () => snapshotStart,
227
- state: () => state$2,
228
- stateChange: () => stateChange,
229
- stateControl: () => stateControl
239
+ upsert: () => upsert
230
240
  });
231
- /** The address constructors. Each class owns the `_tag` of one address kind. */
232
- const JsonAddress = Data.TaggedClass("Json");
233
- const BytesAddress = Data.TaggedClass("Bytes");
234
- function json$2(id, options) {
235
- return new JsonAddress({
236
- id: StreamId.make(id),
237
- contentType: "application/json",
238
- codec: Schema.fromJsonString(Schema.toCodecJson(options.schema))
239
- });
240
- }
241
241
  /**
242
242
  * A codec for the upsert and delete change events of one collection.
243
- * `state` composes one of these per collection. Omit optional headers instead
244
- * of setting them to `undefined`.
243
+ * `StreamAddress.state` composes one of these per collection. Omit optional
244
+ * headers instead of setting them to `undefined`.
245
245
  */
246
- function stateChange(options) {
247
- return changeCodec(Schema.Literal(options.type), options.schema);
246
+ function changeCodec(options) {
247
+ return wireChangeCodec(Schema.Literal(options.type), options.schema, options.type);
248
248
  }
249
249
  /** The codec for a State control message. It needs no services. */
250
- const stateControl = controlCodec;
250
+ const controlCodec = wireControlCodec;
251
251
  /** True for a control message. A change has `headers.operation` and no `headers.control`. */
252
252
  const isControl = (event) => Predicate.hasProperty(event.headers, "control");
253
253
  /** True for an upsert or delete change. */
254
254
  const isChange = (event) => !isControl(event);
255
255
  /** True for an upsert change, with its value available. */
256
256
  const isUpsert = (event) => isChange(event) && event.headers.operation === "upsert";
257
- const control = (name, options) => ({ headers: options.offset === void 0 ? { control: name } : {
257
+ const makeControl = (name, options) => ({ headers: options.offset === void 0 ? { control: name } : {
258
258
  control: name,
259
259
  offset: options.offset
260
260
  } });
261
261
  /** A `reset` control. A reader should clear its materialized state and apply what follows. */
262
- const reset = (options = {}) => control("reset", options);
262
+ const reset = (options = {}) => makeControl("reset", options);
263
263
  /** A `snapshot-start` control. The changes up to `snapshot-end` form a complete snapshot. */
264
- const snapshotStart = (options = {}) => control("snapshot-start", options);
264
+ const snapshotStart = (options = {}) => makeControl("snapshot-start", options);
265
265
  /** A `snapshot-end` control. It closes the snapshot that `snapshot-start` opened. */
266
- const snapshotEnd = (options = {}) => control("snapshot-end", options);
266
+ const snapshotEnd = (options = {}) => makeControl("snapshot-end", options);
267
+ const operations = Data.taggedEnum();
268
+ const isOperation = (entry) => Predicate.isTagged(entry, "Upsert") || Predicate.isTagged(entry, "Delete");
269
+ /** Describe an upsert into a collection. The key is read from the value. */
270
+ const upsert = (type, value, options = {}) => operations.Upsert({
271
+ type,
272
+ value,
273
+ ...options
274
+ });
275
+ /** Describe a delete from a collection by key. An `oldValue` is written as `old_value`. */
276
+ const remove$1 = (type, key, options = {}) => operations.Delete({
277
+ type,
278
+ key,
279
+ ...options
280
+ });
281
+ /**
282
+ * The key as a string. A null, undefined or empty key gives `""`, which the State codec rejects
283
+ * when the change is encoded, so `append` fails with `EncodeFault`.
284
+ */
285
+ const keyOf = (raw) => raw === null || raw === void 0 ? "" : String(raw);
286
+ /** Read the key field of a value. `Key` limits the field to strings and numbers. */
287
+ const readKey = (field, value) => String(value[field] ?? "");
288
+ function changes(source, entries, options = {}) {
289
+ const { offset } = options;
290
+ return Array.map(entries, (entry, index) => isOperation(entry) ? stampChange(source.collections, entry, offset, index) : stampControl(entry, offset));
291
+ }
292
+ const stampChange = (collections, entry, offset, index) => {
293
+ const collection = Record.has(collections, entry.type) ? collections[entry.type] : void 0;
294
+ if (collection === void 0) throw new TypeError(`Unknown state collection "${entry.type}"`);
295
+ const override = entry.headers ?? {};
296
+ const txid = override.txid ?? (offset === void 0 ? void 0 : `${offset}:${index}`);
297
+ const headers = {};
298
+ if (offset !== void 0) headers.offset = offset;
299
+ if (txid !== void 0) headers.txid = txid;
300
+ if (override.timestamp !== void 0) headers.timestamp = override.timestamp;
301
+ if (override.from !== void 0) headers.from = override.from;
302
+ if (Predicate.isTagged(entry, "Upsert")) {
303
+ const key = readKey(collection.key, entry.value);
304
+ return {
305
+ type: entry.type,
306
+ key,
307
+ value: entry.value,
308
+ headers: {
309
+ operation: "upsert",
310
+ ...headers
311
+ }
312
+ };
313
+ }
314
+ const key = keyOf(entry.key);
315
+ return entry.oldValue === void 0 ? {
316
+ type: entry.type,
317
+ key,
318
+ headers: {
319
+ operation: "delete",
320
+ ...headers
321
+ }
322
+ } : {
323
+ type: entry.type,
324
+ key,
325
+ old_value: entry.oldValue,
326
+ headers: {
327
+ operation: "delete",
328
+ ...headers
329
+ }
330
+ };
331
+ };
332
+ const stampControl = (entry, offset) => offset === void 0 || entry.headers.offset !== void 0 ? entry : { headers: {
333
+ control: entry.headers.control,
334
+ offset
335
+ } };
336
+ /** A row key that is unique across collections, for snapshot bookkeeping. */
337
+ const snapshotKey = (type, key) => `${type}\u0000${key}`;
338
+ /** Empty materialized state for the collections of `address`. */
339
+ function materialized(address) {
340
+ const rows = {};
341
+ for (const type of Record.keys(address.collections)) rows[type] = /* @__PURE__ */ new Map();
342
+ return {
343
+ rows,
344
+ snapshot: void 0
345
+ };
346
+ }
347
+ /**
348
+ * Fold State events into materialized state, with the State protocol rules:
349
+ *
350
+ * - `upsert` sets the row of its key, and `delete` removes it.
351
+ * - `reset` clears every collection.
352
+ * - `snapshot-end` removes each row that no change since `snapshot-start` named.
353
+ * A snapshot may span several calls.
354
+ *
355
+ * The input state is not changed. Only the collections that `events` touch are copied.
356
+ */
357
+ function materialize(state, events) {
358
+ const rows = /* @__PURE__ */ new Map();
359
+ let cleared = false;
360
+ let snapshot = state.snapshot === void 0 ? void 0 : new Set(state.snapshot);
361
+ const source = (type) => cleared ? void 0 : Record.has(state.rows, type) ? state.rows[type] : void 0;
362
+ const writable = (type) => {
363
+ const existing = rows.get(type);
364
+ if (existing !== void 0) return existing;
365
+ const copy = new Map(source(type));
366
+ rows.set(type, copy);
367
+ return copy;
368
+ };
369
+ for (const event of events) {
370
+ if (isControl(event)) {
371
+ const control = event.headers.control;
372
+ if (control === "reset") {
373
+ cleared = true;
374
+ rows.clear();
375
+ snapshot = void 0;
376
+ } else if (control === "snapshot-start") snapshot = /* @__PURE__ */ new Set();
377
+ else if (snapshot !== void 0) {
378
+ const seen = snapshot;
379
+ for (const type of Record.keys(state.rows)) {
380
+ const table = writable(type);
381
+ for (const key of Array.fromIterable(table.keys())) if (!seen.has(snapshotKey(type, key))) table.delete(key);
382
+ }
383
+ snapshot = void 0;
384
+ }
385
+ continue;
386
+ }
387
+ const table = writable(event.type);
388
+ if (isUpsert(event)) {
389
+ table.set(event.key, event.value);
390
+ snapshot?.add(snapshotKey(event.type, event.key));
391
+ } else {
392
+ table.delete(event.key);
393
+ snapshot?.delete(snapshotKey(event.type, event.key));
394
+ }
395
+ }
396
+ const next = {};
397
+ for (const type of Record.keys(state.rows)) next[type] = rows.get(type) ?? (cleared ? /* @__PURE__ */ new Map() : state.rows[type]);
398
+ return {
399
+ rows: next,
400
+ snapshot
401
+ };
402
+ }
403
+ // src/toolkit/address.ts
404
+ var address_exports = /* @__PURE__ */ __exportAll({
405
+ bytes: () => bytes$2,
406
+ json: () => json$2,
407
+ state: () => state$2
408
+ });
409
+ /** The address constructors. Each class owns the `_tag` of one address kind. */
410
+ const JsonAddress = Data.TaggedClass("Json");
411
+ const BytesAddress = Data.TaggedClass("Bytes");
412
+ function json$2(id, options) {
413
+ return new JsonAddress({
414
+ id: StreamId.make(id),
415
+ contentType: "application/json",
416
+ codec: Schema.fromJsonString(Schema.toCodecJson(options.schema))
417
+ });
418
+ }
267
419
  /**
268
420
  * A stream of Durable State events for several collections. Each record
269
421
  * key is the `type` on the wire; each entry gives the value schema and the value
@@ -272,11 +424,11 @@ const snapshotEnd = (options = {}) => control("snapshot-end", options);
272
424
  * Typed reads skip changes to undeclared collections unless `strict` is true.
273
425
  */
274
426
  function state$2(id, options) {
275
- const codecs = Array.map(Record.toEntries(options.collections), ([type, collection]) => stateChange({
427
+ const codecs = Array.map(Record.toEntries(options.collections), ([type, collection]) => changeCodec({
276
428
  schema: collection.schema,
277
429
  type
278
430
  }));
279
- const address = json$2(id, { schema: Schema.Union([...codecs, stateControl]) });
431
+ const address = json$2(id, { schema: Schema.Union([...codecs, controlCodec]) });
280
432
  const stateAddress = new JsonAddress({
281
433
  id: address.id,
282
434
  contentType: address.contentType,
@@ -340,10 +492,15 @@ function buildId(template, segments, codecs, params) {
340
492
  if (segment.kind === "literal") return segment.value;
341
493
  const codec = codecs[segment.name];
342
494
  const value = record[segment.name];
343
- if (codec === void 0 || value === void 0) throw new RangeError(`stream route ${template} has no value for parameter: ${segment.name}`);
495
+ const invalid = (message) => throwInvalidStreamParams(new InvalidStreamParams({
496
+ stream: template,
497
+ parameter: segment.name,
498
+ message
499
+ }));
500
+ if (codec === void 0 || value === void 0) return invalid(`stream route ${template} has no value for parameter: ${segment.name}`);
344
501
  const text = Option.getOrUndefined(Schema.encodeOption(codec)(value));
345
- if (text === void 0) throw new RangeError(`stream route ${template} parameter ${segment.name} cannot encode to an id segment`);
346
- if (!isCanonicalIdSegment(text)) throw new RangeError(`stream route ${template} parameter ${segment.name} is not a canonical id segment: ${text}`);
502
+ if (text === void 0) return invalid(`stream route ${template} parameter ${segment.name} cannot encode to an id segment`);
503
+ if (!isCanonicalIdSegment(text)) return invalid(`stream route ${template} parameter ${segment.name} is not a canonical id segment: ${text}`);
347
504
  return text;
348
505
  });
349
506
  return StreamId.make(Array.join(built, "/"));
@@ -356,9 +513,16 @@ function checkTemplateParams(template, names, codecs) {
356
513
  for (const name of names) if (codecs[name] === void 0) throw new RangeError(`stream route ${template} has no codec for parameter: ${name}`);
357
514
  for (const name of Record.keys(codecs)) if (!names.includes(name)) throw new RangeError(`stream route codec is absent from the template: ${name}`);
358
515
  }
516
+ /**
517
+ * The codec record of a route. A singleton template may omit `params`, which is then the
518
+ * empty record. `checkTemplateParams` still rejects a missing codec at run time.
519
+ */
520
+ function codecsOf(params) {
521
+ return params ?? {};
522
+ }
359
523
  function json$1(template, options) {
360
524
  const { segments, names } = compileSegments(template);
361
- const codecs = options.params;
525
+ const codecs = codecsOf(options.params);
362
526
  checkTemplateParams(template, names, codecs);
363
527
  return new Route({
364
528
  template,
@@ -370,7 +534,7 @@ function json$1(template, options) {
370
534
  }
371
535
  function state$1(template, options) {
372
536
  const { segments, names } = compileSegments(template);
373
- const codecs = options.params;
537
+ const codecs = codecsOf(options.params);
374
538
  checkTemplateParams(template, names, codecs);
375
539
  return new Route({
376
540
  template,
@@ -382,16 +546,16 @@ function state$1(template, options) {
382
546
  address: (params) => state$2(buildId(template, segments, codecs, params), options)
383
547
  });
384
548
  }
385
- function bytes$1(template, options) {
549
+ function bytes$1(template, ...[options]) {
386
550
  const { segments, names } = compileSegments(template);
387
- const codecs = options.params;
551
+ const codecs = codecsOf(options?.params);
388
552
  checkTemplateParams(template, names, codecs);
389
553
  return new Route({
390
554
  template,
391
555
  paramSchema: pathSchema(codecs),
392
556
  match: (id) => Option.isSome(matchTemplate(segments, codecs, id)),
393
557
  parse: (id) => matchTemplate(segments, codecs, id),
394
- address: (params) => bytes$2(buildId(template, segments, codecs, params), { contentType: options.contentType ?? "application/octet-stream" })
558
+ address: (params) => bytes$2(buildId(template, segments, codecs, params), { contentType: options?.contentType ?? "application/octet-stream" })
395
559
  });
396
560
  }
397
561
  /** Escape hatch for a grammar a template cannot express, such as a regex stream. */
@@ -405,6 +569,7 @@ function custom$1(options) {
405
569
  }
406
570
  // src/toolkit/streams.ts
407
571
  var streams_exports = /* @__PURE__ */ __exportAll({
572
+ Batch: () => Batch,
408
573
  append: () => append,
409
574
  collect: () => collect,
410
575
  create: () => create,
@@ -412,11 +577,17 @@ var streams_exports = /* @__PURE__ */ __exportAll({
412
577
  fold: () => fold,
413
578
  follow: () => follow,
414
579
  head: () => head,
415
- items: () => items,
416
580
  read: () => read,
417
- remove: () => remove,
418
- session: () => session
581
+ readNext: () => readNext,
582
+ remove: () => remove
419
583
  });
584
+ /** Operators for streams of batches. */
585
+ const Batch = {
586
+ /**
587
+ * Flatten a stream of batches into its items. The items carry no offset, so keep the batches
588
+ * when you need to resume from where you stopped.
589
+ */
590
+ items: (batches) => batches.pipe(Stream.flatMap((batch) => Stream.fromIterable(batch.items))) };
420
591
  const create = Effect.fn("Streams.create")(function* (address, options = {}) {
421
592
  return yield* (yield* StreamsWriter).create(address.id, {
422
593
  ...options,
@@ -460,7 +631,7 @@ const decode = Effect.fn("Streams.decode")(function* (address, result) {
460
631
  const items = yield* Effect.forEach(result.messages, (message, index) => decodeMessage(address, message, index));
461
632
  return {
462
633
  items: Array.getSomes(items),
463
- nextOffset: result.nextOffset,
634
+ offset: result.nextOffset,
464
635
  upToDate: result.upToDate,
465
636
  closed: result.closed
466
637
  };
@@ -473,7 +644,7 @@ function read(address, options = {}) {
473
644
  ...options,
474
645
  offset
475
646
  }));
476
- return [[batch], batch.upToDate ? Option.none() : Option.some(batch.nextOffset)];
647
+ return [[batch], batch.upToDate ? Option.none() : Option.some(batch.offset)];
477
648
  }));
478
649
  }));
479
650
  }
@@ -484,13 +655,13 @@ function read(address, options = {}) {
484
655
  const fold = Effect.fn("Streams.fold")(function* (address, initial, f, options = {}) {
485
656
  return yield* read(address, options).pipe(Stream.runFold(() => ({
486
657
  state: initial(),
487
- offset: options.offset ?? ZERO_OFFSET
658
+ offset: ZERO_OFFSET
488
659
  }), (folded, batch) => {
489
660
  let state = folded.state;
490
661
  for (const item of batch.items) state = f(state, item);
491
662
  return {
492
663
  state,
493
- offset: batch.nextOffset
664
+ offset: batch.offset
494
665
  };
495
666
  }));
496
667
  });
@@ -591,7 +762,7 @@ function follow(address, options = {}) {
591
762
  const [result, cursor] = yield* retrying(state.live ? live(state) : catchUp(state));
592
763
  const batch = yield* decode(address, result);
593
764
  const next = {
594
- offset: batch.nextOffset,
765
+ offset: batch.offset,
595
766
  live: batch.upToDate,
596
767
  cursor
597
768
  };
@@ -599,9 +770,17 @@ function follow(address, options = {}) {
599
770
  }));
600
771
  }));
601
772
  }
602
- const items = (batches) => batches.pipe(Stream.flatMap((batch) => Stream.fromIterable(batch.items)));
603
- const session = Effect.fn("Streams.session")(function* (address, options) {
604
- return yield* (yield* StreamsReader).readNext(address.id, options);
773
+ /**
774
+ * One live read: the items after `offset` if there are any, or else wait once for some. It
775
+ * decodes like `follow`, so a State reader skips changes to collections it does not declare.
776
+ */
777
+ const readNext = Effect.fn("Streams.readNext")(function* (address, options) {
778
+ const result = yield* (yield* StreamsReader).readNext(address.id, options);
779
+ return {
780
+ ...yield* decode(address, result),
781
+ cursor: result.cursor,
782
+ timedOut: result.timedOut
783
+ };
605
784
  });
606
785
  const head = Effect.fn("Streams.head")(function* (address) {
607
786
  return yield* (yield* StreamsReader).head(address.id);
@@ -624,11 +803,10 @@ function checkNoOverlap(routes) {
624
803
  });
625
804
  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}`);
626
805
  }
627
- /** Build a stream service over one protocol graph's wires, with the ownership guard on writes. */
628
- function wireApi(route, services) {
629
- const storage = storageOf(services.writer);
630
- const owner = storage === void 0 ? services.writer : ownerOf(storage);
631
- const write = (id, run) => checkWriteOwner(owner, id, storage !== void 0).pipe(Effect.andThen(Effect.suspend(run)));
806
+ /** Guard a protocol graph's wires for one route, with the ownership guard on writes. */
807
+ function wireRoute(route, services) {
808
+ const { owner, knownOwner } = services;
809
+ const write = (id, run) => checkWriteOwner(owner, id, knownOwner).pipe(Effect.andThen(Effect.suspend(run)));
632
810
  const own = (id, run) => Effect.suspend(() => route.match(id) ? run() : Effect.die(/* @__PURE__ */ new RangeError(`${id} is outside stream ${route.template}`)));
633
811
  const wire = {
634
812
  head: (id) => own(id, () => services.reader.head(id)),
@@ -645,25 +823,49 @@ function wireApi(route, services) {
645
823
  append: (id, options) => write(id, () => own(id, () => services.writer.append(id, options))),
646
824
  remove: (id) => write(id, () => own(id, () => services.writer.remove(id)))
647
825
  };
648
- const context = Context.make(StreamsReader, wire).pipe(Context.add(StreamsWriter, wire));
649
826
  return {
650
827
  owner,
651
- route,
652
828
  wire,
653
- create: (params, options) => create(route.address(params), options).pipe(Effect.provide(context)),
654
- append: (params, items, options) => append(route.address(params), items, options).pipe(Effect.provide(context)),
655
- read: (params, options) => read(route.address(params), options).pipe(Stream.provideContext(context)),
656
- fold: (params, initial, f, options) => fold(route.address(params), initial, f, options).pipe(Effect.provide(context)),
657
- collect: (params, options) => collect(route.address(params), options).pipe(Effect.provide(context)),
658
- decide: (params, spec) => decide(route.address(params), spec).pipe(Effect.provide(context)),
659
- follow: (params, options) => follow(route.address(params), options).pipe(Stream.provideContext(context)),
660
- session: (params, options) => wire.readNext(route.address(params).id, options),
661
- head: (params) => wire.head(route.address(params).id),
662
- remove: (params) => wire.remove(route.address(params).id),
663
- fork: (params, source, options) => wire.fork(route.address(params).id, route.address(source).id, {
664
- ...options,
665
- contentType: route.address(params).contentType
666
- })
829
+ context: Context.make(StreamsReader, wire).pipe(Context.add(StreamsWriter, wire))
830
+ };
831
+ }
832
+ /** Build the handle of one stream. `address` fails with `E` when its params cannot form an id. */
833
+ function wireHandle(wired, address) {
834
+ const { owner, wire, context } = wired;
835
+ const run = (f) => address.pipe(Effect.flatMap(f), Effect.provide(context));
836
+ const stream = (f) => Stream.unwrap(address.pipe(Effect.map(f))).pipe(Stream.provideContext(context));
837
+ return {
838
+ owner,
839
+ wire,
840
+ address,
841
+ create: (options) => run((bound) => create(bound, options)),
842
+ append: (items, options) => run((bound) => append(bound, items, options)),
843
+ read: (options) => stream((bound) => read(bound, options)),
844
+ fold: (initial, f, options) => run((bound) => fold(bound, initial, f, options)),
845
+ collect: (options) => run((bound) => collect(bound, options)),
846
+ decide: (spec) => run((bound) => decide(bound, spec)),
847
+ follow: (options) => stream((bound) => follow(bound, options)),
848
+ readNext: (options) => run((bound) => readNext(bound, options)),
849
+ head: () => address.pipe(Effect.flatMap(({ id }) => wire.head(id))),
850
+ remove: () => address.pipe(Effect.flatMap(({ id }) => wire.remove(id)))
851
+ };
852
+ }
853
+ /** Build the service of a stream with params: `at(params)` gives the handle of one stream. */
854
+ function wireFamily(route, wired, bindAddress) {
855
+ const { owner, wire } = wired;
856
+ return {
857
+ owner,
858
+ wire,
859
+ at: (params) => {
860
+ const address = resolveParams(() => bindAddress(params));
861
+ return {
862
+ ...wireHandle(wired, address),
863
+ fork: (source, options) => Effect.all([address, resolveParams(() => route.address(source))]).pipe(Effect.flatMap(([target, from]) => wire.fork(target.id, from.id, {
864
+ ...options,
865
+ contentType: target.contentType
866
+ })))
867
+ };
868
+ }
667
869
  };
668
870
  }
669
871
  /**
@@ -676,13 +878,29 @@ function define() {
676
878
  return (name, route) => {
677
879
  const key = `@streamsy/core/Stream/${name}`;
678
880
  const service = Context.Service()(key);
881
+ const at = (params) => {
882
+ return Object.assign(route.address(params), { stream: service });
883
+ };
884
+ const singleton = isSingletonRoute(route) ? Option.some(at({})) : Option.none();
885
+ const make = (services) => {
886
+ const wired = wireRoute(route, services);
887
+ return Option.match(singleton, {
888
+ onNone: () => wireFamily(route, wired, at),
889
+ onSome: (address) => wireHandle(wired, Effect.succeed(address))
890
+ });
891
+ };
679
892
  const declared = Object.defineProperty(service, metadataKey, { value: {
680
893
  route,
681
- make: (services) => wireApi(route, services)
682
- } });
683
- return Object.assign(declared, route, { at: (params) => {
684
- return Object.assign(route.address(params), { stream: service });
894
+ make
685
895
  } });
896
+ const statics = Option.match(singleton, {
897
+ onNone: () => ({
898
+ at,
899
+ resolve: (params) => resolveParams(() => at(params))
900
+ }),
901
+ onSome: (address) => ({ singleton: address })
902
+ });
903
+ return Object.assign(declared, route, statics);
686
904
  };
687
905
  }
688
906
  const json = () => (name, ...args) => define()(name, json$1(...args));
@@ -714,19 +932,28 @@ function checkStreams(keys) {
714
932
  function bind(source, streams) {
715
933
  const keys = streams.streams;
716
934
  checkStreams(keys);
717
- const bindContext = (wires, storage) => {
718
- if (storage !== void 0 && (storageOf(wires.reader) !== storage || storageOf(wires.writer) !== storage)) throw new RangeError("The exposed Storage does not own the protocol wires");
935
+ const bindContext = (wires) => {
719
936
  let context = Context.empty();
720
937
  for (const key of keys) context = Context.add(context, key, declaration(key).make(wires));
721
938
  return context;
722
939
  };
723
940
  return source.pipe(Layer.flatMap((context) => Layer.syncContext(() => bindContext({
724
941
  reader: Context.get(context, StreamsReader),
725
- writer: Context.get(context, StreamsWriter)
726
- }, Option.getOrUndefined(Context.getOption(context, Storage))))));
942
+ writer: Context.get(context, StreamsWriter),
943
+ ...Option.match(Context.getOption(context, StorageOwner), {
944
+ onNone: () => ({
945
+ owner: newOwnerId("remote"),
946
+ knownOwner: false
947
+ }),
948
+ onSome: (owner) => ({
949
+ owner: owner.id,
950
+ knownOwner: true
951
+ })
952
+ })
953
+ }))));
727
954
  }
728
955
  function group(...keys) {
729
956
  checkStreams(keys);
730
957
  return Object.freeze({ streams: Object.freeze(keys) });
731
958
  }
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 };
959
+ export { StreamLifecycle as $, ProducerGap as A, compare as B, InvalidAppendRequest as C, InvalidReadRequest as D, InvalidForkRequest as E, StreamNotFound as F, MessageWindow as G, isValid as H, isProtocolError as I, ProducerState as J, Offset as K, StreamsReader as L, StreamBusy as M, StreamClosed as N, NotSupported as O, StreamGone as P, StreamId as Q, StreamsWriter as R, ForkSourceNotFound as S, InvalidEpochSeq as T, next as U, isStreamsyOffset as V, ChangeSnapshot as W, StoredMessage as X, RecordPatch as Y, StreamConfig as Z, isUpsert as _, custom as a, AppendConflict as b, state as c, route_exports as d, StreamRecord as et, address_exports as f, isControl as g, durable_state_exports as h, checkStreams as i, StaleEpoch as j, OffsetMismatch as k, Batch as l, controlCodec as m, bind as n, group as o, changeCodec as p, ProducerId as q, bytes as r, json as s, Wildcard as t, StreamsyOffset as tt, streams_exports as u, AppendResult as v, InvalidCreateRequest as w, CreateConflict as x, CreateResult as y, ZERO_OFFSET as z };