@streamsy/core 0.5.0 → 0.7.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.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { $ as StreamLifecycle, B as StreamsFault, C as ProducerGap, D as StreamGone, E as StreamClosed, G as MessageWindow, H as isRetryableFault, J as ProducerState, K as Offset, L as DecodeFault, M as Storage, N as ZERO_OFFSET, O as StreamNotFound, P as compare, Q as StreamId, R as EncodeFault, S as OffsetMismatch, T as StreamBusy, U as isStreamsFault, V as TransportFault, W as ChangeSnapshot, X as StoredMessage, Y as RecordPatch, Z as StreamConfig, _ as InvalidAppendRequest, a as custom, b as InvalidReadRequest, c as state, d as address_exports, et as StreamRecord, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, k as isProtocolError, m as AppendConflict, n as bind, o as group, p as CreateResult, q as ProducerId, r as bytes, s as json, t as Wildcard, v as InvalidEpochSeq, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest, z as StorageFault } from "./streamsy-DJMArv09.js";
3
- import { n as CommitBoundary, t as layer$1 } from "./layer-DJ-c63nY.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$2, u as Operations } from "./layer-DyezIxJT.js";
5
- import { t as http_exports } from "./http-x2IjDHvw.js";
6
- import { Array, Data, Layer, Predicate, Record, Schema } from "effect";
2
+ import { $ as RecordPatch, A as StreamClosed, C as InvalidForkRequest, D as ProducerGap, E as OffsetMismatch, G as TransportFault, H as EncodeFault, I as Storage, J as ChangeSnapshot, K as isRetryableFault, L as ZERO_OFFSET, M as StreamNotFound, N as isProtocolError, O as StaleEpoch, Q as ProducerState, R as compare, S as InvalidEpochSeq, T as NotSupported, U as StorageFault, V as DecodeFault, W as StreamsFault, X as Offset, Y as MessageWindow, Z as ProducerId, _ as CreateResult, a as custom, b as ForkSourceNotFound, c as state, d as address_exports, et as StoredMessage, f as isControl, g as AppendResult, h as stateControl, it as StreamRecord, j as StreamGone, k as StreamBusy, m as stateChange, n as bind, nt as StreamId, o as group, p as isUpsert, q as isStreamsFault, r as bytes, rt as StreamLifecycle, s as json, t as Wildcard, tt as StreamConfig, v as AppendConflict, w as InvalidReadRequest, x as InvalidAppendRequest, y as CreateConflict } from "./streamsy-D9OCCdw0.js";
3
+ import { n as CommitBoundary, t as layer$1 } from "./layer-C-QriVBc.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$2, u as Operations } from "./layer-8Y1cg6UL.js";
5
+ import { t as http_exports } from "./http-B10ao6xE.js";
6
+ import { Array, Data, Effect, Layer, Option, Predicate, Record, Schema, Stream } from "effect";
7
7
  // src/storage/capabilities.ts
8
8
  const StorageCapabilities = Schema.Struct({
9
9
  fork: Schema.Literals([
@@ -30,6 +30,8 @@ function layer(group, options = {}) {
30
30
  // src/toolkit/durable-state.ts
31
31
  var durable_state_exports = /* @__PURE__ */ __exportAll({
32
32
  changes: () => changes,
33
+ materialize: () => materialize,
34
+ materialized: () => materialized,
33
35
  remove: () => remove,
34
36
  upsert: () => upsert
35
37
  });
@@ -102,6 +104,73 @@ const stampControl = (entry, offset) => offset === void 0 || entry.headers.offse
102
104
  control: entry.headers.control,
103
105
  offset
104
106
  } };
107
+ /** A row key that is unique across collections, for snapshot bookkeeping. */
108
+ const snapshotKey = (type, key) => `${type}\u0000${key}`;
109
+ /** Empty materialized state for the collections of `address`. */
110
+ function materialized(address) {
111
+ const rows = {};
112
+ for (const type of Record.keys(address.collections)) rows[type] = /* @__PURE__ */ new Map();
113
+ return {
114
+ rows,
115
+ snapshot: void 0
116
+ };
117
+ }
118
+ /**
119
+ * Fold State events into materialized state, with the State protocol rules:
120
+ *
121
+ * - `upsert` sets the row of its key, and `delete` removes it.
122
+ * - `reset` clears every collection.
123
+ * - `snapshot-end` removes each row that no change since `snapshot-start` named.
124
+ * A snapshot may span several calls.
125
+ *
126
+ * The input state is not changed. Only the collections that `events` touch are copied.
127
+ */
128
+ function materialize(state, events) {
129
+ const rows = /* @__PURE__ */ new Map();
130
+ let cleared = false;
131
+ let snapshot = state.snapshot === void 0 ? void 0 : new Set(state.snapshot);
132
+ const source = (type) => cleared ? void 0 : Record.has(state.rows, type) ? state.rows[type] : void 0;
133
+ const writable = (type) => {
134
+ const existing = rows.get(type);
135
+ if (existing !== void 0) return existing;
136
+ const copy = new Map(source(type));
137
+ rows.set(type, copy);
138
+ return copy;
139
+ };
140
+ for (const event of events) {
141
+ if (isControl(event)) {
142
+ const control = event.headers.control;
143
+ if (control === "reset") {
144
+ cleared = true;
145
+ rows.clear();
146
+ snapshot = void 0;
147
+ } else if (control === "snapshot-start") snapshot = /* @__PURE__ */ new Set();
148
+ else if (snapshot !== void 0) {
149
+ const seen = snapshot;
150
+ for (const type of Record.keys(state.rows)) {
151
+ const table = writable(type);
152
+ for (const key of Array.fromIterable(table.keys())) if (!seen.has(snapshotKey(type, key))) table.delete(key);
153
+ }
154
+ snapshot = void 0;
155
+ }
156
+ continue;
157
+ }
158
+ const table = writable(event.type);
159
+ if (isUpsert(event)) {
160
+ table.set(event.key, event.value);
161
+ snapshot?.add(snapshotKey(event.type, event.key));
162
+ } else {
163
+ table.delete(event.key);
164
+ snapshot?.delete(snapshotKey(event.type, event.key));
165
+ }
166
+ }
167
+ const next = {};
168
+ for (const type of Record.keys(state.rows)) next[type] = rows.get(type) ?? (cleared ? /* @__PURE__ */ new Map() : state.rows[type]);
169
+ return {
170
+ rows: next,
171
+ snapshot
172
+ };
173
+ }
105
174
  // src/toolkit/producer.ts
106
175
  var producer_exports = /* @__PURE__ */ __exportAll({ next: () => next });
107
176
  /** Advance only after the caller has acknowledged appended or duplicate. Persist this tuple at the owning edge. */
@@ -109,13 +178,170 @@ const next = (position) => ({
109
178
  ...position,
110
179
  producerSeq: position.producerSeq + 1
111
180
  });
181
+ // src/toolkit/wake.ts
182
+ /**
183
+ * Wake streams: one Durable State stream that indexes the writes of a family of
184
+ * source streams.
185
+ *
186
+ * A wake declaration is a State stream with one `stream` collection. Each row
187
+ * is the latest known state of one source stream. A projection writes the rows:
188
+ * `Projection.wake` in `@streamsy/projection` reads one source stream and
189
+ * appends its row with a producer tuple, on the same owner or another one. A
190
+ * wake stream on another owner must exist first: its owner creates it at start.
191
+ * The typed service is the normal State service.
192
+ */
193
+ /** One row of a wake stream: the latest known state of one source stream. */
194
+ const WakeRow = Schema.Struct({
195
+ /** Canonical id of the source stream. It is also the State key. */
196
+ stream: StreamId,
197
+ /** Source tail after the write. The same value as a reader's saved cursor. */
198
+ offset: Offset,
199
+ /** Present when the source stream is closed. */
200
+ closed: Schema.optionalKey(Schema.Literal(true))
201
+ });
202
+ /** The one collection of every wake stream. Its State `type` is `stream`. */
203
+ const wakeCollections = { stream: {
204
+ schema: WakeRow,
205
+ key: "stream"
206
+ } };
207
+ /**
208
+ * The codec of one wake stream message: a `stream` change or a State control.
209
+ * A client that decodes raw JSON pages uses it in place of a typed service.
210
+ */
211
+ const WakeMessage = Schema.Union([stateChange({
212
+ type: "stream",
213
+ schema: WakeRow
214
+ }), stateControl]);
215
+ /**
216
+ * Declare a wake stream: a State stream of `WakeRow`s at a template.
217
+ *
218
+ * ```ts
219
+ * class UserWake extends Streamsy.wake<UserWake>()("App/UserWake", "users/:user/wake", {
220
+ * params: { user: UserKey },
221
+ * }) {}
222
+ * ```
223
+ *
224
+ * The declaration names no sources. A `Projection.wake` binding links one
225
+ * source stream to one wake stream, with params of its own.
226
+ */
227
+ const wake = () => (name, template, options) => state()(name, template, {
228
+ params: options.params,
229
+ collections: wakeCollections
230
+ });
231
+ /** Constructors and matchers for `WakeItem`. */
232
+ const WakeItem = Data.taggedEnum();
233
+ /**
234
+ * The actions for one batch of wake messages. The function is pure: it reads
235
+ * no stream and changes none of its inputs. Rows for one stream collapse to one
236
+ * item; a delete then an upsert of one stream gives `Removed`, then `Dirty` from
237
+ * `-1`. Pass the returned `snapshot` to the call for the next batch.
238
+ *
239
+ * `followWake` uses it over a typed service. A client with its own HTTP reader
240
+ * decodes each page with `WakeMessage` and calls it directly.
241
+ */
242
+ function wakeActions(events, options) {
243
+ const { cursors } = options;
244
+ const items = [];
245
+ let pending = /* @__PURE__ */ new Map();
246
+ let reset = false;
247
+ let open = options.snapshot === void 0 ? void 0 : new Set(options.snapshot);
248
+ const flush = () => {
249
+ for (const [stream, entry] of pending) {
250
+ if (entry.removed) items.push(WakeItem.Removed({ stream }));
251
+ if (Option.isSome(entry.dirty)) items.push(WakeItem.Dirty({
252
+ stream,
253
+ ...entry.dirty.value
254
+ }));
255
+ }
256
+ pending = /* @__PURE__ */ new Map();
257
+ };
258
+ for (const event of events) {
259
+ if (isControl(event)) {
260
+ const control = event.headers.control;
261
+ if (control === "reset") {
262
+ pending = /* @__PURE__ */ new Map();
263
+ items.length = 0;
264
+ items.push(WakeItem.Reset());
265
+ reset = true;
266
+ open = void 0;
267
+ } else if (control === "snapshot-start") open = /* @__PURE__ */ new Set();
268
+ else if (open !== void 0) {
269
+ flush();
270
+ items.push(WakeItem.Snapshot({ streams: open }));
271
+ open = void 0;
272
+ }
273
+ continue;
274
+ }
275
+ const stream = StreamId.make(event.key);
276
+ const prior = pending.get(stream);
277
+ pending.delete(stream);
278
+ if (!isUpsert(event)) {
279
+ pending.set(stream, {
280
+ removed: true,
281
+ dirty: Option.none()
282
+ });
283
+ open?.delete(stream);
284
+ continue;
285
+ }
286
+ const row = event.value;
287
+ const removed = prior?.removed ?? false;
288
+ const base = removed || reset ? "-1" : cursors.get(stream) ?? "-1";
289
+ const dirty = compare(row.offset, base) > 0 || row.closed === true;
290
+ pending.set(stream, {
291
+ removed,
292
+ dirty: dirty ? Option.some({
293
+ from: base,
294
+ offset: row.offset,
295
+ closed: row.closed === true
296
+ }) : Option.none()
297
+ });
298
+ open?.add(stream);
299
+ }
300
+ flush();
301
+ return {
302
+ items,
303
+ snapshot: open
304
+ };
305
+ }
306
+ /**
307
+ * Follow one wake stream and give the actions for each batch: which source
308
+ * streams to read, from which cursor, and which to drop. The helper reads no
309
+ * source stream. Save each source cursor first and the wake cursor (`offset`)
310
+ * last; a stop between the two reads the same rows again, and the offset check
311
+ * skips the streams that were already read.
312
+ */
313
+ function followWake(declaration, params, options) {
314
+ const { from, cursors, ...follow } = options;
315
+ return Stream.unwrap(Effect.map(Effect.service(declaration), (service) => service.follow(params, {
316
+ ...follow,
317
+ offset: from
318
+ }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
319
+ const next = wakeActions(batch.items, {
320
+ cursors,
321
+ snapshot
322
+ });
323
+ const out = {
324
+ items: next.items,
325
+ offset: batch.nextOffset,
326
+ upToDate: batch.upToDate
327
+ };
328
+ return [next.snapshot, [out]];
329
+ }))));
330
+ }
112
331
  // src/streamsy.ts
113
332
  var streamsy_exports = /* @__PURE__ */ __exportAll({
333
+ WakeItem: () => WakeItem,
334
+ WakeMessage: () => WakeMessage,
335
+ WakeRow: () => WakeRow,
114
336
  Wildcard: () => Wildcard,
115
337
  bytes: () => bytes,
116
338
  custom: () => custom,
339
+ followWake: () => followWake,
117
340
  group: () => group,
118
341
  json: () => json,
119
- state: () => state
342
+ state: () => state,
343
+ wake: () => wake,
344
+ wakeActions: () => wakeActions,
345
+ wakeCollections: () => wakeCollections
120
346
  });
121
347
  export { AppendConflict, AppendResult, ChangeSnapshot, CommitBoundary, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, 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 };
@@ -1,4 +1,4 @@
1
- import { n as OwnerRecordsApi, t as OwnerRecords } from "../owner-records-BV5Un5R0.js";
1
+ import { a as CommitHooks, c as OwnerRecords, i as CommitHook, l as OwnerRecordsApi, n as ProjectionMarks, o as CommitHooksApi, r as ProjectionMarksApi, s as commitHookRegistry, t as PendingMark } from "../projection-marks-28vAwOzM.js";
2
2
  import { Context, Effect } from "effect";
3
3
  /** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
4
4
  declare const ForeignOwnerType: unique symbol;
@@ -17,4 +17,40 @@ type Owner = object;
17
17
  export declare const attachOwner: <A extends object>(value: A, owner: Owner) => A;
18
18
  export declare const ownerOf: (value: object) => Owner;
19
19
  export declare const CurrentOwner: Context.Reference<object | undefined>;
20
- export { OwnerRecords, type OwnerRecordsApi };
20
+ /**
21
+ * The MySQL producer key holds a stream id and at most this many producer id
22
+ * code points, so every storage dialect enforces it. Projections that build
23
+ * their own producer ids keep them within it.
24
+ */
25
+ export declare const MAX_PRODUCER_ID_LENGTH = 255;
26
+ /**
27
+ * Fits `key` into `limit` code points. A key within the limit is returned as it is, so
28
+ * keys that storage already holds keep working. A longer key becomes the first code
29
+ * points of `readable`, then `#` and the SHA-256 hex of the full key. The result is at
30
+ * most `limit` code points, and exactly `limit` when `readable` is at least as long.
31
+ */
32
+ export declare const fitKey: (key: string, limit: number, readable?: string) => Effect.Effect<string>;
33
+ /**
34
+ * Compile output shared by `StreamRoute` and stream validation.
35
+ *
36
+ * The public route value carries an id grammar, a typed `parse`, and an address
37
+ * constructor. Stream validation also needs the compiled grammar, so it can
38
+ * reject two templates that can both match one id. This module owns that
39
+ * compilation and the static overlap check.
40
+ */
41
+ interface LiteralSegment {
42
+ readonly kind: "literal";
43
+ readonly value: string;
44
+ }
45
+ interface ParameterSegment {
46
+ readonly kind: "parameter";
47
+ readonly name: string;
48
+ }
49
+ type Segment = LiteralSegment | ParameterSegment;
50
+ interface TemplateGrammar<Template extends string = string> {
51
+ readonly template: Template;
52
+ readonly segments: ReadonlyArray<Segment>;
53
+ readonly names: ReadonlyArray<string>;
54
+ }
55
+ export declare function compileSegments<const Template extends string>(template: Template): TemplateGrammar<Template>;
56
+ export { type CommitHook, CommitHooks, type CommitHooksApi, OwnerRecords, type OwnerRecordsApi, type PendingMark, ProjectionMarks, type ProjectionMarksApi, commitHookRegistry };
@@ -1,3 +1,28 @@
1
- import { a as isForeignOwner, n as attachOwner, o as ownerOf, t as CurrentOwner } from "../owner-BWQ2KvC_.js";
2
- import { t as OwnerRecords } from "../owner-records-C0p8jeC1.js";
3
- export { CurrentOwner, OwnerRecords, attachOwner, isForeignOwner, ownerOf };
1
+ import { a as attachOwner, c as isForeignOwner, i as CurrentOwner, l as ownerOf, t as compileSegments } from "../route-internal-DNL0oGTN.js";
2
+ import { i as OwnerRecords, n as CommitHooks, r as commitHookRegistry, t as ProjectionMarks } from "../projection-marks-RqurLPLA.js";
3
+ import { Array, Effect } from "effect";
4
+ // src/internal/limits.ts
5
+ /**
6
+ * The MySQL producer key holds a stream id and at most this many producer id
7
+ * code points, so every storage dialect enforces it. Projections that build
8
+ * their own producer ids keep them within it.
9
+ */
10
+ const MAX_PRODUCER_ID_LENGTH = 255;
11
+ // src/internal/fit-key.ts
12
+ /** `#` and the 64 hex digits of a SHA-256 end a hashed key. */
13
+ const DIGEST_LENGTH = 65;
14
+ const codePoints = (value) => [...value];
15
+ /** WebCrypto is the SHA-256 that Bun, Node, workerd and browsers all provide. */
16
+ const sha256Hex = (value) => Effect.promise(() => globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))).pipe(Effect.map((digest) => Array.join(Array.map(Array.fromIterable(new Uint8Array(digest)), (byte) => byte.toString(16).padStart(2, "0")), "")));
17
+ /**
18
+ * Fits `key` into `limit` code points. A key within the limit is returned as it is, so
19
+ * keys that storage already holds keep working. A longer key becomes the first code
20
+ * points of `readable`, then `#` and the SHA-256 hex of the full key. The result is at
21
+ * most `limit` code points, and exactly `limit` when `readable` is at least as long.
22
+ */
23
+ const fitKey = (key, limit, readable = key) => {
24
+ if (codePoints(key).length <= limit) return Effect.succeed(key);
25
+ const prefix = Array.join(Array.take(codePoints(readable), limit - DIGEST_LENGTH), "");
26
+ return Effect.map(sha256Hex(key), (digest) => `${prefix}#${digest}`);
27
+ };
28
+ export { CommitHooks, CurrentOwner, MAX_PRODUCER_ID_LENGTH, OwnerRecords, ProjectionMarks, attachOwner, commitHookRegistry, compileSegments, fitKey, isForeignOwner, ownerOf };
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { A as StreamsReader, C as ProducerGap, D as StreamGone, E as StreamClosed, F as isValid, I as next, J as ProducerState, K as Offset, M as Storage, N as ZERO_OFFSET, O as StreamNotFound, P as compare, Q as StreamId, S as OffsetMismatch, T as StreamBusy, X as StoredMessage, Y as RecordPatch, _ as InvalidAppendRequest, b as InvalidReadRequest, et as StreamRecord, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, j as StreamsWriter, m as AppendConflict, n as bind, p as CreateResult, q as ProducerId, v as InvalidEpochSeq, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest } from "./streamsy-DJMArv09.js";
3
- import { r as attachStorage } from "./owner-BWQ2KvC_.js";
2
+ import { $ as RecordPatch, A as StreamClosed, B as next, C as InvalidForkRequest, D as ProducerGap, E as OffsetMismatch, F as StreamsWriter, I as Storage, L as ZERO_OFFSET, M as StreamNotFound, O as StaleEpoch, P as StreamsReader, Q as ProducerState, R as compare, S as InvalidEpochSeq, T as NotSupported, X as Offset, Z as ProducerId, _ as CreateResult, b as ForkSourceNotFound, et as StoredMessage, g as AppendResult, it as StreamRecord, j as StreamGone, k as StreamBusy, n as bind, nt as StreamId, v as AppendConflict, w as InvalidReadRequest, x as InvalidAppendRequest, y as CreateConflict, z as isValid } from "./streamsy-D9OCCdw0.js";
3
+ import { o as attachStorage } from "./route-internal-DNL0oGTN.js";
4
4
  import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
5
5
  import { Array, Clock, Context, Data, Effect, Layer, Match, Option, Predicate, Random, Schema, Stream } from "effect";
6
6
  // src/storage/mutation.ts
@@ -1,8 +1,8 @@
1
- import { M as Storage, N as ZERO_OFFSET } from "./streamsy-DJMArv09.js";
2
- import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-DyezIxJT.js";
3
- import { n as attachOwner, o as ownerOf } from "./owner-BWQ2KvC_.js";
4
- import { t as OwnerRecords } from "./owner-records-C0p8jeC1.js";
5
- import { Array, Context, Effect, Layer, Option, Order, Predicate, Queue, Schedule, Semaphore, Stream } from "effect";
1
+ import { I as Storage, L as ZERO_OFFSET } from "./streamsy-D9OCCdw0.js";
2
+ import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-8Y1cg6UL.js";
3
+ import { a as attachOwner, l as ownerOf } from "./route-internal-DNL0oGTN.js";
4
+ import { i as OwnerRecords, n as CommitHooks, r as commitHookRegistry, t as ProjectionMarks } from "./projection-marks-RqurLPLA.js";
5
+ import { Array, Context, Effect, Layer, Option, Order, Predicate, PubSub, Queue, Schedule, Semaphore, Stream } from "effect";
6
6
  // src/storage/commit-boundary.ts
7
7
  /** The transaction of the storage owner. Every Streamsy storage host provides it. */
8
8
  var CommitBoundary = class extends Context.Service()("@streamsy/core/CommitBoundary") {};
@@ -142,12 +142,73 @@ const createNotifier = Effect.gen(function* () {
142
142
  })
143
143
  };
144
144
  });
145
+ // src/storage/memory/marks.ts
146
+ /** A private transaction draft of the marks. */
147
+ const copyMarks = (marks) => new Map(Array.map([...marks], ([projection, rows]) => [projection, new Map(rows)]));
148
+ const rowsOf = (marks, projection) => {
149
+ const found = marks.get(projection);
150
+ if (found !== void 0) return found;
151
+ const rows = /* @__PURE__ */ new Map();
152
+ marks.set(projection, rows);
153
+ return rows;
154
+ };
155
+ const byDue = Order.mapInput(Order.Tuple([Order.Number, Order.String]), (mark) => [mark.dueAt, mark.params]);
156
+ const mark = (marks, projection, params) => {
157
+ const rows = rowsOf(marks, projection);
158
+ for (const value of params) {
159
+ const found = rows.get(value);
160
+ rows.set(value, found === void 0 ? {
161
+ params: value,
162
+ seq: 1,
163
+ attempts: 0,
164
+ dueAt: 0
165
+ } : {
166
+ ...found,
167
+ seq: found.seq + 1
168
+ });
169
+ }
170
+ };
171
+ const nextDue = (marks, projection) => {
172
+ let earliest;
173
+ for (const row of marks.get(projection)?.values() ?? []) earliest = earliest === void 0 ? row.dueAt : Math.min(earliest, row.dueAt);
174
+ return Option.fromUndefinedOr(earliest);
175
+ };
176
+ const due = (marks, projection, now, limit) => Array.sort(Array.filter([...marks.get(projection)?.values() ?? []], (row) => row.dueAt <= now), byDue).slice(0, limit);
177
+ const read = (marks, projection, params) => {
178
+ const rows = marks.get(projection);
179
+ const found = /* @__PURE__ */ new Map();
180
+ for (const value of params) {
181
+ const row = rows?.get(value);
182
+ if (row !== void 0) found.set(value, row);
183
+ }
184
+ return found;
185
+ };
186
+ const clear = (marks, projection, params, seq) => {
187
+ const rows = marks.get(projection);
188
+ if (rows?.get(params)?.seq === seq) rows.delete(params);
189
+ };
190
+ const remove = (marks, projection, params) => {
191
+ marks.get(projection)?.delete(params);
192
+ };
193
+ const defer = (marks, projection, params, attempts, dueAt) => {
194
+ const rows = rowsOf(marks, projection);
195
+ const found = rows.get(params);
196
+ rows.set(params, {
197
+ params,
198
+ seq: found?.seq ?? 1,
199
+ attempts,
200
+ dueAt
201
+ });
202
+ };
203
+ const deferred = (marks, projection) => Array.filter([...marks.get(projection)?.values() ?? []], (row) => row.attempts > 0).length;
145
204
  // src/storage/memory/boundary.ts
146
205
  var ActiveDraft = class extends Context.Service()("@streamsy/core/internal/MemoryActiveDraft") {};
147
206
  const makeBoundary = (committed, publish) => Effect.gen(function* () {
148
207
  const owner = {};
149
208
  const lock = yield* Semaphore.make(1);
150
209
  let committedRecords = /* @__PURE__ */ new Map();
210
+ let committedMarks = /* @__PURE__ */ new Map();
211
+ const hooks = commitHookRegistry();
151
212
  const current = Effect.flatMap(Effect.serviceOption(ActiveDraft), (draft) => Effect.withFiber((fiber) => {
152
213
  if (Option.isSome(draft) && (draft.value.owner !== owner || !draft.value.active || draft.value.fiberId !== fiber.id)) return Effect.die(/* @__PURE__ */ new Error("Memory boundary requires the active owner fiber"));
153
214
  return Effect.succeed(draft);
@@ -160,21 +221,26 @@ const makeBoundary = (committed, publish) => Effect.gen(function* () {
160
221
  fiberId: fiber.id,
161
222
  state: copyState(committed),
162
223
  records: new Map(committedRecords),
224
+ marks: copyMarks(committedMarks),
225
+ ids: /* @__PURE__ */ new Set(),
163
226
  active: true,
164
227
  changed: false
165
228
  };
166
- return Effect.uninterruptibleMask((restore) => restore(body.pipe(Effect.provideService(ActiveDraft, draft))).pipe(Effect.tap(() => Effect.sync(() => {
229
+ const withHooks = body.pipe(Effect.tap(() => Effect.orDie(hooks.run(draft.ids))), Effect.provideService(ActiveDraft, draft));
230
+ return Effect.uninterruptibleMask((restore) => restore(withHooks).pipe(Effect.tap(() => Effect.sync(() => {
167
231
  Object.assign(committed, draft.state);
168
232
  committedRecords = draft.records;
169
- }).pipe(Effect.andThen(Effect.suspend(() => draft.changed ? publish : Effect.void)))), Effect.ensuring(Effect.sync(() => {
233
+ committedMarks = draft.marks;
234
+ }).pipe(Effect.andThen(Effect.suspend(() => draft.changed ? publish(draft.ids) : Effect.void)))), Effect.ensuring(Effect.sync(() => {
170
235
  draft.active = false;
171
236
  }))));
172
237
  }).pipe(Semaphore.withPermit(lock)));
173
238
  });
174
239
  const access = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.state : committed));
175
- const changed = Effect.map(current, (draft) => {
240
+ const changed = (ids) => Effect.map(current, (draft) => {
176
241
  if (Option.isNone(draft)) throw new Error("Memory mutation requires an owner");
177
242
  draft.value.changed = true;
243
+ for (const id of ids) draft.value.ids.add(id);
178
244
  });
179
245
  const boundary = CommitBoundary.of({ withTransaction });
180
246
  const records = OwnerRecords.of({
@@ -188,9 +254,26 @@ const makeBoundary = (committed, publish) => Effect.gen(function* () {
188
254
  draft.value.records.set(key, encoded);
189
255
  }))
190
256
  });
257
+ const readMarks = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.marks : committedMarks));
258
+ const writeMarks = (f) => withTransaction(Effect.map(current, (draft) => {
259
+ if (Option.isNone(draft)) throw new Error("Memory mark write requires an owner");
260
+ f(draft.value.marks);
261
+ }));
262
+ const marks = ProjectionMarks.of({
263
+ mark: (projection, params) => writeMarks((table) => mark(table, projection, params)),
264
+ nextDue: (projection) => readMarks((table) => nextDue(table, projection)),
265
+ due: (projection, now, limit) => readMarks((table) => due(table, projection, now, limit)),
266
+ read: (projection, params) => readMarks((table) => read(table, projection, params)),
267
+ clear: (projection, params, seq) => writeMarks((table) => clear(table, projection, params, seq)),
268
+ remove: (projection, params) => writeMarks((table) => remove(table, projection, params)),
269
+ defer: (projection, params, attempts, dueAt) => writeMarks((table) => defer(table, projection, params, attempts, dueAt)),
270
+ deferred: (projection) => readMarks((table) => deferred(table, projection))
271
+ });
191
272
  return {
192
273
  boundary: attachOwner(boundary, owner),
274
+ marks: attachOwner(marks, owner),
193
275
  records: attachOwner(records, owner),
276
+ hooks: attachOwner(CommitHooks.of({ beforeCommit: hooks.beforeCommit }), owner),
194
277
  withTransaction,
195
278
  access,
196
279
  changed
@@ -256,7 +339,8 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
256
339
  deadlines: []
257
340
  };
258
341
  const bus = yield* createNotifier;
259
- const owner = yield* makeBoundary(committed, bus.publish);
342
+ const feed = yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown);
343
+ const owner = yield* makeBoundary(committed, (ids) => Effect.andThen(bus.publish, ids.size === 0 ? Effect.void : PubSub.publish(feed, [...ids]).pipe(Effect.asVoid)));
260
344
  const commit = (state, mutation) => {
261
345
  const changed = /* @__PURE__ */ new Set();
262
346
  for (const [index, operation] of mutation.operations.entries()) {
@@ -328,13 +412,14 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
328
412
  const result = yield* owner.access((state) => commit(state, mutation));
329
413
  if (Predicate.isTagged(result, "MutationRejected")) return yield* result;
330
414
  const { outcome, changed } = result;
331
- if (changed.size > 0) yield* owner.changed;
415
+ if (changed.size > 0) yield* owner.changed(ids);
332
416
  return outcome;
333
417
  }).pipe(owner.withTransaction, Effect.uninterruptible);
334
418
  }),
335
419
  changes: (id) => changes(committed, bus, id, chain, interval),
420
+ committed: PubSub.subscribe(feed),
336
421
  nextExpiry: owner.access((state) => Option.fromUndefinedOr(state.deadlines[0]).pipe(Option.map((deadline) => ({ ...deadline }))))
337
422
  });
338
- return Context.make(Storage, attachOwner(storage, ownerOf(owner.boundary))).pipe(Context.add(CommitBoundary, owner.boundary), Context.add(OwnerRecords, owner.records));
423
+ return Context.make(Storage, attachOwner(storage, ownerOf(owner.boundary))).pipe(Context.add(CommitBoundary, owner.boundary), Context.add(OwnerRecords, owner.records), Context.add(CommitHooks, owner.hooks), Context.add(ProjectionMarks, owner.marks));
339
424
  }));
340
425
  export { CommitBoundary as n, layer as t };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { A as StreamsReader, F as isValid, Q as StreamId, f as AppendResult, j as StreamsWriter, k as isProtocolError, p as CreateResult } from "./streamsy-DJMArv09.js";
2
+ import { F as StreamsWriter, N as isProtocolError, P as StreamsReader, _ as CreateResult, g as AppendResult, nt as StreamId, z as isValid } from "./streamsy-D9OCCdw0.js";
3
3
  import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
4
4
  import { Array, Clock, Context, DateTime, Deferred, Effect, Layer, Match, Option, Random, Record, Ref, Schedule, Stream } from "effect";
5
5
  import { HttpServerRequest, HttpServerResponse } from "effect/http";
@@ -1,4 +1,5 @@
1
- import { Context, Data, Effect, Option, Schema, Stream } from "effect";
1
+ import { Context, Data, Effect, Option, PubSub, Schema, Scope, Stream } from "effect";
2
+ import { SqlError } from "effect/sql";
2
3
  declare const StorageFault_base: Schema.Class<StorageFault, Schema.TaggedStruct<"StorageFault", {
3
4
  readonly operation: Schema.String;
4
5
  readonly message: Schema.String;
@@ -2920,6 +2921,15 @@ interface StorageShape {
2920
2921
  readonly producer: (id: StreamId, producerId: ProducerId) => Effect.Effect<Option.Option<ProducerState>, StorageFault>;
2921
2922
  readonly mutate: (mutation: Mutation) => Effect.Effect<MutationApplied, MutationRejected | StorageFault>;
2922
2923
  readonly changes: (id: StreamId) => Stream.Stream<ChangeSnapshot, StorageFault>;
2924
+ /**
2925
+ * Subscribe to the stream ids of later local commits. The subscription exists when
2926
+ * this effect returns, so a commit after that point always lands in it. Each item
2927
+ * holds the ids that one commit created, appended to or deleted, after that commit.
2928
+ * A rolled-back mutation reports nothing. In process and best effort: a commit by
2929
+ * another process on the same database does not show, and nothing replays after a
2930
+ * restart. The scope releases the subscription.
2931
+ */
2932
+ readonly committed: Effect.Effect<PubSub.Subscription<ReadonlyArray<StreamId>>, never, Scope.Scope>;
2923
2933
  readonly nextExpiry: Effect.Effect<Option.Option<{
2924
2934
  readonly at: number;
2925
2935
  readonly streamId: StreamId;
@@ -2938,4 +2948,72 @@ interface OwnerRecordsApi {
2938
2948
  }
2939
2949
  declare const OwnerRecords_base: Context.ServiceClass<OwnerRecords, "@streamsy/core/internal/OwnerRecords", OwnerRecordsApi>;
2940
2950
  declare class OwnerRecords extends OwnerRecords_base {}
2941
- export { ProducerOptions as $, CreateConflictReason as A, ProducerGap as B, ReadNextResult as C, AppendError as D, AppendConflict as E, InvalidEpochSeq as F, StaleEpoch as G, ReadError as H, InvalidForkRequest as I, StreamGone as J, StreamBusy as K, InvalidReadRequest as L, ForkSourceNotFound as M, HeadError as N, AppendErrorFor as O, InvalidAppendRequest as P, AppendOptions as Q, NotSupported as R, ReadMessage as S, AppendBaseError as T, ReadNextError as U, ProtocolError as V, RemoveError as W, isProtocolError as X, StreamNotFound as Y, AppendCallOptions as Z, StreamsWriter as _, StreamsFault as _t, Mutation as a, Offset as at, CreateResult as b, isStreamsFault as bt, Mutations as c, RecordPatch as ct, OperationResults as d, StreamId as dt, ReadNextOptions as et, Operations as f, StreamLifecycle as ft, StreamsReader as g, StorageFault as gt, Reader as h, EncodeFault as ht, StorageShape as i, MessageWindow as it, CreateError as j, CreateConflict as k, Operation as l, StoredMessage as lt, StorageCapabilities as m, DecodeFault as mt, OwnerRecordsApi as n, CreateOptions as nt, MutationApplied as o, ProducerId as ot, ProducerPrecondition as p, StreamRecord as pt, StreamClosed as q, Storage as r, ChangeSnapshot as rt, MutationRejected as s, ProducerState as st, OwnerRecords as t, ReadOptions as tt, OperationResult as u, StreamConfig as ut, Writer as v, TransportFault as vt, ReadResult as w, HeadResult as x, AppendResult as y, isRetryableFault as yt, OffsetMismatch as z };
2951
+ /**
2952
+ * Work that joins an owned transaction just before it commits. It receives the
2953
+ * stream ids that the transaction created, appended to or deleted.
2954
+ */
2955
+ type CommitHook = (ids: ReadonlySet<StreamId>) => Effect.Effect<void, SqlError.SqlError>;
2956
+ /**
2957
+ * Commit hooks on the storage owner, for the durable projection marks.
2958
+ *
2959
+ * A hook runs inside each later owned transaction that wrote at least one stream
2960
+ * id, after the body and before COMMIT. Statements in the hook join the
2961
+ * transaction, and a hook failure rolls the transaction back. A SQL host treats
2962
+ * a hook failure like a body failure, so a retryable `SqlError` replays the
2963
+ * whole transaction, hook included. The memory host turns a hook failure into a
2964
+ * defect. A hook must not write streams: its ids would not reach other hooks.
2965
+ */
2966
+ interface CommitHooksApi {
2967
+ /** Register `hook` until the scope closes. */
2968
+ readonly beforeCommit: (hook: CommitHook) => Effect.Effect<void, never, Scope.Scope>;
2969
+ }
2970
+ declare const CommitHooks_base: Context.ServiceClass<CommitHooks, "@streamsy/core/internal/CommitHooks", CommitHooksApi>;
2971
+ declare class CommitHooks extends CommitHooks_base {}
2972
+ /** Shared registry for storage boundaries: register in a scope, run in order. */
2973
+ declare const commitHookRegistry: () => {
2974
+ beforeCommit: (hook: CommitHook) => Effect.Effect<void, never, Scope.Scope>;
2975
+ run: (ids: ReadonlySet<StreamId>) => Effect.Effect<void, SqlError.SqlError>;
2976
+ };
2977
+ /** One pending mark: a binding whose input has commits that may not have run. */
2978
+ interface PendingMark {
2979
+ /** The binding's canonical params, as `canonicalParams` encodes them. */
2980
+ readonly params: string;
2981
+ /** Raised by every mark. A clear only deletes the row when its `seq` still matches. */
2982
+ readonly seq: number;
2983
+ /** Failed runs since the last success. A mark keeps it. */
2984
+ readonly attempts: number;
2985
+ /** Epoch ms. 0 means due now. */
2986
+ readonly dueAt: number;
2987
+ }
2988
+ /**
2989
+ * Durable pending marks on the storage owner, for attached projections.
2990
+ *
2991
+ * A mark is keyed by projection id and canonical params. Version and generation
2992
+ * are left out, so a deploy that raises the version picks up the old marks.
2993
+ */
2994
+ interface ProjectionMarksApi {
2995
+ /**
2996
+ * Insert a mark for each binding, or raise its `seq`. A raise keeps
2997
+ * `attempts` and `dueAt`, so a write does not reset a binding's backoff.
2998
+ * Call it inside a commit hook. It joins the transaction and fails like the
2999
+ * transaction's own statements.
3000
+ */
3001
+ readonly mark: (projection: string, params: ReadonlyArray<string>) => Effect.Effect<void, SqlError.SqlError>;
3002
+ /** The earliest `dueAt` of the projection's marks. */
3003
+ readonly nextDue: (projection: string) => Effect.Effect<Option.Option<number>, StorageFault>;
3004
+ /** Up to `limit` marks with `dueAt <= now`, earliest first. */
3005
+ readonly due: (projection: string, now: number, limit: number) => Effect.Effect<ReadonlyArray<PendingMark>, StorageFault>;
3006
+ /** The marks of these bindings that exist, keyed by params. */
3007
+ readonly read: (projection: string, params: ReadonlyArray<string>) => Effect.Effect<ReadonlyMap<string, PendingMark>, StorageFault>;
3008
+ /** Delete the mark if its `seq` still equals `seq`. A later mark keeps the row. */
3009
+ readonly clear: (projection: string, params: string, seq: number) => Effect.Effect<void, StorageFault>;
3010
+ /** Delete the mark whatever its `seq`. */
3011
+ readonly remove: (projection: string, params: string) => Effect.Effect<void, StorageFault>;
3012
+ /** Set `attempts` and `dueAt`, and insert the mark if it is absent. */
3013
+ readonly defer: (projection: string, params: string, attempts: number, dueAt: number) => Effect.Effect<void, StorageFault>;
3014
+ /** The number of the projection's marks with at least one failed attempt. */
3015
+ readonly deferred: (projection: string) => Effect.Effect<number, StorageFault>;
3016
+ }
3017
+ declare const ProjectionMarks_base: Context.ServiceClass<ProjectionMarks, "@streamsy/core/internal/ProjectionMarks", ProjectionMarksApi>;
3018
+ declare class ProjectionMarks extends ProjectionMarks_base {}
3019
+ export { StreamBusy as $, ReadNextResult as A, HeadError as B, StreamsReader as C, StorageFault as Ct, CreateResult as D, isStreamsFault as Dt, AppendResult as E, isRetryableFault as Et, AppendErrorFor as F, NotSupported as G, InvalidEpochSeq as H, CreateConflict as I, ProtocolError as J, OffsetMismatch as K, CreateConflictReason as L, AppendBaseError as M, AppendConflict as N, HeadResult as O, AppendError as P, StaleEpoch as Q, CreateError as R, Reader as S, EncodeFault as St, Writer as T, TransportFault as Tt, InvalidForkRequest as U, InvalidAppendRequest as V, InvalidReadRequest as W, ReadNextError as X, ReadError as Y, RemoveError as Z, OperationResult as _, StreamConfig as _t, CommitHooks as a, AppendOptions as at, ProducerPrecondition as b, StreamRecord as bt, OwnerRecords as c, ReadOptions as ct, StorageShape as d, MessageWindow as dt, StreamClosed as et, Mutation as f, Offset as ft, Operation as g, StoredMessage as gt, Mutations as h, RecordPatch as ht, CommitHook as i, AppendCallOptions as it, ReadResult as j, ReadMessage as k, OwnerRecordsApi as l, CreateOptions as lt, MutationRejected as m, ProducerState as mt, ProjectionMarks as n, StreamNotFound as nt, CommitHooksApi as o, ProducerOptions as ot, MutationApplied as p, ProducerId as pt, ProducerGap as q, ProjectionMarksApi as r, isProtocolError as rt, commitHookRegistry as s, ReadNextOptions as st, PendingMark as t, StreamGone as tt, Storage as u, ChangeSnapshot as ut, OperationResults as v, StreamId as vt, StreamsWriter as w, StreamsFault as wt, StorageCapabilities as x, DecodeFault as xt, Operations as y, StreamLifecycle as yt, ForkSourceNotFound as z };