@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.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { $ as CreateError, At as ProducerState, Bt as StreamsFault, C as OperationResults, Ct as ReadNextOptions, Dt as MessageWindow, E as StorageCapabilities, Et as ChangeSnapshot, Ft as StreamLifecycle, G as ReadNextResult, H as CreateResult, Ht as isRetryableFault, I as address_d_exports, It as StreamRecord, J as AppendConflict, K as ReadResult, Lt as DecodeFault, Mt as StoredMessage, Nt as StreamConfig, Ot as Offset, Pt as StreamId, Q as CreateConflictReason, Rt as EncodeFault, S as OperationResult, St as ProducerOptions, T as ProducerPrecondition, Tt as CreateOptions, U as HeadResult, Ut as isStreamsFault, V as AppendResult, Vt as TransportFault, W as ReadMessage, X as AppendErrorFor, Y as AppendError, Z as CreateConflict, _ as Mutation, _t as StreamGone, at as InvalidForkRequest, b as Mutations, bt as AppendCallOptions, ct as OffsetMismatch, dt as ReadError, et as ForkSourceNotFound, ft as ReadNextError, g as StorageShape, gt as StreamClosed, h as Storage, ht as StreamBusy, it as InvalidEpochSeq, jt as RecordPatch, kt as ProducerId, lt as ProducerGap, m as CommitBoundaryApi, mt as StaleEpoch, nt as InvalidAppendRequest, ot as InvalidReadRequest, p as CommitBoundary, pt as RemoveError, q as AppendBaseError, rt as InvalidCreateRequest, st as NotSupported, tt as HeadError, ut as ProtocolError, v as MutationApplied, vt as StreamNotFound, w as Operations, wt as ReadOptions, x as Operation, xt as AppendOptions, y as MutationRejected, yt as isProtocolError, zt as StorageFault } from "./projection-marks-DcO_5VNd.js";
2
- import { A as Batch, B as RemoveFailure, F as Decision, G as streams_d_exports, H as streamsy_d_exports, I as Folded, L as FollowFailure, M as CreateFailure, N as DecideSpec, P as Decided, R as HeadFailure, U as producer_d_exports, W as durable_state_d_exports, X as compare, Y as ZERO_OFFSET, j as Collected, k as AppendFailure, t as index_d_exports, z as ReadFailure } from "./index-D-n48qXe.js";
3
- export { AppendBaseError, type AppendCallOptions, AppendConflict, AppendError, AppendErrorFor, type AppendFailure, type AppendOptions, AppendResult, type Batch, ChangeSnapshot, type Collected, CommitBoundary, type CommitBoundaryApi, CreateConflict, CreateConflictReason, CreateError, type CreateFailure, type CreateOptions, CreateResult, type DecideSpec, type Decided, type Decision, DecodeFault, durable_state_d_exports as DurableState, EncodeFault, type Folded, type FollowFailure, ForkSourceNotFound, HeadError, type HeadFailure, type HeadResult, index_d_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_d_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_d_exports as Producer, ProducerGap, ProducerId, type ProducerOptions, ProducerPrecondition, ProducerState, ProtocolError, ReadError, type ReadFailure, type ReadMessage, ReadNextError, type ReadNextOptions, type ReadNextResult, type ReadOptions, type ReadResult, RecordPatch, RemoveError, type RemoveFailure, StaleEpoch, Storage, StorageCapabilities, StorageFault, type StorageShape, StoredMessage, address_d_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_d_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
1
+ import { $ as StreamsFault, A as ReadResult, B as ProducerId, C as StorageOwnerApi, D as HeadResult, E as CreateResult, F as ReadOptions, G as StreamId, H as RecordPatch, I as StartOffset, J as StreamsyOffset, K as StreamLifecycle, L as ChangeSnapshot, M as AppendOptions, N as ProducerOptions, O as ReadMessage, P as ReadNextOptions, Q as StorageFault, R as MessageWindow, S as StorageOwner, T as AppendResult, U as StoredMessage, V as ProducerState, W as StreamConfig, X as EncodeFault, Y as DecodeFault, Z as InvalidStreamParams, a as Mutations, b as durable_state_d_exports, c as OperationResults, et as TransportFault, i as MutationRejected, j as AppendCallOptions, k as ReadNextResult, l as Operations, n as Mutation, nt as isStreamsFault, o as Operation, p as address_d_exports, q as StreamRecord, r as MutationApplied, s as OperationResult, t as StorageShape, tt as isRetryableFault, u as ProducerPrecondition, w as StorageCapabilities, x as OwnerId, z as Offset } from "./storage-xTb82JxJ.js";
2
+ import { A as Batch, At as StreamNotFound, B as ReadFailure, Ct as ReadError, Dt as StreamBusy, Et as StaleEpoch, F as Decision, G as streams_d_exports, I as Folded, L as FollowFailure, M as CreateFailure, Mt as CreateOptions, N as DecideSpec, Ot as StreamClosed, P as Decided, R as HeadFailure, St as ProtocolError, Tt as RemoveError, U as streamsy_d_exports, V as RemoveFailure, W as producer_d_exports, X as compare, Y as ZERO_OFFSET, _t as InvalidForkRequest, at as AppendBaseError, bt as OffsetMismatch, ct as AppendErrorFor, dt as CreateError, ft as ForkSourceNotFound, gt as InvalidEpochSeq, ht as InvalidCreateRequest, j as Collected, jt as isProtocolError, k as AppendFailure, kt as StreamGone, lt as CreateConflict, mt as InvalidAppendRequest, ot as AppendConflict, pt as HeadError, st as AppendError, t as index_d_exports, ut as CreateConflictReason, vt as InvalidReadRequest, wt as ReadNextError, xt as ProducerGap, yt as NotSupported, z as LiveBatch } from "./index-DIx4D2t0.js";
3
+ export { AppendBaseError, type AppendCallOptions, AppendConflict, AppendError, AppendErrorFor, type AppendFailure, type AppendOptions, AppendResult, Batch, ChangeSnapshot, type Collected, CreateConflict, CreateConflictReason, CreateError, type CreateFailure, type CreateOptions, CreateResult, type DecideSpec, type Decided, type Decision, DecodeFault, durable_state_d_exports as DurableState, EncodeFault, type Folded, type FollowFailure, ForkSourceNotFound, HeadError, type HeadFailure, type HeadResult, index_d_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, InvalidStreamParams, type LiveBatch, streams_d_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, type OwnerId, producer_d_exports as Producer, ProducerGap, ProducerId, type ProducerOptions, ProducerPrecondition, ProducerState, ProtocolError, ReadError, type ReadFailure, type ReadMessage, ReadNextError, type ReadNextOptions, type ReadNextResult, type ReadOptions, type ReadResult, RecordPatch, RemoveError, type RemoveFailure, StaleEpoch, type StartOffset, StorageCapabilities, StorageFault, StorageOwner, type StorageOwnerApi, type StorageShape, StoredMessage, address_d_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_d_exports as Streamsy, StreamsyOffset, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
package/dist/index.js CHANGED
@@ -1,10 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { A as StreamBusy, C as InvalidEpochSeq, D as OffsetMismatch, E as NotSupported, G as ProducerId, H as ChangeSnapshot, J as StoredMessage, K as ProducerState, L as Storage, M as StreamGone, N as StreamNotFound, O as ProducerGap, P as isProtocolError, Q as StreamRecord, R as ZERO_OFFSET, S as InvalidCreateRequest, T as InvalidReadRequest, U as MessageWindow, W as Offset, X as StreamId, Y as StreamConfig, Z as StreamLifecycle, _ as CreateResult, a as custom, b as ForkSourceNotFound, c as state, d as address_exports, f as isControl, g as AppendResult, h as stateControl, j as StreamClosed, k as StaleEpoch, m as stateChange, n as bind, o as group, p as isUpsert, q as RecordPatch, r as bytes, s as json, t as Wildcard, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict, z as compare } from "./streamsy-IBFULoEr.js";
3
- import { _ as StorageFault, b as isRetryableFault, g as EncodeFault, h as DecodeFault, v as StreamsFault, x as isStreamsFault, y as TransportFault } from "./read-message-CGHhOCMc.js";
4
- import { p as CommitBoundary } from "./boundary-BTrhL8De.js";
5
- import { a as MutationRejected, c as OperationResult, d as ProducerPrecondition, i as MutationApplied, l as OperationResults, o as Mutations, r as Mutation, s as Operation, t as layer$1, u as Operations } from "./layer-pomDIajD.js";
6
- import { t as layer$2 } from "./layer-C-8GAL_W.js";
7
- import { t as http_exports } from "./http-BNYNMGuk.js";
2
+ import { $ as StreamLifecycle, A as ProducerGap, B as compare, C as InvalidAppendRequest, D as InvalidReadRequest, E as InvalidForkRequest, F as StreamNotFound, G as MessageWindow, H as isValid, I as isProtocolError, J as ProducerState, K as Offset, M as StreamBusy, N as StreamClosed, O as NotSupported, P as StreamGone, Q as StreamId, S as ForkSourceNotFound, T as InvalidEpochSeq, W as ChangeSnapshot, X as StoredMessage, Y as RecordPatch, Z as StreamConfig, _ as isUpsert, a as custom, b as AppendConflict, c as state, et as StreamRecord, f as address_exports, g as isControl, h as durable_state_exports, j as StaleEpoch, k as OffsetMismatch, l as Batch, m as controlCodec, n as bind, o as group, p as changeCodec, q as ProducerId, r as bytes, s as json, t as Wildcard, tt as StreamsyOffset, v as AppendResult, w as InvalidCreateRequest, x as CreateConflict, y as CreateResult, z as ZERO_OFFSET } from "./streamsy-DiAjZWlT.js";
3
+ import { A as DecodeFault, F as TransportFault, I as isRetryableFault, L as isStreamsFault, M as InvalidStreamParams, N as StorageFault, P as StreamsFault, j as EncodeFault, k as StorageOwner } from "./read-message-DP1UpEFl.js";
4
+ import { a as MutationRejected, c as OperationResult, d as ProducerPrecondition, i as MutationApplied, l as OperationResults, o as Mutations, r as Mutation, s as Operation, t as layer$1, u as Operations } from "./layer-DTOhxWkw.js";
5
+ import { t as layer$2 } from "./layer-Dv_LBCgD.js";
6
+ import { t as http_exports } from "./http-aCMEaxro.js";
8
7
  import { Array, Data, Effect, Layer, Option, Predicate, Record, Schema, Stream } from "effect";
9
8
  // src/storage/capabilities.ts
10
9
  const StorageCapabilities = Schema.Struct({
@@ -29,150 +28,6 @@ function layer(group, options = {}) {
29
28
  const protocol = layer$1(options).pipe(Layer.provideMerge(storage));
30
29
  return bind(protocol, group).pipe(Layer.provideMerge(storage));
31
30
  }
32
- // src/toolkit/durable-state.ts
33
- var durable_state_exports = /* @__PURE__ */ __exportAll({
34
- changes: () => changes,
35
- materialize: () => materialize,
36
- materialized: () => materialized,
37
- remove: () => remove,
38
- upsert: () => upsert
39
- });
40
- const operations = Data.taggedEnum();
41
- const isOperation = (entry) => Predicate.isTagged(entry, "Upsert") || Predicate.isTagged(entry, "Delete");
42
- /** Describe an upsert into a collection. The key is read from the value. */
43
- const upsert = (type, value, options = {}) => operations.Upsert({
44
- type,
45
- value,
46
- ...options
47
- });
48
- /** Describe a delete from a collection by key. An `oldValue` is written as `old_value`. */
49
- const remove = (type, key, options = {}) => operations.Delete({
50
- type,
51
- key,
52
- ...options
53
- });
54
- /** Reject keys that Durable State clients cannot address. */
55
- const checkKey = (type, source, raw) => {
56
- if (raw === null || raw === void 0 || raw === "") throw new TypeError(`Invalid state key for type "${type}": ${source} must not be null, undefined, or empty`);
57
- return String(raw);
58
- };
59
- /** Read the key field of a value. `StateKey` limits the field to strings and numbers. */
60
- const readKey = (type, field, value) => checkKey(type, `field "${String(field)}"`, String(value[field] ?? ""));
61
- function changes(address, options, entries) {
62
- const { offset } = options;
63
- return Array.map(entries, (entry, index) => isOperation(entry) ? stampChange(address.collections, entry, offset, index) : stampControl(entry, offset));
64
- }
65
- const stampChange = (collections, entry, offset, index) => {
66
- const collection = Record.has(collections, entry.type) ? collections[entry.type] : void 0;
67
- if (collection === void 0) throw new TypeError(`Unknown state collection "${entry.type}"`);
68
- const override = entry.headers ?? {};
69
- const txid = override.txid ?? (offset === void 0 ? void 0 : `${offset}:${index}`);
70
- const headers = {};
71
- if (offset !== void 0) headers.offset = offset;
72
- if (txid !== void 0) headers.txid = txid;
73
- if (override.timestamp !== void 0) headers.timestamp = override.timestamp;
74
- if (override.from !== void 0) headers.from = override.from;
75
- if (Predicate.isTagged(entry, "Upsert")) {
76
- const key = readKey(entry.type, collection.key, entry.value);
77
- return {
78
- type: entry.type,
79
- key,
80
- value: entry.value,
81
- headers: {
82
- operation: "upsert",
83
- ...headers
84
- }
85
- };
86
- }
87
- const key = checkKey(entry.type, "key", entry.key);
88
- return entry.oldValue === void 0 ? {
89
- type: entry.type,
90
- key,
91
- headers: {
92
- operation: "delete",
93
- ...headers
94
- }
95
- } : {
96
- type: entry.type,
97
- key,
98
- old_value: entry.oldValue,
99
- headers: {
100
- operation: "delete",
101
- ...headers
102
- }
103
- };
104
- };
105
- const stampControl = (entry, offset) => offset === void 0 || entry.headers.offset !== void 0 ? entry : { headers: {
106
- control: entry.headers.control,
107
- offset
108
- } };
109
- /** A row key that is unique across collections, for snapshot bookkeeping. */
110
- const snapshotKey = (type, key) => `${type}\u0000${key}`;
111
- /** Empty materialized state for the collections of `address`. */
112
- function materialized(address) {
113
- const rows = {};
114
- for (const type of Record.keys(address.collections)) rows[type] = /* @__PURE__ */ new Map();
115
- return {
116
- rows,
117
- snapshot: void 0
118
- };
119
- }
120
- /**
121
- * Fold State events into materialized state, with the State protocol rules:
122
- *
123
- * - `upsert` sets the row of its key, and `delete` removes it.
124
- * - `reset` clears every collection.
125
- * - `snapshot-end` removes each row that no change since `snapshot-start` named.
126
- * A snapshot may span several calls.
127
- *
128
- * The input state is not changed. Only the collections that `events` touch are copied.
129
- */
130
- function materialize(state, events) {
131
- const rows = /* @__PURE__ */ new Map();
132
- let cleared = false;
133
- let snapshot = state.snapshot === void 0 ? void 0 : new Set(state.snapshot);
134
- const source = (type) => cleared ? void 0 : Record.has(state.rows, type) ? state.rows[type] : void 0;
135
- const writable = (type) => {
136
- const existing = rows.get(type);
137
- if (existing !== void 0) return existing;
138
- const copy = new Map(source(type));
139
- rows.set(type, copy);
140
- return copy;
141
- };
142
- for (const event of events) {
143
- if (isControl(event)) {
144
- const control = event.headers.control;
145
- if (control === "reset") {
146
- cleared = true;
147
- rows.clear();
148
- snapshot = void 0;
149
- } else if (control === "snapshot-start") snapshot = /* @__PURE__ */ new Set();
150
- else if (snapshot !== void 0) {
151
- const seen = snapshot;
152
- for (const type of Record.keys(state.rows)) {
153
- const table = writable(type);
154
- for (const key of Array.fromIterable(table.keys())) if (!seen.has(snapshotKey(type, key))) table.delete(key);
155
- }
156
- snapshot = void 0;
157
- }
158
- continue;
159
- }
160
- const table = writable(event.type);
161
- if (isUpsert(event)) {
162
- table.set(event.key, event.value);
163
- snapshot?.add(snapshotKey(event.type, event.key));
164
- } else {
165
- table.delete(event.key);
166
- snapshot?.delete(snapshotKey(event.type, event.key));
167
- }
168
- }
169
- const next = {};
170
- for (const type of Record.keys(state.rows)) next[type] = rows.get(type) ?? (cleared ? /* @__PURE__ */ new Map() : state.rows[type]);
171
- return {
172
- rows: next,
173
- snapshot
174
- };
175
- }
176
31
  // src/toolkit/producer.ts
177
32
  var producer_exports = /* @__PURE__ */ __exportAll({ next: () => next });
178
33
  /** Advance only after the caller has acknowledged appended or duplicate. Persist this tuple at the owning edge. */
@@ -229,10 +84,10 @@ const frontierStreamCollections = { stream: frontier };
229
84
  * The codec of one frontier stream message: a `stream` change or a State control.
230
85
  * A client that decodes raw JSON pages uses it in place of a typed service.
231
86
  */
232
- const FrontierMessage = Schema.Union([stateChange({
87
+ const FrontierMessage = Schema.Union([changeCodec({
233
88
  type: "stream",
234
89
  schema: Frontier
235
- }), stateControl]);
90
+ }), controlCodec]);
236
91
  /**
237
92
  * Declare a frontier stream: a State stream of `Frontier` rows at a template.
238
93
  *
@@ -242,11 +97,13 @@ const FrontierMessage = Schema.Union([stateChange({
242
97
  * }) {}
243
98
  * ```
244
99
  *
100
+ * A template without `:name` declares a singleton frontier stream and may omit `params`,
101
+ * and so the whole options argument: `Streamsy.frontierStream<Wake>()("App/Wake", "wake")`.
245
102
  * The declaration names no sources. A `Projection.frontier` binding links one
246
103
  * source stream to one frontier stream, with params of its own.
247
104
  */
248
- const frontierStream = () => (name, template, options) => state()(name, template, {
249
- params: options.params,
105
+ const frontierStream = () => (name, template, ...[options]) => state()(name, template, {
106
+ ...options,
250
107
  collections: frontierStreamCollections
251
108
  });
252
109
  /** Constructors and matchers for `FrontierItem`. */
@@ -307,12 +164,13 @@ function frontierActions(events, options) {
307
164
  const row = event.value;
308
165
  const removed = prior?.removed ?? false;
309
166
  const base = removed || reset ? "-1" : cursors.get(stream) ?? "-1";
310
- const dirty = compare(row.offset, base) > 0 || row.closed === true;
167
+ const offset = isValid(row.offset) ? row.offset : void 0;
168
+ const dirty = offset !== void 0 && (compare(offset, base) > 0 || row.closed === true);
311
169
  pending.set(stream, {
312
170
  removed,
313
171
  dirty: dirty ? Option.some({
314
172
  from: base,
315
- offset: row.offset,
173
+ offset,
316
174
  closed: row.closed === true
317
175
  }) : Option.none()
318
176
  });
@@ -331,9 +189,9 @@ function frontierActions(events, options) {
331
189
  * last; a stop between the two reads the same rows again, and the offset check
332
190
  * skips the streams that were already read.
333
191
  */
334
- function followFrontier(declaration, params, options) {
192
+ function followFrontier(stream, options) {
335
193
  const { from, cursors, ...follow } = options;
336
- return Stream.unwrap(Effect.map(Effect.service(declaration), (service) => service.follow(params, {
194
+ return stream.follow({
337
195
  ...follow,
338
196
  offset: from
339
197
  }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
@@ -343,12 +201,20 @@ function followFrontier(declaration, params, options) {
343
201
  });
344
202
  const out = {
345
203
  items: next.items,
346
- offset: batch.nextOffset,
204
+ offset: batch.offset,
347
205
  upToDate: batch.upToDate
348
206
  };
349
207
  return [next.snapshot, [out]];
350
- }))));
208
+ }));
351
209
  }
210
+ /**
211
+ * The collections of a State address. The handle types its address as a plain stream address,
212
+ * so the collections are read from the value. A stream that is not State has none.
213
+ */
214
+ const collectionsOf = (address) => {
215
+ if (!Predicate.hasProperty(address, "collections") || !Predicate.isObject(address.collections)) return {};
216
+ return address.collections;
217
+ };
352
218
  /** The name of the collection declared with `Streamsy.frontier`, found by schema identity. */
353
219
  const frontierCollection = (collections) => {
354
220
  const names = Array.filter(Record.keys(collections), (name) => collections[name]?.schema === Frontier && collections[name]?.key === "stream");
@@ -357,33 +223,35 @@ const frontierCollection = (collections) => {
357
223
  return name;
358
224
  };
359
225
  /**
360
- * Wait until the frontier row for `stream` reaches `offset`. `declaration` is a
361
- * frontier stream or any State class with one `Streamsy.frontier` collection; the
362
- * other collections are read and skipped. Works with local and remote
363
- * services. Callers choose their own timeout. Removed source ids must not be
364
- * reused; a new generation needs a new stream or a State reset. Without
226
+ * Wait until the frontier row for `stream` reaches `offset`. `stream` is the handle of a
227
+ * frontier stream or of any State stream with one `Streamsy.frontier` collection; the
228
+ * other collections are read and skipped. Another stream dies with a `RangeError`. Works
229
+ * with local and remote services. Callers choose their own timeout. Removed source ids
230
+ * must not be reused; a new generation needs a new stream or a State reset. Without
365
231
  * `options.from`, each call reads the history from the start.
366
232
  */
367
- const awaitFrontier = (declaration, params, target, options = {}) => {
368
- const type = frontierCollection(declaration.collections);
369
- const stream = StreamId.make(target.stream);
233
+ const awaitFrontier = (stream, target, options = {}) => {
234
+ const source = StreamId.make(target.stream);
370
235
  const { from, ...follow } = options;
371
- return Stream.unwrap(Effect.map(Effect.service(declaration), (service) => service.follow(params, {
372
- ...follow,
373
- offset: from
374
- }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
375
- const next = frontierActions(Array.filter(batch.items, (event) => isControl(event) || event.type === type), {
376
- cursors: /* @__PURE__ */ new Map(),
377
- snapshot
378
- });
379
- return [next.snapshot, [{
380
- items: next.items,
381
- upToDate: batch.upToDate
382
- }]];
383
- })))).pipe(Stream.mapAccum(() => Option.none(), (observed, batch) => {
236
+ return Stream.unwrap(Effect.map(stream.address, (address) => {
237
+ const type = frontierCollection(collectionsOf(address));
238
+ return stream.follow({
239
+ ...follow,
240
+ offset: from
241
+ }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
242
+ const next = frontierActions(Array.filter(batch.items, (event) => isControl(event) || event.type === type), {
243
+ cursors: /* @__PURE__ */ new Map(),
244
+ snapshot
245
+ });
246
+ return [next.snapshot, [{
247
+ items: next.items,
248
+ upToDate: batch.upToDate
249
+ }]];
250
+ }));
251
+ })).pipe(Stream.mapAccum(() => Option.none(), (observed, batch) => {
384
252
  let current = observed;
385
- for (const item of batch.items) if (FrontierItem.$is("Reset")(item) || FrontierItem.$is("Removed")(item) && item.stream === stream || FrontierItem.$is("Snapshot")(item) && !item.streams.has(stream)) current = Option.none();
386
- else if (FrontierItem.$is("Dirty")(item) && item.stream === stream) current = Option.some(item.offset);
253
+ for (const item of batch.items) if (FrontierItem.$is("Reset")(item) || FrontierItem.$is("Removed")(item) && item.stream === source || FrontierItem.$is("Snapshot")(item) && !item.streams.has(source)) current = Option.none();
254
+ else if (FrontierItem.$is("Dirty")(item) && item.stream === source) current = Option.some(item.offset);
387
255
  return [current, [batch.upToDate && Option.isSome(current) && compare(current.value, target.offset) >= 0]];
388
256
  }), Stream.filter((reached) => reached), Stream.runHead, Effect.flatMap((found) => Option.isSome(found) ? Effect.void : Effect.never));
389
257
  };
@@ -407,4 +275,4 @@ var streamsy_exports = /* @__PURE__ */ __exportAll({
407
275
  state: () => state,
408
276
  token: () => token
409
277
  });
410
- export { AppendConflict, AppendResult, ChangeSnapshot, CommitBoundary, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_exports as Producer, ProducerGap, ProducerId, ProducerPrecondition, ProducerState, RecordPatch, StaleEpoch, Storage, StorageCapabilities, StorageFault, StoredMessage, address_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
278
+ export { AppendConflict, AppendResult, Batch, ChangeSnapshot, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, InvalidStreamParams, streams_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_exports as Producer, ProducerGap, ProducerId, ProducerPrecondition, ProducerState, RecordPatch, StaleEpoch, StorageCapabilities, StorageFault, StorageOwner, StoredMessage, address_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_exports as Streamsy, StreamsyOffset, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
@@ -1,5 +1,6 @@
1
- import { K as ReadResult, Lt as DecodeFault, P as StreamAddress, W as ReadMessage, a as ProjectionMarksApi, c as CommitHooksApi, d as OwnerRecords, f as OwnerRecordsApi, i as ProjectionMarks, l as commitHookRegistry, n as PendingMark, o as CommitHook, r as ProjectionMarkSummary, s as CommitHooks, t as MarkFailure, u as OWNER_RECORDS_LIST_UNSUPPORTED } from "../projection-marks-DcO_5VNd.js";
2
- import { Cause, Context, Effect, Option, Schema } from "effect";
1
+ import { A as ReadResult, C as StorageOwnerApi, G as StreamId, O as ReadMessage, Q as StorageFault, S as StorageOwner, Y as DecodeFault, Z as InvalidStreamParams, f as StreamAddress, t as StorageShape, x as OwnerId } from "../storage-xTb82JxJ.js";
2
+ import { Cause, Context, Data, Effect, Option, Schema, Scope } from "effect";
3
+ import { SqlClient, SqlError } from "effect/sql";
3
4
  /** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
4
5
  declare const ForeignOwnerType: unique symbol;
5
6
  declare const ForeignOwner_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
@@ -13,10 +14,223 @@ declare class ForeignOwner extends ForeignOwner_base<{
13
14
  constructor(stream: string, knownOwner: boolean);
14
15
  }
15
16
  export declare const isForeignOwner: (value: unknown) => value is ForeignOwner;
16
- type Owner = object;
17
- export declare const attachOwner: <A extends object>(value: A, owner: Owner) => A;
18
- export declare const ownerOf: (value: object) => Owner;
19
- export declare const CurrentOwner: Context.Reference<object | undefined>;
17
+ export declare const CurrentOwner: Context.Reference<OwnerId | undefined>;
18
+ /**
19
+ * Work that joins an owned transaction just before it commits. It receives the
20
+ * stream ids that the transaction created, appended to or deleted.
21
+ */
22
+ type CommitHook = (ids: ReadonlySet<StreamId>) => Effect.Effect<void, SqlError.SqlError>;
23
+ /**
24
+ * Commit hooks on the storage owner, for the durable projection marks.
25
+ *
26
+ * A hook runs inside each later owned transaction that wrote at least one stream
27
+ * id, after the body and before COMMIT. Statements in the hook join the
28
+ * transaction, and a hook failure rolls the transaction back. A SQL host treats
29
+ * a hook failure like a body failure, so a retryable `SqlError` replays the
30
+ * whole transaction, hook included. The memory host turns a hook failure into a
31
+ * defect. A hook must not write streams: its ids would not reach other hooks.
32
+ */
33
+ interface CommitHooksApi {
34
+ /** Register `hook` until the scope closes. */
35
+ readonly beforeCommit: (hook: CommitHook) => Effect.Effect<void, never, Scope.Scope>;
36
+ }
37
+ /** Shared registry for storage boundaries: register in a scope, run in order. */
38
+ export declare const commitHookRegistry: () => {
39
+ beforeCommit: (hook: CommitHook) => Effect.Effect<void, never, Scope.Scope>;
40
+ run: (ids: ReadonlySet<StreamId>) => Effect.Effect<void, SqlError.SqlError>;
41
+ };
42
+ /**
43
+ * Encoded records on the storage owner, for the projection checkpoint store.
44
+ * Calls inside `StorageOwner.withTransaction` join that transaction.
45
+ */
46
+ interface OwnerRecordsApi {
47
+ readonly read: (key: string) => Effect.Effect<Option.Option<string>, StorageFault>;
48
+ /**
49
+ * A snapshot of the owner's encoded entries whose keys start with this exact prefix.
50
+ * A store that cannot list fails with operation `OWNER_RECORDS_LIST_UNSUPPORTED`.
51
+ */
52
+ readonly list: (prefix: string) => Effect.Effect<ReadonlyArray<readonly [key: string, encoded: string]>, StorageFault>;
53
+ readonly write: (key: string, encoded: string) => Effect.Effect<void, StorageFault>;
54
+ readonly remove: (key: string) => Effect.Effect<void, StorageFault>;
55
+ }
56
+ /** The `StorageFault.operation` of an owner store that cannot list its records. */
57
+ export declare const OWNER_RECORDS_LIST_UNSUPPORTED = "records.list.unsupported";
58
+ /** Last failed run, retained through marks, retries and resumes. Messages hold at most 1,000 characters. */
59
+ interface MarkFailure {
60
+ readonly at: number;
61
+ readonly reason: Option.Option<string>;
62
+ readonly message: string;
63
+ }
64
+ /** One pending mark: a binding with input work, a retry, or a recorded wake. */
65
+ interface PendingMark {
66
+ /** The binding's canonical params, as `canonicalParams` encodes them. */
67
+ readonly params: string;
68
+ /** Raised by every mark. A clear only deletes the row when its `seq` still matches. */
69
+ readonly seq: number;
70
+ /** Failed runs since the last success. A mark keeps it. */
71
+ readonly attempts: number;
72
+ /** Epoch ms. 0 means due now; ignored while stopped. */
73
+ readonly dueAt: number;
74
+ /** Recorded wake; when set, equals dueAt and the row has no failure or attempts. */
75
+ readonly wakeAt: Option.Option<number>;
76
+ /** Waits until retry or resume. A mark preserves the stop. */
77
+ readonly stopped: boolean;
78
+ readonly failure: Option.Option<MarkFailure>;
79
+ }
80
+ /** Disjoint counts of one projection's marks at the supplied time. */
81
+ interface ProjectionMarkSummary {
82
+ readonly fresh: number;
83
+ readonly sleeping: number;
84
+ readonly retryDue: number;
85
+ readonly backingOff: number;
86
+ readonly stopped: number;
87
+ /** Earliest due time across non-stopped marks, including fresh and sleeping marks. */
88
+ readonly nextDueAt: Option.Option<number>;
89
+ }
90
+ /**
91
+ * Pending marks for attached projections, on a storage owner or in private memory.
92
+ *
93
+ * A mark is keyed by projection id and canonical params. A deploy that raises the
94
+ * generation picks up the existing marks.
95
+ */
96
+ interface ProjectionMarksApi {
97
+ /** Maximum projection id length in Unicode code points, when bounded by storage. */
98
+ readonly maxProjectionIdLength?: number;
99
+ /**
100
+ * Insert a mark for each binding, or raise its `seq`. A raise keeps
101
+ * `attempts`, `stopped` and `failure`, so a write never resets backoff or a stop.
102
+ * A sleeping row becomes due now and loses its wake index.
103
+ * Call it inside a commit hook. It joins the transaction and fails like the
104
+ * transaction's own statements.
105
+ */
106
+ readonly mark: (projection: string, params: ReadonlyArray<string>) => Effect.Effect<void, SqlError.SqlError>;
107
+ /** The earliest `dueAt` of the projection's non-stopped marks. */
108
+ readonly nextDue: (projection: string) => Effect.Effect<Option.Option<number>, StorageFault>;
109
+ /** Five disjoint counts: fresh, sleeping, retry due, backing off and stopped. */
110
+ readonly summary: (projection: string, now: number) => Effect.Effect<ProjectionMarkSummary, StorageFault>;
111
+ /** Up to `limit` non-stopped marks with `dueAt <= now`, earliest first. */
112
+ readonly due: (projection: string, now: number, limit: number) => Effect.Effect<ReadonlyArray<PendingMark>, StorageFault>;
113
+ /** The marks of these bindings that exist, keyed by params. */
114
+ readonly read: (projection: string, params: ReadonlyArray<string>) => Effect.Effect<ReadonlyMap<string, PendingMark>, StorageFault>;
115
+ /** Delete on a matching `seq`; otherwise keep the row and reset its failure, attempts, dueAt, wakeAt and stop. */
116
+ readonly clear: (projection: string, params: string, seq: number) => Effect.Effect<void, StorageFault>;
117
+ /** Keep a matching row asleep at wakeAt and reset failure state. A seq mismatch
118
+ * becomes fresh and due now. An absent row is inserted asleep with seq 1. */
119
+ readonly sleep: (projection: string, params: string, seq: number, wakeAt: number) => Effect.Effect<void, StorageFault>;
120
+ /** Delete the mark whatever its `seq`. */
121
+ readonly remove: (projection: string, params: string) => Effect.Effect<void, StorageFault>;
122
+ /** Insert or update a failure, preserving seq. Some(dueAt) backs off; None stops. */
123
+ readonly fail: (projection: string, params: string, options: {
124
+ readonly attempts: number;
125
+ readonly failure: MarkFailure;
126
+ readonly dueAt: Option.Option<number>;
127
+ }) => Effect.Effect<void, StorageFault>;
128
+ /** Set failed or stopped marks due now and clear their stop, preserving attempts, seq and failure.
129
+ * Optionally select one binding. Returns the number changed; already due, non-stopped marks are unchanged.
130
+ */
131
+ readonly retry: (projection: string, params?: string) => Effect.Effect<number, StorageFault>;
132
+ /** Make stopped marks due now, preserving attempts, seq and failure. Returns the number changed. */
133
+ readonly resume: (projection: string) => Effect.Effect<number, StorageFault>;
134
+ /** Up to limit marks with attempts > 0, stopped first, then by dueAt and params. */
135
+ readonly failed: (projection: string, limit: number) => Effect.Effect<ReadonlyArray<PendingMark>, StorageFault>;
136
+ }
137
+ interface TransactionParticipant {
138
+ /** Runs synchronously after the draft becomes committed, before wakes. Must not throw. */
139
+ readonly onCommit: () => void;
140
+ /**
141
+ * Runs synchronously when the outer transaction rolls back. Must not throw.
142
+ * A throw adds a defect to the transaction's cause. Effect's typed recovery
143
+ * gives defects precedence even when the exit still contains a typed failure.
144
+ */
145
+ readonly onRollback: () => void;
146
+ }
147
+ declare const MemoryEnlistFault_base: Schema.Class<MemoryEnlistFault, Schema.TaggedStruct<"MemoryEnlistFault", {
148
+ readonly message: Schema.String;
149
+ }>, Cause.YieldableError & {
150
+ readonly brand: unique symbol;
151
+ }>;
152
+ export declare class MemoryEnlistFault extends MemoryEnlistFault_base {}
153
+ /**
154
+ * The backend kind of a storage owner. `Sql`: Streamsy packages put their tables on
155
+ * this client, in its transaction. `Memory`: Streamsy packages join the owner's
156
+ * transaction open on this fiber with `enlist`, which fails outside it.
157
+ */
158
+ export type OwnerBackend = Data.TaggedEnum<{
159
+ Sql: {
160
+ readonly client: SqlClient.SqlClient;
161
+ };
162
+ Memory: {
163
+ readonly enlist: (participant: TransactionParticipant) => Effect.Effect<void, MemoryEnlistFault>;
164
+ };
165
+ }>;
166
+ export declare const OwnerBackend: Data.TaggedEnum.Constructor<{
167
+ readonly _tag: "Memory";
168
+ readonly enlist: (participant: TransactionParticipant) => Effect.Effect<void, MemoryEnlistFault>;
169
+ } | {
170
+ readonly _tag: "Sql";
171
+ readonly client: SqlClient.SqlClient;
172
+ }>;
173
+ /** A SQL owner's backend. */
174
+ type SqlBackend = Data.TaggedEnum.Value<OwnerBackend, "Sql">;
175
+ /** A memory owner's backend. */
176
+ type MemoryBackend = Data.TaggedEnum.Value<OwnerBackend, "Memory">;
177
+ /**
178
+ * Join the memory owner's transaction open on this fiber. A SQL owner has no memory
179
+ * transaction, so there it fails as an enlist outside the owner fiber does.
180
+ */
181
+ export declare const memoryEnlist: (backend: OwnerBackend) => MemoryBackend["enlist"];
182
+ /**
183
+ * A key for one value on each owner. Keep the key in a module constant: each owner runs
184
+ * `make` with its own parts once, on first use.
185
+ */
186
+ export declare class OwnerSlot<A> {
187
+ readonly make: (parts: OwnerParts) => A;
188
+ constructor(make: (parts: OwnerParts) => A);
189
+ }
190
+ /** The adapter parts of a storage owner, for Streamsy packages. */
191
+ interface OwnerParts {
192
+ readonly storage: StorageShape;
193
+ readonly records: OwnerRecordsApi;
194
+ readonly hooks: CommitHooksApi;
195
+ readonly marks: ProjectionMarksApi;
196
+ readonly backend: OwnerBackend;
197
+ /**
198
+ * The value of `key` on this owner. The first call runs the key's `make`; later calls
199
+ * with the same key return that value, whichever layer asks.
200
+ */
201
+ readonly slot: <A>(key: OwnerSlot<A>) => A;
202
+ }
203
+ /** What an adapter supplies to build a storage owner. */
204
+ interface OwnerOptions {
205
+ /** A short label for the owner id, such as `memory` or `sql`. */
206
+ readonly label: string;
207
+ readonly storage: StorageShape;
208
+ readonly records: OwnerRecordsApi;
209
+ readonly hooks: CommitHooksApi;
210
+ readonly marks: ProjectionMarksApi;
211
+ readonly backend: OwnerBackend;
212
+ /** The owner's transaction. A SQL host maps each `SqlError` to a `StorageFault`. */
213
+ readonly withTransaction: StorageOwnerApi["withTransaction"];
214
+ }
215
+ /** A fresh owner identity. Each call returns a value no other call returns. */
216
+ export declare const newOwnerId: (label: string) => OwnerId;
217
+ /** Build a storage owner from its adapter parts. Each call is a new owner. */
218
+ export declare const buildStorageOwner: (options: OwnerOptions) => typeof StorageOwner.Service;
219
+ /** The parts a decorator can replace. */
220
+ interface OwnerPatch {
221
+ readonly storage?: StorageShape;
222
+ readonly records?: OwnerRecordsApi;
223
+ readonly hooks?: CommitHooksApi;
224
+ readonly marks?: ProjectionMarksApi;
225
+ readonly withTransaction?: StorageOwnerApi["withTransaction"];
226
+ }
227
+ /**
228
+ * The same owner with some parts replaced, for decorators in tests. The id, the backend
229
+ * and the slots stay the owner's own.
230
+ */
231
+ export declare const decorateOwner: (owner: typeof StorageOwner.Service, patch: OwnerPatch) => typeof StorageOwner.Service;
232
+ /** The adapter parts of `owner`. Dies when `buildStorageOwner` did not build it. */
233
+ export declare const ownerParts: (owner: typeof StorageOwner.Service) => OwnerParts;
20
234
  /**
21
235
  * The MySQL producer key holds a stream id and at most this many producer id
22
236
  * code points, so every storage dialect enforces it. Projections that build
@@ -53,32 +267,21 @@ interface TemplateGrammar<Template extends string = string> {
53
267
  readonly names: ReadonlyArray<string>;
54
268
  }
55
269
  export declare function compileSegments<const Template extends string>(template: Template): TemplateGrammar<Template>;
270
+ /**
271
+ * True when a route is a singleton: a template route whose template names no parameter.
272
+ * A custom route has an empty template and is never a singleton.
273
+ */
274
+ export declare function isSingletonRoute(route: {
275
+ readonly template: string;
276
+ }): boolean;
56
277
  /** A new private marks store. Each operation runs synchronously when its Effect executes. */
57
278
  export declare const memoryProjectionMarks: () => ProjectionMarksApi;
58
- interface TransactionParticipant {
59
- /** Runs synchronously after the draft becomes committed, before wakes. Must not throw. */
60
- readonly onCommit: () => void;
61
- /**
62
- * Runs synchronously when the outer transaction rolls back. Must not throw.
63
- * A throw adds a defect to the transaction's cause. Effect's typed recovery
64
- * gives defects precedence even when the exit still contains a typed failure.
65
- */
66
- readonly onRollback: () => void;
67
- }
68
- declare const MemoryEnlistFault_base: Schema.Class<MemoryEnlistFault, Schema.TaggedStruct<"MemoryEnlistFault", {
69
- readonly message: Schema.String;
70
- }>, Cause.YieldableError & {
71
- readonly brand: unique symbol;
72
- }>;
73
- declare class MemoryEnlistFault extends MemoryEnlistFault_base {}
74
- /** Join the memory owner transaction open on this fiber. */
75
- export declare function enlist(owner: object, participant: TransactionParticipant): Effect.Effect<void, MemoryEnlistFault>;
76
279
  export declare const attachOffsets: <A extends object>(result: A, offsets: ReadonlyArray<string>) => A;
77
280
  export declare const offsetsOf: (result: Pick<ReadResult, "messages">) => ReadonlyArray<string> | undefined;
78
281
  /** A decoded message, or None for a change outside a non-strict State address's collections. */
79
282
  export declare const decodeMessage: <A, RD, RE>(address: StreamAddress<A, RD, RE>, message: ReadMessage, index: number) => Effect.Effect<Option.Option<A>, DecodeFault, RD>;
80
283
  /** Decode the State envelope while keeping row values in their wire form. */
81
- export declare const decodeStateWire: (input: string, options?: import("effect/SchemaAST").ParseOptions) => import("effect/Effect").Effect<{
284
+ export declare const decodeStateWire: (input: string, options?: import("effect/SchemaAST").ParseOptions) => Effect.Effect<{
82
285
  readonly headers: {
83
286
  readonly control: "reset" | "snapshot-end" | "snapshot-start";
84
287
  readonly offset?: string | undefined;
@@ -106,4 +309,29 @@ export declare const decodeStateWire: (input: string, options?: import("effect/S
106
309
  readonly operation: "delete";
107
310
  };
108
311
  }, Schema.SchemaError, never>;
109
- export { type CommitHook, CommitHooks, type CommitHooksApi, type MarkFailure, OWNER_RECORDS_LIST_UNSUPPORTED, OwnerRecords, type OwnerRecordsApi, type PendingMark, type ProjectionMarkSummary, ProjectionMarks, type ProjectionMarksApi, type TransactionParticipant, commitHookRegistry };
312
+ /**
313
+ * Throw a params failure from a synchronous binding such as `at(params)`. The throw is a
314
+ * `RangeError` whose `cause` is the typed failure, so `resolveParams` can recover it.
315
+ */
316
+ export declare const throwInvalidStreamParams: (error: InvalidStreamParams) => never;
317
+ /**
318
+ * Run a throwing params binding inside an Effect. A params failure becomes
319
+ * `InvalidStreamParams` in `E`; any other throw is a defect.
320
+ */
321
+ export declare const resolveParams: <A>(bind: () => A) => Effect.Effect<A, InvalidStreamParams>;
322
+ /**
323
+ * A declaration that binds to a value. A singleton declaration has `singleton`, its bound
324
+ * value. A declaration with params has `at(params)`.
325
+ */
326
+ type Bindable<P, B> = {
327
+ readonly singleton: B;
328
+ } | {
329
+ readonly at: (params: P) => B;
330
+ };
331
+ /**
332
+ * Bind any declaration for `params`: its `singleton` for a singleton, `at(params)` otherwise.
333
+ * A singleton ignores `params`, as its route reads none. `at` may throw a `RangeError` whose
334
+ * `cause` is an `InvalidStreamParams`; wrap the call in `resolveParams` for request values.
335
+ */
336
+ export declare const bindDeclaration: <P, B>(declaration: Bindable<P, B>, params: P) => B;
337
+ export type { Bindable, CommitHook, CommitHooksApi, MarkFailure, MemoryBackend, OwnerOptions, OwnerParts, OwnerPatch, OwnerRecordsApi, PendingMark, ProjectionMarkSummary, ProjectionMarksApi, SqlBackend, TransactionParticipant };