@streamsy/projection 0.15.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.js CHANGED
@@ -1,10 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { _ as NonRetryable, c as recordKey, d as canonicalParams, f as encodeKey, g as InvalidBinding, h as withParams, i as assertCheckpointKeyVersion, l as restore, m as unitOf, n as CheckpointStore, o as loadLatest, p as terminalOf, r as advance, s as rangesOf, t as CheckpointRecord, u as unsupportedBindingList, v as NotAttached, y as ProjectionFault } from "./checkpoint-store-BE0zelau.js";
2
+ import { A as ProjectionFault, B as isInputLoss, C as InvalidBinding, D as NonRetryable, E as InvalidWakeTime, F as SupersededGeneration, H as outputReason, I as TokenConflict, L as UnsupportedComposition, M as ProjectionFaultReasonTag, N as RangeUnreproducible, O as NotAttached, P as RetiredGeneration, R as inputNotFound, S as InputNotFound, T as InvalidSource, V as isValidWakeTime, _ as unitOf, b as HistoryUnavailable, c as rangesOf, d as unsupportedBindingList, f as inOwnerTransaction, g as terminalOf, h as encodeKey, i as assertCheckpointKeyVersion, j as ProjectionFaultReason, k as OutputRejected, l as recordKey, m as canonicalParams, n as CheckpointStore, o as loadLatest, p as storageFault, r as advance, s as ownerCheckpoints, t as CheckpointRecord, u as restore, v as withParams, w as InvalidRecord, x as IdentityMismatch, y as GenerationMismatch, z as invalidWakeTime } from "./checkpoint-store-8FaC7V5x.js";
3
3
  import { Array, Cause, Clock, Context, Data, DateTime, Deferred, Duration, Effect, Exit, Function, Layer, Option, Order, Pipeable, Predicate, PubSub, Pull, Queue, Record, Ref, Result, Schedule, Schema, Semaphore, Stream } from "effect";
4
- import { CommitBoundary, DurableState, Offset, Storage, StorageFault, StreamAddress, StreamId, Streamsy, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
5
- import { CommitHooks, CurrentOwner, MAX_PRODUCER_ID_LENGTH, OwnerRecords, ProjectionMarks, compileSegments, fitKey, isForeignOwner, memoryProjectionMarks, offsetsOf, ownerOf } from "@streamsy/core/internal";
4
+ import { DecodeFault, DurableState, EncodeFault, InvalidStreamParams, Offset, StorageFault, StorageOwner, StreamAddress, StreamId, Streamsy, StreamsyOffset, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
5
+ import { CurrentOwner, MAX_PRODUCER_ID_LENGTH, OwnerBackend, OwnerSlot, bindDeclaration, compileSegments, decodeMessage, decodeStateWire, fitKey, isForeignOwner, memoryProjectionMarks, offsetsOf, ownerParts, resolveParams, throwInvalidStreamParams } from "@streamsy/core/internal";
6
6
  import { Streams, StreamsWriter } from "@streamsy/core/protocol";
7
- import { SqlClient } from "effect/sql";
8
7
  // src/batch.ts
9
8
  /** An input that was skipped this pass: nothing read, nothing known beyond its cursor. */
10
9
  const emptySlice = (from) => ({
@@ -17,43 +16,64 @@ const emptySlice = (from) => ({
17
16
  });
18
17
  /** Iteration preserves the union of the declared input stream requirements. */
19
18
  const inputEntries = (inputs) => Record.toEntries(inputs);
19
+ // src/stored-offset.ts
20
+ /**
21
+ * Projection state keeps input offsets as the strings a Streamsy reader returned. Check one
22
+ * where it goes back into a read or an append; a value that fails is a corrupt record.
23
+ */
24
+ const storedOffset = (value, fault) => Schema.decodeEffect(StreamsyOffset)(value).pipe(Effect.mapError((cause) => {
25
+ const message = `${fault.what} is not a valid offset: ${value}`;
26
+ return fault.input === void 0 ? new ProjectionFault({
27
+ phase: fault.phase,
28
+ reason: new InvalidRecord({
29
+ message,
30
+ cause
31
+ })
32
+ }) : new ProjectionFault({
33
+ phase: fault.phase,
34
+ input: fault.input,
35
+ reason: new InvalidRecord({
36
+ message,
37
+ cause
38
+ })
39
+ });
40
+ }));
20
41
  // src/read.ts
21
- const validateOptions = (options) => Effect.suspend(() => options.limit === void 0 || Number.isSafeInteger(options.limit) && options.limit > 0 ? Effect.void : Effect.fail(new ProjectionFault({
22
- phase: "load",
23
- reason: "invalid-options",
24
- message: "limit must be a positive safe integer"
25
- })));
42
+ /** A bad `limit` is a caller bug, so it is a defect that names the option and the value. */
43
+ const validateOptions = (options) => Effect.suspend(() => options.limit === void 0 || Number.isSafeInteger(options.limit) && options.limit > 0 ? Effect.void : Effect.die(/* @__PURE__ */ new RangeError(`Projection run option limit must be a positive safe integer, got ${String(options.limit)}`)));
26
44
  /** One bounded read after `from`; retain input history and never reuse a deleted stream id. */
27
45
  const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, from) {
28
46
  const { wire: reader } = yield* address.stream;
29
47
  const historyUnavailable = () => new ProjectionFault({
30
48
  phase: "read",
31
- reason: "history-unavailable",
32
49
  input,
33
- message: `Required history of ${address.id} after ${from} is unavailable`
50
+ reason: new HistoryUnavailable({ message: `Required history of ${address.id} after ${from} is unavailable` })
34
51
  });
35
52
  const storageFailure = (cause) => new ProjectionFault({
36
53
  phase: "read",
37
- reason: "storage-failure",
38
54
  input,
39
- message: `Cannot read ${address.id}`,
40
- cause
55
+ reason: cause
41
56
  });
42
- if (Option.isNone(Schema.decodeOption(Offset)(from))) return yield* new ProjectionFault({
57
+ const start = Schema.decodeOption(StreamsyOffset)(from);
58
+ if (Option.isNone(start)) return yield* new ProjectionFault({
43
59
  phase: "load",
44
- reason: "invalid-record",
45
60
  input,
46
- message: `Stored offset for ${input} is not a valid offset`
61
+ reason: new InvalidRecord({ message: `Stored offset for ${input} is not a valid offset` })
47
62
  });
48
- const result = yield* reader.read(address.id, { offset: from }).pipe(Effect.catchTags({
63
+ const result = yield* reader.read(address.id, { offset: start.value }).pipe(Effect.catchTags({
49
64
  InvalidReadRequest: (cause) => new ProjectionFault({
50
65
  phase: "read",
51
- reason: "invalid-source",
52
66
  input,
53
- message: cause.message,
54
- cause
67
+ reason: new InvalidSource({
68
+ message: cause.message,
69
+ cause
70
+ })
71
+ }),
72
+ StreamNotFound: (cause) => new ProjectionFault({
73
+ phase: "read",
74
+ input,
75
+ reason: inputNotFound(address.id, cause)
55
76
  }),
56
- StreamNotFound: () => historyUnavailable(),
57
77
  StreamGone: () => historyUnavailable(),
58
78
  StorageFault: storageFailure,
59
79
  TransportFault: storageFailure
@@ -61,23 +81,19 @@ const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, f
61
81
  if (result.nextOffset < from || result.messages.length === 0 && result.nextOffset !== from) return yield* historyUnavailable();
62
82
  if (result.nextOffset === from && (result.messages.length > 0 || !result.upToDate)) return yield* new ProjectionFault({
63
83
  phase: "read",
64
- reason: "invalid-source",
65
84
  input,
66
- message: `Read of ${address.id} did not advance past ${from}`
85
+ reason: new InvalidSource({ message: `Read of ${address.id} did not advance past ${from}` })
67
86
  });
68
- const items = yield* decodeMessages(input, address, result.messages);
69
- const offsets = pageOffsets(result);
70
- const slice = {
71
- from,
72
- items,
73
- nextOffset: result.nextOffset,
74
- upToDate: result.upToDate,
75
- closed: result.closed
87
+ return {
88
+ slice: {
89
+ from,
90
+ ...yield* decodeMessages(input, address, result.messages, pageOffsets(result)),
91
+ nextOffset: result.nextOffset,
92
+ upToDate: result.upToDate,
93
+ closed: result.closed
94
+ },
95
+ count: result.messages.length
76
96
  };
77
- return { slice: offsets === void 0 ? slice : {
78
- ...slice,
79
- offsets
80
- } };
81
97
  });
82
98
  /** Empty reads know all their offsets; malformed metadata is treated as unavailable. */
83
99
  const pageOffsets = (result) => {
@@ -92,7 +108,7 @@ const pageOffsets = (result) => {
92
108
  */
93
109
  const readOrGone = Effect.fn("Projection.readOrGone")(function* (input, address, from, read, seen) {
94
110
  return yield* read.pipe(Effect.catchTag("ProjectionFault", (fault) => {
95
- if (!seen || fault.reason !== "history-unavailable") return Effect.fail(fault);
111
+ if (!seen || !isInputLoss(fault)) return Effect.fail(fault);
96
112
  return Effect.gen(function* () {
97
113
  const { wire } = yield* address.stream;
98
114
  if (!(yield* wire.head(address.id).pipe(Effect.as(false), Effect.catchTags({
@@ -100,74 +116,92 @@ const readOrGone = Effect.fn("Projection.readOrGone")(function* (input, address,
100
116
  StreamGone: () => Effect.succeed(true)
101
117
  }), Effect.mapError((cause) => new ProjectionFault({
102
118
  phase: "read",
103
- reason: "storage-failure",
104
119
  input,
105
- message: `Cannot read the head of ${address.id}`,
106
- cause
120
+ reason: cause
107
121
  }))))) return yield* fault;
108
- return { slice: {
109
- ...emptySlice(from),
110
- upToDate: true,
111
- closed: true,
112
- gone: true
113
- } };
122
+ return {
123
+ slice: {
124
+ ...emptySlice(from),
125
+ upToDate: true,
126
+ closed: true,
127
+ gone: true
128
+ },
129
+ count: 0
130
+ };
114
131
  });
115
132
  }));
116
133
  });
117
134
  /** Decode failure is an input fault: the stored bytes do not match the declared codec. */
118
- const decodeMessages = (input, address, messages) => Effect.forEach(messages, (message, index) => Schema.decodeEffect(address.codec)(Predicate.isTagged(address, "Json") ? new TextDecoder().decode(message.data) : message.data).pipe(Effect.mapError(() => new ProjectionFault({
119
- phase: "read",
120
- reason: "invalid-source",
121
- input,
122
- message: `Cannot decode ${address.id} at read message ${index}`
123
- }))));
135
+ const decodeMessages = (input, address, messages, offsets) => Effect.gen(function* () {
136
+ const items = [];
137
+ const keptOffsets = [];
138
+ for (const [index, message] of messages.entries()) {
139
+ const decoded = yield* decodeMessage(address, message, index).pipe(Effect.mapError((cause) => new ProjectionFault({
140
+ phase: "read",
141
+ input,
142
+ reason: cause
143
+ })));
144
+ if (Option.isNone(decoded)) continue;
145
+ items.push(decoded.value);
146
+ const offset = offsets?.[index];
147
+ if (offset !== void 0) keptOffsets.push(offset);
148
+ }
149
+ return offsets === void 0 ? { items } : {
150
+ items,
151
+ offsets: keptOffsets
152
+ };
153
+ });
124
154
  /** Re-read server pages, retaining the pinned count and checking the boundary where available. */
125
155
  const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, range) {
126
156
  const { wire: reader } = yield* address.stream;
127
157
  const unreproducible = (detail) => new ProjectionFault({
128
158
  phase: "pin",
129
- reason: "range-unreproducible",
130
159
  input,
131
- message: `Pinned range of ${address.id} after ${range.from} cannot be reproduced: ${detail}`
160
+ reason: new RangeUnreproducible({ message: `Pinned range of ${address.id} after ${range.from} cannot be reproduced: ${detail}` })
132
161
  });
133
162
  if (range.count === 0) {
134
163
  if (range.from !== range.nextOffset || !range.closed && !range.gone) return yield* unreproducible("an empty pin must describe a terminal outcome at the same offset");
135
- return { slice: {
136
- ...emptySlice(range.from),
137
- nextOffset: range.nextOffset,
138
- closed: range.closed === true,
139
- upToDate: true,
140
- ...terminalOf(range)
141
- } };
164
+ return {
165
+ slice: {
166
+ ...emptySlice(range.from),
167
+ nextOffset: range.nextOffset,
168
+ closed: range.closed === true,
169
+ upToDate: true,
170
+ ...terminalOf(range)
171
+ },
172
+ count: 0
173
+ };
142
174
  }
143
175
  let messages = [];
144
176
  let offsets = [];
145
177
  let cursor = range.from;
146
178
  let last;
147
179
  while (messages.length < range.count) {
148
- const page = yield* reader.read(address.id, { offset: cursor }).pipe(Effect.catchTags({
180
+ const start = yield* storedOffset(cursor, {
181
+ phase: "pin",
182
+ input,
183
+ what: `The pinned offset of ${input}`
184
+ });
185
+ const page = yield* reader.read(address.id, { offset: start }).pipe(Effect.catchTags({
149
186
  InvalidReadRequest: (cause) => new ProjectionFault({
150
187
  phase: "pin",
151
- reason: "invalid-record",
152
188
  input,
153
- message: cause.message,
154
- cause
189
+ reason: new InvalidRecord({
190
+ message: cause.message,
191
+ cause
192
+ })
155
193
  }),
156
194
  StreamNotFound: () => unreproducible("the input is missing"),
157
195
  StreamGone: () => unreproducible("the input is gone"),
158
196
  StorageFault: (cause) => new ProjectionFault({
159
197
  phase: "pin",
160
- reason: "storage-failure",
161
198
  input,
162
- message: `Cannot read ${address.id}`,
163
- cause
199
+ reason: cause
164
200
  }),
165
201
  TransportFault: (cause) => new ProjectionFault({
166
202
  phase: "pin",
167
- reason: "storage-failure",
168
203
  input,
169
- message: `Cannot read ${address.id}`,
170
- cause
204
+ reason: cause
171
205
  })
172
206
  }));
173
207
  if (page.messages.length === 0) return yield* unreproducible("the input ended early");
@@ -187,31 +221,33 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
187
221
  offsets = offsets?.slice(0, range.count);
188
222
  if (compare(cursor, range.nextOffset) < 0) return yield* unreproducible("the input is shorter than the pin");
189
223
  }
190
- const slice = {
191
- from: range.from,
192
- items: yield* decodeMessages(input, address, messages),
193
- nextOffset: range.nextOffset,
194
- upToDate: range.upToDate ?? (last.upToDate && cursor === range.nextOffset),
195
- closed: range.closed === true
224
+ return {
225
+ slice: {
226
+ from: range.from,
227
+ ...yield* decodeMessages(input, address, messages, offsets),
228
+ nextOffset: range.nextOffset,
229
+ upToDate: range.upToDate ?? (last.upToDate && cursor === range.nextOffset),
230
+ closed: range.closed === true
231
+ },
232
+ count: messages.length
196
233
  };
197
- return { slice: offsets === void 0 ? slice : {
198
- ...slice,
199
- offsets
200
- } };
201
234
  });
202
235
  /** Read one server page per input in declaration order. */
203
236
  const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets, seen = false) {
204
237
  const slices = {};
238
+ const counts = {};
205
239
  let items = 0;
206
240
  for (const [name, address] of inputEntries(inputs)) {
207
241
  const from = offsets[name] ?? "";
208
242
  const read = yield* readOrGone(name, address, from, readSlice(name, address, from), seen);
209
243
  slices[name] = read.slice;
210
244
  items += read.slice.items.length;
245
+ if (read.count > 0) counts[name] = read.count;
211
246
  }
212
247
  return {
213
248
  slices,
214
- items
249
+ items,
250
+ counts
215
251
  };
216
252
  });
217
253
  /** Tagged items in declaration order, then stream order within each input. */
@@ -244,15 +280,16 @@ const pin$1 = (commit) => Object.defineProperty(commit, RangeKey, {
244
280
  const isPinned = (commit) => RangeKey in commit && commit[RangeKey] === "pin";
245
281
  const inherit = (source, target) => {
246
282
  if (supportsPrepare(source)) withPrepare(target);
247
- if (supportsAccepted(source)) withAccepted(target);
283
+ if (supportsFrontier(source)) withFrontier(target);
248
284
  return isPinned(source) ? pin$1(target) : extend(target);
249
285
  };
250
286
  const PrepareKey = Symbol.for("@streamsy/projection/internal/Prepare");
251
287
  const withPrepare = (commit) => Object.defineProperty(commit, PrepareKey, { value: true });
252
288
  const supportsPrepare = (commit) => PrepareKey in commit && commit[PrepareKey] === true;
253
- const AcceptedKey = Symbol.for("@streamsy/projection/internal/Accepted");
254
- const withAccepted = (commit) => Object.defineProperty(commit, AcceptedKey, { value: true });
255
- const supportsAccepted = (commit) => AcceptedKey in commit && commit[AcceptedKey] === true;
289
+ /** Marks a Commit that writes output batches, which both frontier destinations need. */
290
+ const FrontierKey = Symbol.for("@streamsy/projection/internal/Frontier");
291
+ const withFrontier = (commit) => Object.defineProperty(commit, FrontierKey, { value: true });
292
+ const supportsFrontier = (commit) => FrontierKey in commit && commit[FrontierKey] === true;
256
293
  // src/commit/model.ts
257
294
  const TypeId$1 = "~@streamsy/projection/Commit";
258
295
  /** Opaque to Commit authors; the kernel restores the original typed handler error. */
@@ -277,6 +314,71 @@ const make$1 = (options) => extend({
277
314
  return Pipeable.pipeArguments(this, arguments);
278
315
  }
279
316
  });
317
+ // src/routed-outputs.ts
318
+ const RoutedOutputs = Symbol.for("@streamsy/projection/internal/RoutedOutputs");
319
+ const processFault$1 = (reason) => new ProjectionFault({
320
+ phase: "process",
321
+ reason
322
+ });
323
+ const rejected$1 = (message) => processFault$1(new OutputRejected({ message }));
324
+ const requireRouteRecords = (store, phase) => store?.routes === void 0 ? Effect.fail(new ProjectionFault({
325
+ phase,
326
+ reason: new UnsupportedComposition({ message: "This CheckpointStore does not support routed outputs" })
327
+ })) : Effect.succeed(store.routes);
328
+ /** The checkpoint store of the commit whose retire runs the current cleanup. */
329
+ const CleanupCheckpoints = Context.Reference("@streamsy/projection/internal/CleanupCheckpoints", { defaultValue: () => void 0 });
330
+ /** The route records of the store whose retire runs the current cleanup. */
331
+ const currentRouteRecords = Effect.gen(function* () {
332
+ return yield* requireRouteRecords(yield* CleanupCheckpoints, "checkpoint");
333
+ });
334
+ const routedUnit = (key, store) => ({
335
+ key: recordKey(key),
336
+ store,
337
+ opened: /* @__PURE__ */ new Map(),
338
+ lock: Semaphore.makeUnsafe(1)
339
+ });
340
+ const TransactionRoutedOutputs = Context.Reference("@streamsy/projection/internal/TransactionRoutedOutputs", { defaultValue: () => void 0 });
341
+ const routedDefinition = (route) => ({
342
+ matches: route.match,
343
+ restore: (id) => {
344
+ const parsed = route.parse(id);
345
+ if (Option.isNone(parsed)) return void 0;
346
+ const address = bindDeclaration(route, parsed.value);
347
+ return address.id === id ? address : void 0;
348
+ }
349
+ });
350
+ const routedHandle = (name, route, names, params, key, occupied, routed) => ({ open: (values) => Effect.gen(function* () {
351
+ const unit = yield* TransactionRoutedOutputs;
352
+ if (unit === void 0 || unit.key !== recordKey(key)) return yield* processFault$1(new UnsupportedComposition({ message: `Routed output ${name} requires its binding's process transaction` }));
353
+ const unexpected = Array.findFirst([...names, ...Record.keys(values)], (param) => !Record.has(values, param) || !names.includes(param));
354
+ const address = yield* (Option.isSome(unexpected) ? Effect.fail(new InvalidStreamParams({
355
+ stream: route.template,
356
+ parameter: unexpected.value,
357
+ message: `Expected route parameters ${Array.join(names, ", ")}`
358
+ })) : resolveParams(() => bindDeclaration(route, {
359
+ ...params,
360
+ ...values
361
+ }))).pipe(Effect.mapError(processFault$1));
362
+ if (occupied.has(address.id)) return yield* rejected$1(`Routed output ${name} overlaps an input or output at ${address.id}`);
363
+ if (!Predicate.isTagged(address, "Json")) return yield* rejected$1("Projection outputs require JSON or state routes");
364
+ const service = yield* address.stream;
365
+ const owner = yield* CurrentOwner;
366
+ if (service.owner !== owner) return yield* Effect.die(/* @__PURE__ */ new Error(`Projection ${key.id}: routed output ${name} at ${address.id} is on storage owner ${service.owner}, but Commit.transaction runs on storage owner ${String(owner)}. Provide the output stream from the storage layer that provides the projection's StorageOwner.`));
367
+ return yield* unit.lock.withPermits(1)(Effect.gen(function* () {
368
+ const opened = unit.opened.get(address.id);
369
+ if (opened === name) return address;
370
+ if (opened !== void 0) return yield* rejected$1(`Routed outputs ${opened} and ${name} both name ${address.id}`);
371
+ const records = yield* requireRouteRecords(unit.store, "process");
372
+ if ((yield* records.state(key, name, address.id)) !== "live") {
373
+ for (const [other, definition] of routed) if (other !== name && definition.matches(address.id) && (yield* records.has(key, other, address.id))) return yield* rejected$1(`Routed outputs ${other} and ${name} both name ${address.id}`);
374
+ const created = yield* createOutput(address, service.wire);
375
+ if (created.closed || created.offset !== ZERO_OFFSET) return yield* rejected$1(`Generation-bound output ${address.id} must start empty and open`);
376
+ yield* records.add(key, name, address.id);
377
+ }
378
+ unit.opened.set(address.id, name);
379
+ return address;
380
+ }));
381
+ }) });
280
382
  // src/commit/internal.ts
281
383
  const DetailsKey = Symbol.for("@streamsy/projection/internal/Pending");
282
384
  const setDetails = (pending, value) => Object.defineProperty(pending, DetailsKey, { value });
@@ -286,13 +388,21 @@ const detailsOf = (pending) => {
286
388
  outputs: {}
287
389
  };
288
390
  };
391
+ /**
392
+ * A transactional output on another owner is a wiring defect. `Projection.attach` checks
393
+ * it once at layer build; a direct run finds it here.
394
+ */
395
+ const foreignOutput = (projection, output, owner, found) => /* @__PURE__ */ new Error(`Projection ${projection}: output ${output} is on storage owner ${found}, but Commit.transaction runs on storage owner ${owner}. Provide the output stream from the storage layer that provides the projection's StorageOwner.`);
289
396
  const load = (key) => CheckpointStore.use((store) => store.load(key));
290
397
  const remove$1 = (key) => CheckpointStore.use((store) => store.remove(key));
291
- const retire$1 = ({ key, cleanup }) => CheckpointStore.use((store) => store.retire === void 0 ? Effect.fail(new ProjectionFault({
398
+ /** The startup inventory of an id in `store`, or `UnsupportedComposition` without `list`. */
399
+ const listIn = (store, id) => store.list === void 0 ? Effect.fail(unsupportedBindingList()) : store.list(id);
400
+ const list = (id) => CheckpointStore.use((store) => listIn(store, id));
401
+ const retireIn = (store, { key, cleanup }) => store.retire === void 0 ? Effect.fail(new ProjectionFault({
292
402
  phase: "checkpoint",
293
- reason: "unsupported-composition",
294
- message: `The checkpoint store cannot retire ${key.id}`
295
- })) : store.retire(key).pipe(Effect.tap(() => cleanup)));
403
+ reason: new UnsupportedComposition({ message: `The checkpoint store cannot retire ${key.id}` })
404
+ })) : store.retire(key).pipe(Effect.tap(() => cleanup.pipe(Effect.provideService(CleanupCheckpoints, store))));
405
+ const retire$1 = (request) => CheckpointStore.use((store) => retireIn(store, request));
296
406
  /** Merge the handler's state and timer into the same checkpoint write. */
297
407
  const withState = (next, result) => {
298
408
  const stored = result !== void 0 && "encoded" in result ? {
@@ -308,30 +418,18 @@ const beforeRecord = (pending) => Option.getOrElse(pending.loaded.record, () =>
308
418
  ...pending.next,
309
419
  inputs: Record.fromEntries(Array.map(Record.toEntries(pending.next.inputs), ([name, offset]) => [name, pending.unit.ranges[name]?.from ?? offset]))
310
420
  }));
311
- const settle = (pending, result) => CheckpointStore.use((store) => store.compareAndSet(pending.key, pending.loaded.token, withState(pending.next, result))).pipe(Effect.asVoid);
421
+ const settleIn = (store, pending, result) => store.compareAndSet(pending.key, pending.loaded.token, withState(pending.next, result)).pipe(Effect.asVoid);
422
+ const settle = (pending, result) => CheckpointStore.use((store) => settleIn(store, pending, result));
312
423
  // src/commit/checkpoint.ts
313
424
  const checkpoint = make$1({
314
425
  name: "checkpoint",
315
426
  guarantee: "exactly-once",
316
427
  load,
428
+ list,
317
429
  remove: remove$1,
318
430
  retire: retire$1,
319
431
  apply: (pending) => Effect.flatMap(pending.run, (result) => settle(pending, result))
320
432
  });
321
- // src/transaction.ts
322
- /** The storage owner's transaction, used by Commit.transaction. */
323
- var Transaction = class extends Context.Service()("@streamsy/projection/Transaction") {
324
- /** Join the commit boundary on a memory or SQL storage host. */
325
- static layer = Layer.effect(this, Effect.map(CommitBoundary, (boundary) => ({
326
- owner: ownerOf(boundary),
327
- withTransaction: (body) => boundary.withTransaction(body).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(new ProjectionFault({
328
- phase: "checkpoint",
329
- reason: "storage-failure",
330
- message: "The owner transaction failed",
331
- cause
332
- }))))
333
- })));
334
- };
335
433
  // src/per-generation.ts
336
434
  const TypeId = Symbol.for("@streamsy/projection/PerGeneration");
337
435
  function perGeneration(route, param, options) {
@@ -368,86 +466,23 @@ const validateGenerationParam = (output, params) => {
368
466
  const GenerationOutputs = Symbol.for("@streamsy/projection/internal/GenerationOutputs");
369
467
  /** Outputs whose creation is managed by the current transaction. */
370
468
  const TransactionGenerationOutputs = Context.Reference("@streamsy/projection/internal/TransactionGenerationOutputs", { defaultValue: () => void 0 });
371
- // src/routed-outputs.ts
372
- const RoutedOutputs = Symbol.for("@streamsy/projection/internal/RoutedOutputs");
373
- const processFault = (reason, message, cause) => new ProjectionFault({
374
- phase: "process",
375
- reason,
376
- message,
377
- cause
378
- });
379
- const requireRouteRecords = (store, phase) => store?.routes === void 0 ? Effect.fail(new ProjectionFault({
380
- phase,
381
- reason: "unsupported-composition",
382
- message: "This CheckpointStore does not support routed outputs"
383
- })) : Effect.succeed(store.routes);
384
- const currentRouteRecords = Effect.serviceOption(CheckpointStore).pipe(Effect.flatMap((store) => requireRouteRecords(Option.getOrUndefined(store), "checkpoint")));
385
- const routedUnit = (key, store) => ({
386
- key: recordKey(key),
387
- store,
388
- opened: /* @__PURE__ */ new Map(),
389
- lock: Semaphore.makeUnsafe(1)
390
- });
391
- const TransactionRoutedOutputs = Context.Reference("@streamsy/projection/internal/TransactionRoutedOutputs", { defaultValue: () => void 0 });
392
- const routedDefinition = (route) => ({
393
- matches: route.match,
394
- restore: (id) => {
395
- const parsed = route.parse(id);
396
- if (Option.isNone(parsed)) return void 0;
397
- const address = route.at(parsed.value);
398
- return address.id === id ? address : void 0;
399
- }
400
- });
401
- const routedHandle = (name, route, names, params, key, occupied, routed) => ({ open: (values) => Effect.gen(function* () {
402
- const unit = yield* TransactionRoutedOutputs;
403
- if (unit === void 0 || unit.key !== recordKey(key)) return yield* processFault("unsupported-composition", `Routed output ${name} requires its binding's process transaction`);
404
- const address = yield* Effect.try({
405
- try: () => {
406
- if (Record.keys(values).length !== names.length || !Array.every(names, (param) => Record.has(values, param))) throw new RangeError(`Expected route parameters ${Array.join(names, ", ")}`);
407
- return route.at({
408
- ...params,
409
- ...values
410
- });
411
- },
412
- catch: (cause) => processFault("invalid-output", `Cannot resolve routed output ${name}: ${cause instanceof RangeError ? cause.message : String(cause)}`, cause)
413
- });
414
- if (occupied.has(address.id)) return yield* processFault("invalid-output", `Routed output ${name} overlaps an input or output at ${address.id}`);
415
- if (!Predicate.isTagged(address, "Json")) return yield* processFault("invalid-output", "Projection outputs require JSON or state routes");
416
- const service = yield* address.stream;
417
- const owner = yield* CurrentOwner;
418
- if (service.owner !== owner) return yield* processFault("unsupported-composition", `Output ${address.id} does not share the transaction owner`);
419
- return yield* unit.lock.withPermits(1)(Effect.gen(function* () {
420
- const opened = unit.opened.get(address.id);
421
- if (opened === name) return address;
422
- if (opened !== void 0) return yield* processFault("invalid-output", `Routed outputs ${opened} and ${name} both name ${address.id}`);
423
- const records = yield* requireRouteRecords(unit.store, "process");
424
- if ((yield* records.state(key, name, address.id)) !== "live") {
425
- for (const [other, definition] of routed) if (other !== name && definition.matches(address.id) && (yield* records.has(key, other, address.id))) return yield* processFault("invalid-output", `Routed outputs ${other} and ${name} both name ${address.id}`);
426
- const created = yield* createOutput(address, service.wire);
427
- if (created.closed || created.nextOffset !== ZERO_OFFSET) return yield* processFault("invalid-output", `Generation-bound output ${address.id} must start empty and open`);
428
- yield* records.add(key, name, address.id);
429
- }
430
- unit.opened.set(address.id, name);
431
- return address;
432
- }));
433
- }) });
434
469
  // src/commit/transaction.ts
435
- const checkpointOwnerFault = (key) => new ProjectionFault({
436
- phase: "checkpoint",
437
- reason: "unsupported-composition",
438
- message: `The checkpoint store for ${key.id} does not share the transaction owner`
439
- });
470
+ const ownerTransaction = Effect.map(StorageOwner, (owner) => ({
471
+ id: owner.id,
472
+ store: ownerCheckpoints(owner),
473
+ withTransaction: inOwnerTransaction(owner)
474
+ }));
440
475
  /** Run the body for the owner, and fail when it writes to a stream on another owner. */
441
- const withOwner = (tx, phase) => (body) => body.pipe(Effect.provideService(CurrentOwner, tx.owner), Effect.catchDefect((defect) => isForeignOwner(defect) ? Effect.fail(new ProjectionFault({
476
+ const withOwner = (tx, phase) => (body) => body.pipe(Effect.provideService(CurrentOwner, tx.id), Effect.catchDefect((defect) => isForeignOwner(defect) ? Effect.fail(new ProjectionFault({
442
477
  phase,
443
- reason: "unsupported-composition",
444
- message: defect.message
478
+ reason: new UnsupportedComposition({ message: defect.message })
445
479
  })) : Effect.die(defect)));
446
- const checkpointState = (loaded) => loaded.pipe(Effect.map(({ record }) => Option.isSome(record) ? "present" : "absent"), Effect.catchIf((fault) => fault.reason === "retired-generation", () => Effect.succeed("retired")), Effect.catchIf((fault) => fault.reason === "invalid-record", () => Effect.succeed("present")), Effect.mapError(({ reason, message, cause }) => new ProjectionFault({
480
+ const checkpointState = (loaded) => loaded.pipe(Effect.map(({ record }) => Option.isSome(record) ? "present" : "absent"), Effect.catchReasons("ProjectionFault", {
481
+ RetiredGeneration: () => Effect.succeed("retired"),
482
+ InvalidRecord: () => Effect.succeed("present")
483
+ }), Effect.mapError(({ reason }) => new ProjectionFault({
447
484
  phase: "checkpoint",
448
- reason,
449
- message,
450
- cause
485
+ reason
451
486
  })));
452
487
  const removeWithRoutes = (store, key, checkpoint) => Effect.gen(function* () {
453
488
  const records = yield* requireRouteRecords(store, "checkpoint");
@@ -458,23 +493,17 @@ const removeWithRoutes = (store, key, checkpoint) => Effect.gen(function* () {
458
493
  }
459
494
  return yield* Effect.void;
460
495
  });
461
- const retireInTransaction = (tx, request) => Effect.gen(function* () {
462
- const store = yield* CheckpointStore;
463
- if (ownerOf(store.load) !== tx.owner) return yield* checkpointOwnerFault(request.key);
464
- return yield* tx.withTransaction(retire$1(request).pipe(withOwner(tx, "checkpoint")));
465
- });
496
+ const retireInTransaction = (tx, request) => tx.withTransaction(retireIn(tx.store, request).pipe(withOwner(tx, "checkpoint")));
466
497
  const TransactionCommitTypeId = Symbol("@streamsy/projection/TransactionCommit");
467
498
  const removeInTransaction = (tx, key, cleanup) => tx.withTransaction(Effect.gen(function* () {
468
- const store = yield* CheckpointStore;
469
- if (ownerOf(store.load) !== tx.owner) return yield* checkpointOwnerFault(key);
499
+ const store = tx.store;
470
500
  const checkpoint = yield* checkpointState(store.load(key));
471
501
  if (RoutedOutputs in key) yield* removeWithRoutes(store, key, checkpoint);
472
502
  else yield* store.remove(key);
473
503
  yield* cleanup.pipe(withOwner(tx, "checkpoint"));
474
504
  if ((yield* checkpointState(checkpoint === "absent" ? loadLatest(store, key) : store.load(key))) !== (checkpoint === "retired" ? "retired" : "absent")) return yield* new ProjectionFault({
475
505
  phase: "checkpoint",
476
- reason: "token-conflict",
477
- message: `Record of ${key.id} changed while it was being forgotten. A second writer on the same key is the likely cause. Stop its runners, then forget again.`
506
+ reason: new TokenConflict({ message: `Record of ${key.id} changed while it was being forgotten. A second writer on the same key is the likely cause. Stop its runners, then forget again.` })
478
507
  });
479
508
  return yield* Effect.void;
480
509
  }));
@@ -498,67 +527,55 @@ const removeInTransaction = (tx, key, cleanup) => tx.withTransaction(Effect.gen(
498
527
  const transaction = Object.assign(withPrepare(make$1({
499
528
  name: "transaction",
500
529
  guarantee: "exactly-once",
501
- load,
502
- remove: (key) => Transaction.use((tx) => removeInTransaction(tx, key, Effect.void)),
503
- retire: (request) => Transaction.use((tx) => retireInTransaction(tx, request)),
530
+ load: (key) => Effect.flatMap(ownerTransaction, (tx) => tx.store.load(key)),
531
+ list: (id) => Effect.flatMap(ownerTransaction, (tx) => listIn(tx.store, id)),
532
+ remove: (key) => Effect.flatMap(ownerTransaction, (tx) => removeInTransaction(tx, key, Effect.void)),
533
+ retire: (request) => Effect.flatMap(ownerTransaction, (tx) => retireInTransaction(tx, request)),
504
534
  apply: (pending) => Effect.gen(function* () {
505
- const tx = yield* Transaction;
506
- const store = yield* CheckpointStore;
535
+ const tx = yield* ownerTransaction;
536
+ const store = tx.store;
507
537
  const { outputs, prepare } = detailsOf(pending);
508
538
  const hasRoutes = RoutedOutputs in pending.key;
509
- for (const { address, service } of Record.values(outputs)) if (service.owner !== tx.owner) return yield* new ProjectionFault({
510
- phase: "load",
511
- reason: "unsupported-composition",
512
- message: `Output ${address.id} does not share the transaction owner`
513
- });
514
- if (ownerOf(store.load) !== tx.owner) return yield* checkpointOwnerFault(pending.key);
539
+ for (const { address, service } of Record.values(outputs)) if (service.owner !== tx.id) return yield* Effect.die(foreignOutput(pending.key.id, address.id, tx.id, service.owner));
515
540
  if (prepare !== void 0) yield* prepare;
516
541
  yield* tx.withTransaction(Effect.gen(function* () {
517
542
  const again = yield* store.load(pending.key);
518
543
  if (again.token !== pending.loaded.token) return yield* new ProjectionFault({
519
544
  phase: "checkpoint",
520
- reason: "token-conflict",
521
- message: `Record of ${pending.key.id} changed while the unit was read. A second writer on the same key is the likely cause. Use one writer per key: the follower or one run at a time.`
545
+ reason: new TokenConflict({ message: `Record of ${pending.key.id} changed while the unit was read. A second writer on the same key is the likely cause. Use one writer per key: the follower or one run at a time.` })
522
546
  });
523
547
  if (Option.isNone(again.record)) for (const { address, service, generation } of Record.values(outputs)) {
524
548
  if (generation === void 0) continue;
525
549
  const created = yield* createOutput(address, service.wire);
526
- if (!generation.shared && (created.closed || created.nextOffset !== ZERO_OFFSET)) return yield* new ProjectionFault({
550
+ if (!generation.shared && (created.closed || created.offset !== ZERO_OFFSET)) return yield* new ProjectionFault({
527
551
  phase: "process",
528
- reason: "invalid-output",
529
- message: `Generation-bound output ${address.id} must start empty and open`
552
+ reason: new OutputRejected({ message: `Generation-bound output ${address.id} must start empty and open` })
530
553
  });
531
554
  }
532
555
  const result = yield* pending.run.pipe(withOwner(tx, "process"), Effect.provideService(TransactionGenerationOutputs, pending.generationOutputs), Effect.provideService(TransactionRoutedOutputs, hasRoutes ? routedUnit(pending.key, store) : void 0));
533
556
  if (result !== void 0 && "outputs" in result) for (const [name, output] of Record.toEntries(result.outputs)) {
534
557
  if (!Array.isReadonlyArrayNonEmpty(output.items)) continue;
535
558
  const resolved = outputs[name];
536
- if (resolved === void 0) return yield* new ProjectionFault({
537
- phase: "process",
538
- reason: "invalid-output",
539
- message: `Undeclared output ${name}`
540
- });
559
+ if (resolved === void 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection handler returned an undeclared output: ${name}`));
541
560
  yield* Streams.append(output.address, output.items).pipe(Effect.provideService(StreamsWriter, resolved.service.wire), Effect.mapError((cause) => new ProjectionFault({
542
561
  phase: "process",
543
- reason: isStreamsFault(cause) ? "storage-failure" : Predicate.isTagged(cause, "StreamBusy") ? "output-busy" : "invalid-output",
544
- message: `Cannot append to ${output.address.id}`,
545
- cause
562
+ reason: outputReason(`Cannot append to ${output.address.id}`, cause)
546
563
  })));
547
564
  }
548
- yield* settle(pending, result);
565
+ yield* settleIn(store, pending, result);
549
566
  return yield* Effect.void;
550
567
  }));
551
568
  return yield* Effect.void;
552
569
  })
553
- })).pipe(withAccepted), { [TransactionCommitTypeId]: true });
570
+ })).pipe(withFrontier), { [TransactionCommitTypeId]: true });
554
571
  /**
555
572
  * Clean up binding state in the owner's transaction on forget and retire.
556
573
  * The boundary follows the same nesting rules as {@link transaction}.
557
574
  */
558
575
  const transactionWithCleanup = (cleanup) => inherit(transaction, {
559
576
  ...transaction,
560
- remove: (key) => Transaction.use((tx) => removeInTransaction(tx, key, Effect.suspend(() => cleanup(key)))),
561
- retire: (request) => Transaction.use((tx) => retireInTransaction(tx, {
577
+ remove: (key) => Effect.flatMap(ownerTransaction, (tx) => removeInTransaction(tx, key, Effect.suspend(() => cleanup(key)))),
578
+ retire: (request) => Effect.flatMap(ownerTransaction, (tx) => retireInTransaction(tx, {
562
579
  ...request,
563
580
  cleanup: request.cleanup.pipe(Effect.andThen(() => cleanup(request.key)))
564
581
  }))
@@ -575,36 +592,32 @@ const producerId = (id, params) => fitKey(`${id}${PRODUCER_ID_SUFFIX}${Record.ke
575
592
  /** The head of one output. A missing output on the checkpoint's owner is created here. */
576
593
  const prepareOutput = (output, store, beforeCreate) => {
577
594
  const { wire, owner: outputOwner } = output.service;
578
- return wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== ownerOf(store.load) ? Effect.fail(cause) : beforeCreate.pipe(Effect.andThen(Streams.create(output.address)), Effect.provideService(StreamsWriter, wire), Effect.andThen(wire.head(output.address.id)))), Effect.mapError((cause) => Predicate.isTagged(cause, "ProjectionFault") ? cause : new ProjectionFault({
595
+ return wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== store.owner ? Effect.fail(cause) : beforeCreate.pipe(Effect.andThen(Streams.create(output.address)), Effect.provideService(StreamsWriter, wire), Effect.andThen(wire.head(output.address.id)))), Effect.mapError((cause) => Predicate.isTagged(cause, "ProjectionFault") ? cause : new ProjectionFault({
579
596
  phase: "pin",
580
- reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
581
- message: `Cannot prepare output ${output.address.id}`,
582
- cause
597
+ reason: outputReason(`Cannot prepare output ${output.address.id}`, cause)
583
598
  })));
584
599
  };
585
600
  /** The pin write is the last save before the append, so its conflict is a pin failure. */
586
- const asPin = (fault) => fault.phase === "checkpoint" && fault.reason === "token-conflict" ? new ProjectionFault({
601
+ const asPin = (fault) => fault.phase === "checkpoint" && Predicate.isTagged(fault.reason, "TokenConflict") ? new ProjectionFault({
587
602
  phase: "pin",
588
- reason: fault.reason,
589
- message: fault.message
603
+ reason: fault.reason
590
604
  }) : fault;
591
605
  const producer = pin$1(make$1({
592
606
  name: "producer",
593
607
  guarantee: "effectively-once",
594
608
  remove: remove$1,
595
609
  retire: retire$1,
610
+ list,
596
611
  load: (key) => Effect.gen(function* () {
597
612
  const loaded = yield* load(key);
598
613
  if (Option.isSome(loaded.record)) {
599
614
  if (loaded.record.value.pending !== void 0 && loaded.record.value.pending.seqs === void 0) return yield* new ProjectionFault({
600
615
  phase: "load",
601
- reason: "invalid-record",
602
- message: "A producer pin must include output sequences"
616
+ reason: new InvalidRecord({ message: "A producer pin must include output sequences" })
603
617
  });
604
618
  for (const [name, position] of Record.toEntries(loaded.record.value.adapters.outputs ?? {})) if (position.epoch !== key.generation) return yield* new ProjectionFault({
605
619
  phase: "load",
606
- reason: "stale-epoch",
607
- message: `Stored epoch ${position.epoch} of ${key.id}/${name} is not generation ${key.generation}`
620
+ reason: new SupersededGeneration({ message: `Stored epoch ${position.epoch} of ${key.id}/${name} is not generation ${key.generation}` })
608
621
  });
609
622
  }
610
623
  return loaded;
@@ -621,8 +634,7 @@ const producer = pin$1(make$1({
621
634
  const positions = { ...adapters.outputs };
622
635
  for (const [name, position] of Record.toEntries(positions)) if (position.epoch !== projection.generation) return yield* new ProjectionFault({
623
636
  phase: "load",
624
- reason: "stale-epoch",
625
- message: `Stored epoch ${position.epoch} of ${projection.id}/${name} is not generation ${projection.generation}`
637
+ reason: new SupersededGeneration({ message: `Stored epoch ${position.epoch} of ${projection.id}/${name} is not generation ${projection.generation}` })
626
638
  });
627
639
  const pending = before.record.pending;
628
640
  const result = yield* request.run;
@@ -630,14 +642,12 @@ const producer = pin$1(make$1({
630
642
  const seqs = pending === void 0 ? Record.fromEntries(Array.map(Array.filter(Record.keys(streams), (name) => (processed.items[name]?.length ?? 0) > 0), (name) => [name, positions[name]?.nextSeq ?? 0])) : pending.seqs ?? {};
631
643
  for (const name of Record.keys(seqs)) if (streams[name] === void 0 || (processed.items[name]?.length ?? 0) === 0) return yield* new ProjectionFault({
632
644
  phase: "process",
633
- reason: "invalid-output",
634
- message: `Cannot reproduce pinned output ${name}`
645
+ reason: new OutputRejected({ message: `Cannot reproduce pinned output ${name}` })
635
646
  });
636
647
  if (pending !== void 0) {
637
648
  for (const name of Record.keys(streams)) if ((processed.items[name]?.length ?? 0) > 0 && seqs[name] === void 0) return yield* new ProjectionFault({
638
649
  phase: "process",
639
- reason: "invalid-output",
640
- message: `Cannot reproduce pinned unit: output ${name} has items that were not pinned`
650
+ reason: new OutputRejected({ message: `Cannot reproduce pinned unit: output ${name} has items that were not pinned` })
641
651
  });
642
652
  }
643
653
  let token = before.token;
@@ -645,8 +655,7 @@ const producer = pin$1(make$1({
645
655
  const checkBeforeCreate = Effect.gen(function* () {
646
656
  if ((yield* owner.load(projection)).token !== before.token) return yield* new ProjectionFault({
647
657
  phase: "pin",
648
- reason: "token-conflict",
649
- message: `Record for ${projection.id} changed before creating an output`
658
+ reason: new TokenConflict({ message: `Record for ${projection.id} changed before creating an output` })
650
659
  });
651
660
  return yield* Effect.void;
652
661
  });
@@ -655,13 +664,11 @@ const producer = pin$1(make$1({
655
664
  const head = yield* prepareOutput(output, owner, output.generation === void 0 ? Effect.void : checkBeforeCreate);
656
665
  if (head.closed) return yield* new ProjectionFault({
657
666
  phase: "pin",
658
- reason: "invalid-output",
659
- message: `Output ${output.address.id} is closed`
667
+ reason: new OutputRejected({ message: `Output ${output.address.id} is closed` })
660
668
  });
661
- if (output.generation?.shared === false && positions[name] === void 0 && head.nextOffset !== ZERO_OFFSET) return yield* new ProjectionFault({
669
+ if (output.generation?.shared === false && positions[name] === void 0 && head.offset !== ZERO_OFFSET) return yield* new ProjectionFault({
662
670
  phase: "pin",
663
- reason: "invalid-output",
664
- message: `Generation-bound output ${output.address.id} must start empty and open`
671
+ reason: new OutputRejected({ message: `Generation-bound output ${output.address.id} must start empty and open` })
665
672
  });
666
673
  positions[name] = positions[name] ?? {
667
674
  epoch: projection.generation,
@@ -707,12 +714,13 @@ const producer = pin$1(make$1({
707
714
  }, result));
708
715
  return yield* Effect.void;
709
716
  })
710
- })).pipe(withAccepted);
717
+ })).pipe(withFrontier);
711
718
  // src/commit/at-least-once.ts
712
719
  const atLeastOnce = pin$1(make$1({
713
720
  name: "atLeastOnce",
714
721
  guarantee: "at-least-once",
715
722
  load,
723
+ list,
716
724
  remove: remove$1,
717
725
  retire: retire$1,
718
726
  apply: (pending) => Effect.gen(function* () {
@@ -760,56 +768,172 @@ var commit_exports = /* @__PURE__ */ __exportAll({
760
768
  transactionWithCleanup: () => transactionWithCleanup,
761
769
  withCompensation: () => withCompensation
762
770
  });
763
- // src/accepted.ts
764
- /** Private output name, stable across producer retries. */
771
+ // src/frontier.ts
772
+ /**
773
+ * The `frontier` option: one row builder, two destinations.
774
+ *
775
+ * Each unit publishes one `Streamsy.Frontier` row for each input that moved or
776
+ * closed, plus the frontier rows its State inputs carry. `frontier: true` appends
777
+ * the rows to each fixed State output that declares a frontier collection.
778
+ * `frontier: X` writes them to the frontier stream `X` as part of the unit.
779
+ */
780
+ /** Private output name of a frontier stream. Stable across producer retries, so keep the old name. */
765
781
  const acceptedKey = "@streamsy/accepted";
766
- const validateAccepted = (output, params, inputTemplates, commit, outputNames = []) => {
767
- if (output === void 0) return;
768
- if (!supportsAccepted(commit)) throw new RangeError("accepted requires Commit.transaction or Commit.producer");
782
+ const FrontierOutputs = Symbol.for("@streamsy/projection/internal/FrontierOutputs");
783
+ const frontierOutputs = (binding) => binding[FrontierOutputs];
784
+ /**
785
+ * Collections of an input that is read as raw JSON text, such as the State stream of a
786
+ * `StateTable`. Its frontier rows are forwarded like those of a decoded State input.
787
+ */
788
+ const RawCollections = Symbol.for("@streamsy/projection/internal/RawCollections");
789
+ /** @internal Shared with View.circuit. */
790
+ const isFrontierCollection = (collection) => Predicate.hasProperty(collection, "schema") && collection.schema === Streamsy.Frontier && Predicate.hasProperty(collection, "key") && collection.key === "stream";
791
+ const namesOf = (collections) => Predicate.isObject(collections) ? Array.filter(Record.keys(collections), (name) => isFrontierCollection(collections[name])) : [];
792
+ const frontierCollections = (value) => Predicate.hasProperty(value, "collections") ? namesOf(value.collections) : [];
793
+ const rawCollections = (value) => Predicate.hasProperty(value, RawCollections) ? namesOf(value[RawCollections]) : [];
794
+ const validateCollections = (outputs) => {
795
+ const collections = /* @__PURE__ */ new Map();
796
+ for (const [name, output] of Record.toEntries(outputs)) {
797
+ const generation = isPerGeneration(output) ? generationBinding(output) : void 0;
798
+ if (generation?.routeBy !== void 0) throw new RangeError("frontier does not support routed outputs");
799
+ const [collection, duplicate] = frontierCollections(generation?.route ?? output);
800
+ if (duplicate !== void 0) throw new RangeError(`frontier output ${name} declares more than one frontier collection`);
801
+ if (collection !== void 0) collections.set(name, collection);
802
+ }
803
+ if (collections.size === 0) throw new RangeError("frontier requires a fixed State output with a frontier collection");
804
+ return collections;
805
+ };
806
+ const validateStream = (output, params, inputTemplates, outputNames) => {
769
807
  validateGenerationParam(output, params);
770
- const { route: accepted, param, routeBy } = isPerGeneration(output) ? generationBinding(output) : {
808
+ const { route: stream, param, routeBy } = isPerGeneration(output) ? generationBinding(output) : {
771
809
  route: output,
772
810
  param: void 0,
773
811
  routeBy: void 0
774
812
  };
775
- if (routeBy !== void 0) throw new RangeError("accepted does not support routed outputs");
776
- if (accepted.collections !== Streamsy.wakeCollections) {
777
- if (accepted.collections.stream?.schema !== Streamsy.WakeRow || accepted.collections.stream.key !== "stream") throw new RangeError("accepted requires a wake stream declaration");
778
- }
779
- for (const name of Record.keys(accepted.paramCodecs)) if (name !== param && !Record.has(params, name)) throw new RangeError(`accepted parameter ${name} must be a projection parameter`);
780
- for (const template of inputTemplates) if (template === accepted.template) throw new RangeError("An accepted stream may not name an input stream");
781
- if (Array.contains(outputNames, "@streamsy/accepted")) throw new RangeError(`Output name ${acceptedKey} is reserved for accepted`);
813
+ if (routeBy !== void 0) throw new RangeError("frontier does not support routed outputs");
814
+ if (!isFrontierCollection(stream.collections.stream)) throw new RangeError("frontier requires a frontier stream declaration");
815
+ for (const name of Record.keys(stream.paramCodecs)) if (name !== param && !Record.has(params, name)) throw new RangeError(`frontier parameter ${name} must be a projection parameter`);
816
+ for (const template of inputTemplates) if (template === stream.template) throw new RangeError("A frontier stream may not name an input stream");
817
+ if (Array.contains(outputNames, "@streamsy/accepted")) throw new RangeError(`Output name ${acceptedKey} is reserved for the frontier stream`);
782
818
  };
783
- /** Only moved inputs contribute a row; terminal closes retain their final offset. */
784
- const acceptedOutput = (address, inputs, unit, closed = {}) => {
785
- const items = [];
819
+ /**
820
+ * Check the `frontier` option of a declaration. For `true`, answer the frontier collection
821
+ * of each output that gets the rows. A frontier stream answers `undefined`.
822
+ *
823
+ * @internal Shared with View.circuit.
824
+ */
825
+ const validateFrontier = (frontier, context) => {
826
+ if (frontier === void 0) return void 0;
827
+ if (!supportsFrontier(context.commit)) throw new RangeError("frontier requires Commit.transaction or Commit.producer");
828
+ const outputs = context.outputs ?? {};
829
+ if (frontier === true) return validateCollections(outputs);
830
+ validateStream(frontier, context.params, context.inputTemplates ?? [], Record.keys(outputs));
831
+ };
832
+ /** @internal Reject the removed `accepted` option, passed from JavaScript or unchecked TypeScript. */
833
+ const rejectAccepted = (id, definition) => {
834
+ if ("accepted" in definition && definition.accepted !== void 0) throw new RangeError(`Projection ${id}: accepted was removed. Use frontier: in its place.`);
835
+ };
836
+ /**
837
+ * The row of one input range, or undefined. An input that did not move gives no row,
838
+ * except once at its terminal close. A gone input gives no row.
839
+ */
840
+ const inputFrontier = (stream, range, closedBefore) => {
841
+ if (range.gone === true) return void 0;
842
+ const closed = range.closed === true;
843
+ if (compare(range.nextOffset, range.from) <= 0 && (!closed || closedBefore)) return void 0;
844
+ return closed ? {
845
+ stream,
846
+ offset: range.nextOffset,
847
+ closed: true
848
+ } : {
849
+ stream,
850
+ offset: range.nextOffset
851
+ };
852
+ };
853
+ /** An upsert of a frontier row, in any collection. The caller checks the collection name. */
854
+ const FrontierUpsert = Schema.Struct({
855
+ type: Schema.String,
856
+ value: Streamsy.Frontier,
857
+ headers: Schema.Struct({ operation: Schema.Literal("upsert") })
858
+ });
859
+ const isFrontierUpsert = Schema.is(FrontierUpsert);
860
+ const decodeRawUpsert = Schema.decodeUnknownOption(Schema.fromJsonString(FrontierUpsert));
861
+ /** The frontier upsert in one input item, decoded or stored JSON text. */
862
+ const frontierUpsert = (item, raw) => {
863
+ if (!raw) return isFrontierUpsert(item) ? item : void 0;
864
+ return Predicate.isString(item) ? Option.getOrUndefined(decodeRawUpsert(item)) : void 0;
865
+ };
866
+ /**
867
+ * The frontier rows of one unit, for either destination: the rows its State inputs carry,
868
+ * then one row for each input that moved or closed. `closed` holds the inputs whose close an
869
+ * earlier unit recorded.
870
+ *
871
+ * @internal Shared with View.circuit.
872
+ */
873
+ const unitFrontiers = (inputs, unit, batch, closed = {}) => {
874
+ const rows = /* @__PURE__ */ new Map();
875
+ for (const [name, slice] of Record.toEntries(batch)) {
876
+ const input = inputs[name];
877
+ if (input === void 0) continue;
878
+ const decoded = frontierCollections(input);
879
+ const raw = decoded.length === 0 ? rawCollections(input) : [];
880
+ const types = decoded.length === 0 ? raw : decoded;
881
+ if (types.length === 0) continue;
882
+ for (const value of slice.items) {
883
+ const item = frontierUpsert(value, raw.length > 0);
884
+ if (item === void 0 || !Array.contains(types, item.type)) continue;
885
+ const row = item.value;
886
+ const previous = rows.get(row.stream);
887
+ if (previous === void 0 || compare(row.offset, previous.offset) > 0) rows.set(row.stream, row);
888
+ }
889
+ }
786
890
  for (const [name, range] of Record.toEntries(unit.ranges)) {
787
891
  const input = inputs[name];
788
- if (input === void 0 || range.gone || compare(range.nextOffset, range.from) <= 0 && (!range.closed || closed[name])) continue;
789
- const stream = StreamId.make(input.id);
790
- const offset = Offset.make(range.nextOffset);
791
- const value = range.closed ? {
792
- stream,
793
- offset,
794
- closed: true
795
- } : {
796
- stream,
797
- offset
798
- };
799
- items.push({
800
- type: "stream",
801
- key: stream,
892
+ if (input === void 0) continue;
893
+ const row = inputFrontier(input.id, range, closed[name] === true);
894
+ if (row === void 0) continue;
895
+ const previous = rows.get(row.stream);
896
+ rows.delete(row.stream);
897
+ rows.set(row.stream, previous !== void 0 && compare(previous.offset, row.offset) > 0 ? previous : row);
898
+ }
899
+ return Array.fromIterable(rows.values());
900
+ };
901
+ /** `frontier: true`: append the rows to the buffers before the Commit writes any output. */
902
+ const frontierResult = (result, collections, rows) => {
903
+ if (result === void 0 || !("outputs" in result)) return result;
904
+ if (rows.length === 0) return result;
905
+ const outputs = { ...result.outputs };
906
+ for (const [name, type] of collections) {
907
+ const output = outputs[name];
908
+ if (output === void 0) continue;
909
+ const items = Array.map(rows, (value) => ({
910
+ type,
911
+ key: value.stream,
802
912
  value,
803
913
  headers: { operation: "upsert" }
804
- });
914
+ }));
915
+ outputs[name] = {
916
+ address: output.address,
917
+ items: [...output.items, ...items]
918
+ };
805
919
  }
806
- return {
920
+ return "encoded" in result ? Accumulated({
921
+ value: result.value,
922
+ encoded: result.encoded,
923
+ outputs
924
+ }) : Emitted({ outputs });
925
+ };
926
+ /** `frontier: X`: one more output batch for the frontier stream, added to every handler kind. */
927
+ const frontierStreamResult = (result, address, rows) => {
928
+ const output = {
807
929
  address,
808
- items
930
+ items: Array.map(rows, (value) => ({
931
+ type: "stream",
932
+ key: value.stream,
933
+ value,
934
+ headers: { operation: "upsert" }
935
+ }))
809
936
  };
810
- };
811
- /** Adapt every handler kind to the existing output-writing Commit result. */
812
- const acceptedResult = (result, output) => {
813
937
  const outputs = result !== void 0 && "outputs" in result ? {
814
938
  ...result.outputs,
815
939
  [acceptedKey]: output
@@ -826,18 +950,18 @@ const acceptedResult = (result, output) => {
826
950
  } : emitted;
827
951
  };
828
952
  // src/outputs.ts
829
- const resolveOutputs = (outputs, acceptedOutput, params, key, inputs) => {
953
+ const resolveOutputs = (outputs, frontierStream, params, key, inputs) => {
830
954
  const generationOutputs = /* @__PURE__ */ new Map();
831
955
  const resolve = (name, output) => {
832
956
  if (isPerGeneration(output)) {
833
957
  const { route, param, shared } = generationBinding(output);
834
958
  generationOutputs.set(name, { shared });
835
- return route.at({
959
+ return bindDeclaration(route, {
836
960
  ...params,
837
961
  [param]: key.generation
838
962
  });
839
963
  }
840
- return isDeclaration(output) ? output.at(params) : output;
964
+ return isDeclaration(output) ? bindDeclaration(output, params) : output;
841
965
  };
842
966
  const routed = /* @__PURE__ */ new Map();
843
967
  const streams = Record.fromEntries(Array.flatMap(Record.toEntries(outputs), ([name, output]) => {
@@ -847,7 +971,7 @@ const resolveOutputs = (outputs, acceptedOutput, params, key, inputs) => {
847
971
  }
848
972
  return [[name, resolve(name, output)]];
849
973
  }));
850
- const accepted = acceptedOutput === void 0 ? void 0 : resolve(acceptedKey, acceptedOutput);
974
+ const accepted = frontierStream === void 0 ? void 0 : resolve(acceptedKey, frontierStream);
851
975
  const addresses = accepted === void 0 ? Record.values(streams) : [...Record.values(streams), accepted];
852
976
  const ids = Array.map(addresses, (address) => address.id);
853
977
  if (new Set(ids).size !== ids.length) throw new RangeError("Two outputs may not name the same stream");
@@ -876,9 +1000,10 @@ const resolveOutputs = (outputs, acceptedOutput, params, key, inputs) => {
876
1000
  };
877
1001
  const createOutput = (address, wire) => Streams.create(address).pipe(Effect.provideService(StreamsWriter, wire), Effect.mapError((cause) => new ProjectionFault({
878
1002
  phase: "process",
879
- reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
880
- message: `Cannot create output ${address.id}`,
881
- cause
1003
+ reason: isStreamsFault(cause) ? cause : new OutputRejected({
1004
+ message: `Cannot create output ${address.id}`,
1005
+ cause
1006
+ })
882
1007
  })));
883
1008
  const boundOutputs = (bound) => bound.accepted === void 0 ? bound.streams ?? {} : {
884
1009
  ...bound.streams,
@@ -897,48 +1022,49 @@ const createOutputs = (bound) => Effect.gen(function* () {
897
1022
  const collect = (outputs, buffers, emitted) => Effect.gen(function* () {
898
1023
  for (const [name, entries] of Record.toEntries(emitted)) {
899
1024
  const output = outputs[name];
900
- if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* new ProjectionFault({
901
- phase: "process",
902
- reason: "invalid-output",
903
- message: `Invalid output array ${name}`
904
- });
905
- const values = yield* Effect.try({
906
- try: () => "collections" in output ? DurableState.changes(output, {}, entries) : entries,
907
- catch: (cause) => new ProjectionFault({
908
- phase: "process",
909
- reason: "invalid-output",
910
- message: `Invalid row change for ${name}`,
911
- cause
912
- })
1025
+ if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection handler returned an invalid output array: ${name}`));
1026
+ const values = yield* Effect.suspend(() => {
1027
+ try {
1028
+ return Effect.succeed("collections" in output ? DurableState.changes(output, entries) : entries);
1029
+ } catch (cause) {
1030
+ return Effect.die(new RangeError(`Projection handler returned an invalid row change for output ${name}`, { cause }));
1031
+ }
913
1032
  });
914
1033
  (buffers[name] ??= []).push(...values);
915
1034
  }
916
1035
  return yield* Effect.void;
917
1036
  });
918
- const pin = (reason, message, cause) => new ProjectionFault({
1037
+ const pin = (reason) => new ProjectionFault({
919
1038
  phase: "pin",
920
- reason,
921
- message,
922
- cause
1039
+ reason
923
1040
  });
1041
+ const rejected = (message) => pin(new OutputRejected({ message }));
924
1042
  /** Append one unit under its pinned tuple; appended and duplicate are one outcome. */
925
1043
  const appendPinned = Effect.fn("Projection.appendPinned")(function* (output, wire, items, position) {
926
1044
  return yield* Streams.append(output, items, { producer: position }).pipe(Effect.provideService(StreamsWriter, wire), Effect.catchTags({
927
- EncodeFault: () => new ProjectionFault({
1045
+ EncodeFault: (cause) => new ProjectionFault({
928
1046
  phase: "process",
929
- reason: "invalid-output",
930
- message: `Cannot encode output for ${output.id}`
1047
+ reason: cause
931
1048
  }),
932
- StaleEpoch: (error) => pin("stale-epoch", `Epoch ${position.producerEpoch} of ${output.id} is behind ${error.currentEpoch}`),
933
- ProducerGap: (error) => pin("invalid-record", `Sequence ${error.receivedSeq} of ${output.id} does not follow ${error.expectedSeq}`),
934
- NotSupported: (error) => pin("unsupported-composition", `${output.id} does not support ${error.feature}`),
935
- StorageFault: (cause) => pin("storage-failure", `Cannot append to ${output.id}`, cause),
936
- TransportFault: (cause) => pin("storage-failure", `Cannot append to ${output.id}`, cause),
937
- StreamNotFound: () => pin("invalid-output", `Output ${output.id} does not exist`),
938
- StreamGone: () => pin("invalid-output", `Output ${output.id} is gone`),
939
- StreamClosed: () => pin("invalid-output", `Output ${output.id} is closed`),
940
- AppendConflict: () => pin("invalid-output", `Output ${output.id} refused the append`),
941
- StreamBusy: () => pin("output-busy", `Output ${output.id} is busy`)
1049
+ StaleEpoch: (error) => pin(new SupersededGeneration({
1050
+ message: `Epoch ${position.producerEpoch} of ${output.id} is behind ${error.currentEpoch}`,
1051
+ cause: error
1052
+ })),
1053
+ ProducerGap: (error) => pin(new InvalidRecord({
1054
+ message: `Sequence ${error.receivedSeq} of ${output.id} does not follow ${error.expectedSeq}`,
1055
+ cause: error
1056
+ })),
1057
+ NotSupported: (error) => pin(new UnsupportedComposition({
1058
+ message: `${output.id} does not support ${error.feature}`,
1059
+ cause: error
1060
+ })),
1061
+ StorageFault: pin,
1062
+ TransportFault: pin,
1063
+ StreamNotFound: () => rejected(`Output ${output.id} does not exist`),
1064
+ StreamGone: () => rejected(`Output ${output.id} is gone`),
1065
+ StreamClosed: () => rejected(`Output ${output.id} is closed`),
1066
+ AppendConflict: () => rejected(`Output ${output.id} refused the append`),
1067
+ StreamBusy: pin
942
1068
  }));
943
1069
  });
944
1070
  // src/state.ts
@@ -952,9 +1078,10 @@ const bindState = (definition, params) => {
952
1078
  /** Decodes the state field. `None` means no state is stored. */
953
1079
  const decodeState = (key, schema, encoded) => Option.isNone(encoded) ? Effect.succeedNone : Schema.decodeEffect(Schema.fromJsonString(schema))(encoded.value).pipe(Effect.asSome, Effect.mapError((cause) => new ProjectionFault({
954
1080
  phase: "load",
955
- reason: "invalid-record",
956
- message: `Invalid stored state for ${key.id}`,
957
- cause
1081
+ reason: new InvalidRecord({
1082
+ message: `Invalid stored state for ${key.id}`,
1083
+ cause
1084
+ })
958
1085
  })));
959
1086
  /** The stored state, or the initial value when stored state is absent. */
960
1087
  const currentState = (key, state, encoded) => Effect.gen(function* () {
@@ -963,28 +1090,37 @@ const currentState = (key, state, encoded) => Effect.gen(function* () {
963
1090
  });
964
1091
  const encodeState = (key, schema, value) => Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(Effect.mapError((cause) => new ProjectionFault({
965
1092
  phase: "process",
966
- reason: "invalid-output",
967
- message: `Cannot encode state for ${key.id}`,
968
- cause
1093
+ reason: new EncodeFault({
1094
+ message: `Cannot encode state for ${key.id}`,
1095
+ cause
1096
+ })
969
1097
  })));
970
1098
  // src/wake-at.ts
971
1099
  const request = Data.taggedEnum().WakeAt;
972
- /** Return this request from process; returning void clears the previous deadline. */
973
- const wakeAt = (time) => {
974
- const millis = Predicate.isNumber(time) ? time : DateTime.toEpochMillis(time);
975
- if (!Number.isSafeInteger(millis) || millis < 0) throw new RangeError("wakeAt must be a non-negative safe integer in epoch milliseconds");
976
- return request({ wakeAt: millis });
977
- };
1100
+ /**
1101
+ * Return this request from process; returning void clears the previous deadline. It never throws.
1102
+ * A time that is not a non-negative safe integer in epoch milliseconds fails the unit with a
1103
+ * `ProjectionFault` whose reason is `InvalidWakeTime`, before anything is committed.
1104
+ */
1105
+ const wakeAt = (time) => request({ wakeAt: Predicate.isNumber(time) ? time : DateTime.toEpochMillis(time) });
978
1106
  /** Internal: discard ordinary process return values while keeping wake requests. */
979
1107
  const isWakeAt = (value) => Predicate.isTagged(value, "WakeAt");
980
1108
  // src/step.ts
1109
+ /**
1110
+ * Every process result passes here before any Commit writes, so an invalid wake time fails the
1111
+ * unit on every commit path.
1112
+ */
1113
+ const checkWakeAt = (request) => isValidWakeTime(request.wakeAt) ? Effect.succeed(request) : Effect.fail(new ProjectionFault({
1114
+ phase: "process",
1115
+ reason: invalidWakeTime(request.wakeAt)
1116
+ }));
981
1117
  /** One adapter invocation is one unit. Per-entry variants thread state and preserve order. */
982
1118
  const adapt = (kind, key, state, streams, outputs, handler, batch, unit, encoded, prepared, attempt = 1) => Effect.gen(function* () {
983
- if (kind === "process") return yield* Effect.map(handler(batch, unit, {
1119
+ if (kind === "process") return yield* Effect.flatMap(handler(batch, unit, {
984
1120
  prepared,
985
1121
  outputs,
986
1122
  attempt
987
- }), (result) => isWakeAt(result) ? result : void 0);
1123
+ }), (result) => isWakeAt(result) ? checkWakeAt(result) : Effect.undefined);
988
1124
  let value = state === void 0 ? void 0 : yield* currentState(key, state, encoded);
989
1125
  const buffers = Record.fromEntries(Array.map(Record.keys(streams), (name) => [name, []]));
990
1126
  const steps = kind === "mapAccumBatch" ? [batch] : items(batch);
@@ -1016,34 +1152,66 @@ const adapt = (kind, key, state, streams, outputs, handler, batch, unit, encoded
1016
1152
  // src/declaration.ts
1017
1153
  /** Internal access to the same binding at a chosen generation. */
1018
1154
  const BindGeneration = Symbol.for("@streamsy/projection/internal/BindGeneration");
1155
+ const DeclaredKey = Symbol.for("@streamsy/projection/internal/Declared");
1156
+ /** The commit and owned outputs that `declare` recorded, if it built this declaration. */
1157
+ const declaredOf = (declaration) => DeclaredKey in declaration ? declaration[DeclaredKey] : void 0;
1158
+ /** The stream service of a declared output, a stream class, an address or a per-generation route. */
1159
+ const outputService = (output) => isPerGeneration(output) ? generationBinding(output).route : isDeclaration(output) ? output : output.stream;
1019
1160
  const bindAtGeneration = (declaration, params, generation) => declaration[BindGeneration]?.(params, generation);
1020
- const isDeclaration = (input) => "at" in input;
1161
+ /** A stream declaration, with or without params, as opposed to a fixed address. */
1162
+ const isDeclaration = (input) => "singleton" in input || "at" in input;
1021
1163
  const encodeParams = (id, codecs, params) => {
1022
1164
  const values = params;
1023
1165
  return Record.fromEntries(Array.map(Record.toEntries(codecs), ([name, codec]) => {
1024
1166
  const encoded = Schema.encodeOption(codec)(values[name]);
1025
- if (Option.isNone(encoded)) throw new RangeError(`Cannot encode projection ${id} parameter ${name}`);
1167
+ if (Option.isNone(encoded)) return throwInvalidStreamParams(new InvalidStreamParams({
1168
+ stream: id,
1169
+ parameter: name,
1170
+ message: `Cannot encode projection ${id} parameter ${name}`
1171
+ }));
1026
1172
  return [name, encoded.value];
1027
1173
  }));
1028
1174
  };
1029
1175
  const addressesOf = (inputs, params) => {
1030
- return Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, input]) => [name, isDeclaration(input) ? input.at(params) : input]));
1176
+ return Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, input]) => [name, isDeclaration(input) ? bindDeclaration(input, params) : input]));
1177
+ };
1178
+ /**
1179
+ * Add `singleton` to a declaration without params. It binds on first read, so a binding that
1180
+ * throws still throws where the value is used, and then returns the same object every time.
1181
+ */
1182
+ const withSingleton = (target, bind) => {
1183
+ let cached;
1184
+ return Object.defineProperty(target, "singleton", {
1185
+ enumerable: true,
1186
+ get: () => (cached ??= { value: bind() }).value
1187
+ });
1031
1188
  };
1032
- const declare = (definition, bind) => {
1189
+ /**
1190
+ * Add non-enumerable `at` and `resolve` to a singleton. Both ignore their argument and give the
1191
+ * `singleton` value. A codec record typed wider than its value, such as one annotated
1192
+ * `StreamRoute.ParamCodecs`, gives a declaration whose type has `at` but whose empty record makes
1193
+ * it a singleton at run time. Non-enumerable, so spreads and key lists see only `singleton`, and
1194
+ * every discriminator still tests `"singleton" in x` first.
1195
+ */
1196
+ const withSingletonBindings = (target) => Object.defineProperties(target, {
1197
+ at: { value: () => target.singleton },
1198
+ resolve: { value: () => resolveParams(() => target.singleton) }
1199
+ });
1200
+ const declare = (definition, bind, declared) => {
1033
1201
  const generation = definition.generation ?? 1;
1202
+ const codecs = definition.params ?? {};
1034
1203
  const atGeneration = (params, selected) => bind({
1035
1204
  id: definition.id,
1036
1205
  generation: selected,
1037
- params: encodeParams(definition.id, definition.params, params),
1206
+ params: encodeParams(definition.id, codecs, params),
1038
1207
  decoded: params
1039
1208
  });
1040
- const declaration = {
1209
+ const core = {
1041
1210
  retry: definition.retry,
1042
1211
  id: definition.id,
1043
1212
  generation,
1044
- params: definition.params,
1213
+ params: codecs,
1045
1214
  inputs: definition.inputs,
1046
- at: (params) => atGeneration(params, generation),
1047
1215
  parse: (id) => {
1048
1216
  for (const input of Record.values(definition.inputs)) {
1049
1217
  if (!isDeclaration(input)) continue;
@@ -1053,6 +1221,11 @@ const declare = (definition, bind) => {
1053
1221
  return Option.none();
1054
1222
  }
1055
1223
  };
1224
+ const declaration = Record.isEmptyRecord(codecs) ? withSingletonBindings(withSingleton(core, () => atGeneration({}, generation))) : Object.assign(core, {
1225
+ at: (params) => atGeneration(params, generation),
1226
+ resolve: (params) => resolveParams(() => atGeneration(params, generation))
1227
+ });
1228
+ if (declared !== void 0) Object.defineProperty(declaration, DeclaredKey, { value: declared });
1056
1229
  return Object.defineProperty(declaration, BindGeneration, { value: atGeneration });
1057
1230
  };
1058
1231
  /** @internal Reject legacy definitions passed from JavaScript or unchecked TypeScript. */
@@ -1063,21 +1236,30 @@ const rejectProjectionVersion = (id, definition) => {
1063
1236
  };
1064
1237
  const build = (kind, definition) => {
1065
1238
  rejectProjectionVersion(definition.id, definition);
1239
+ rejectAccepted(definition.id, definition);
1066
1240
  const commit = definition.commit ?? checkpoint;
1067
1241
  const outputs = definition.outputs ?? {};
1242
+ const stream = definition.frontier === true ? void 0 : definition.frontier;
1243
+ const params = definition.params ?? {};
1244
+ const frontier = validateFrontier(definition.frontier, {
1245
+ commit,
1246
+ params,
1247
+ outputs,
1248
+ inputTemplates: Array.map(Array.filter(Record.values(definition.inputs), isDeclaration), (input) => input.template)
1249
+ });
1250
+ if (frontier !== void 0 && (kind === "fold" || kind === "process")) throw new RangeError("frontier requires Projection.emit, Projection.mapAccum or Projection.mapAccumBatch");
1068
1251
  for (const output of Record.values(outputs)) {
1069
- validateGenerationParam(output, definition.params);
1252
+ validateGenerationParam(output, params);
1070
1253
  if (isPerGeneration(output) && generationBinding(output).routeBy !== void 0) {
1071
1254
  if (kind !== "process") throw new RangeError("Routed outputs require Projection.process");
1072
1255
  if (!supportsPrepare(commit)) throw new RangeError("Routed outputs require Commit.transaction");
1073
1256
  }
1074
1257
  }
1075
- validateAccepted(definition.accepted, definition.params, Array.map(Array.filter(Record.values(definition.inputs), isDeclaration), (input) => input.template), commit, Record.keys(outputs));
1076
1258
  if (definition.prepare !== void 0 && !supportsPrepare(commit)) throw new RangeError("prepare requires Commit.transaction");
1077
1259
  return declare(definition, ({ decoded, ...key }) => {
1078
1260
  const state = definition.state === void 0 ? void 0 : bindState(definition.state, decoded);
1079
1261
  const inputs = addressesOf(definition.inputs, decoded);
1080
- const { streams, accepted, generationOutputs, routed, handlerOutputs } = resolveOutputs(outputs, definition.accepted, decoded, key, inputs);
1262
+ const { streams, accepted, generationOutputs, routed, handlerOutputs } = resolveOutputs(outputs, stream, decoded, key, inputs);
1081
1263
  const bound = {
1082
1264
  ...key,
1083
1265
  inputs,
@@ -1090,7 +1272,17 @@ const build = (kind, definition) => {
1090
1272
  };
1091
1273
  if (generationOutputs.size > 0) Object.assign(bound, { [GenerationOutputs]: generationOutputs });
1092
1274
  if (routed.size > 0) Object.assign(bound, { [RoutedOutputs]: routed });
1275
+ if (frontier !== void 0) Object.assign(bound, { [FrontierOutputs]: frontier });
1093
1276
  return bound;
1277
+ }, {
1278
+ commit,
1279
+ ownedOutputs: supportsPrepare(commit) ? [...Array.map(Record.toEntries(outputs), ([name, output]) => ({
1280
+ name,
1281
+ stream: outputService(output)
1282
+ })), ...stream === void 0 ? [] : [{
1283
+ name: "frontier",
1284
+ stream: outputService(stream)
1285
+ }]] : []
1094
1286
  });
1095
1287
  };
1096
1288
  // src/fold.ts
@@ -1117,16 +1309,15 @@ function mapAccumBatch(definition) {
1117
1309
  * Deletes a live checkpoint and marks its routed outputs as forgotten so retirement
1118
1310
  * can still find them. Preserves retirement tombstones. Stop the follower first,
1119
1311
  * or use a new generation.
1120
- * Pass the binding from `declaration.at(params)` for a routed projection. A bare
1121
- * key deletes the checkpoint and leaves the route records live.
1312
+ * Pass the binding from `declaration.at(params)`, or `declaration.singleton`, for a
1313
+ * routed projection. A bare key deletes the checkpoint and leaves the route records live.
1122
1314
  * Delete stream outputs first, because forgetting restarts their producer sequences.
1123
1315
  */
1124
1316
  const forget = (projection) => Effect.gen(function* () {
1125
1317
  assertCheckpointKeyVersion(projection);
1126
1318
  if (projection.commit.remove === void 0) return yield* new ProjectionFault({
1127
1319
  phase: "checkpoint",
1128
- reason: "unsupported-composition",
1129
- message: "This Commit does not support forgetting"
1320
+ reason: new UnsupportedComposition({ message: "This Commit does not support forgetting" })
1130
1321
  });
1131
1322
  yield* projection.commit.remove(projection);
1132
1323
  return yield* Effect.void;
@@ -1177,10 +1368,10 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1177
1368
  const pending = before.record.pending;
1178
1369
  if (pending !== void 0 && !isPinned(projection.commit)) return yield* new ProjectionFault({
1179
1370
  phase: "load",
1180
- reason: "invalid-record",
1181
- message: `Commit ${projection.commit.name} cannot resume a pinned unit`
1371
+ reason: new InvalidRecord({ message: `Commit ${projection.commit.name} cannot resume a pinned unit` })
1182
1372
  });
1183
1373
  let batch;
1374
+ let counts;
1184
1375
  let count = 0;
1185
1376
  let due = pending?.due;
1186
1377
  let dueOnly = pending !== void 0 && due !== void 0 && Record.isEmptyRecord(pending.ranges);
@@ -1189,6 +1380,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1189
1380
  if (before.record.wakeAt <= now) due = before.record.wakeAt;
1190
1381
  }
1191
1382
  if (pending !== void 0) {
1383
+ counts = Record.map(pending.ranges, (range) => range.count);
1192
1384
  const slices = {};
1193
1385
  for (const [name, address] of inputEntries(projection.inputs)) {
1194
1386
  const range = pending.ranges[name];
@@ -1204,8 +1396,10 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1204
1396
  const read = yield* readInputs(projection.inputs, before.record.inputs, Option.isSome(before.loaded.record));
1205
1397
  batch = read.slices;
1206
1398
  count = read.items;
1399
+ counts = read.counts;
1207
1400
  const terminal = Array.some(Record.toEntries(batch), ([name, slice]) => slice.gone === true || slice.closed && slice.upToDate && !before.record.closed?.[name]);
1208
- if (count === 0 && !terminal && (due === void 0 || !allowEmptyDue)) return {
1401
+ const empty = Record.isEmptyRecord(counts);
1402
+ if (empty && !terminal && (due === void 0 || !allowEmptyDue)) return {
1209
1403
  status: Array.every(Record.values(batch), (slice) => slice.closed) ? "source-closed" : "caught-up",
1210
1404
  units: 0,
1211
1405
  items: 0,
@@ -1213,7 +1407,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1213
1407
  encoded: before.record.state,
1214
1408
  wakeAt: Option.fromUndefinedOr(before.record.wakeAt)
1215
1409
  };
1216
- dueOnly = count === 0 && !terminal;
1410
+ dueOnly = empty && !terminal;
1217
1411
  if (dueOnly) batch = Record.map(batch, (_slice, name) => emptySlice(before.record.inputs[name] ?? ""));
1218
1412
  }
1219
1413
  const gone = Array.some(Record.values(batch), (slice) => slice.gone === true);
@@ -1245,10 +1439,12 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1245
1439
  let prepared;
1246
1440
  let result;
1247
1441
  const run = Effect.suspend(() => projection.process(batch, unit, before.record.state, prepared, context?.attempt ?? 1)).pipe(Effect.map((value) => {
1248
- if (projection.accepted === void 0) return value;
1442
+ const frontier = frontierOutputs(projection);
1443
+ if (projection.accepted === void 0 && frontier === void 0) return value;
1249
1444
  const handled = value;
1250
- const output = acceptedOutput(projection.accepted, projection.inputs, unit, before.record.closed);
1251
- return acceptedResult(handled, output);
1445
+ const rows = unitFrontiers(projection.inputs, unit, batch, before.record.closed);
1446
+ const withFrontier = frontier === void 0 ? handled : frontierResult(handled, frontier, rows);
1447
+ return projection.accepted === void 0 ? withFrontier : frontierStreamResult(withFrontier, projection.accepted, rows);
1252
1448
  }), Effect.tap((value) => Effect.sync(() => {
1253
1449
  result = value;
1254
1450
  })), Effect.mapError((error) => new HandlerFailed({ error })));
@@ -1266,7 +1462,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1266
1462
  prepare,
1267
1463
  ranges: Record.fromEntries(Array.map(Record.toEntries(ranges), ([name, range]) => [name, {
1268
1464
  ...range,
1269
- count: batch[name]?.items.length ?? 0,
1465
+ count: counts[name] ?? 0,
1270
1466
  closed: batch[name]?.closed ?? false,
1271
1467
  upToDate: batch[name]?.upToDate ?? false
1272
1468
  }]))
@@ -1360,13 +1556,16 @@ const hint = Effect.fn("Projection.hint")(function* (input, address, offset, int
1360
1556
  const { wire: reader } = yield* address.stream;
1361
1557
  const storageFailure = (cause) => new ProjectionFault({
1362
1558
  phase: "read",
1363
- reason: "storage-failure",
1364
1559
  input,
1365
- message: `Cannot wait on ${address.id}`,
1366
- cause
1560
+ reason: cause
1561
+ });
1562
+ const from = yield* storedOffset(offset, {
1563
+ phase: "read",
1564
+ input,
1565
+ what: `The offset of ${input}`
1367
1566
  });
1368
1567
  return yield* reader.readNext(address.id, {
1369
- offset,
1568
+ offset: from,
1370
1569
  cursor
1371
1570
  }).pipe(Effect.tap((result) => Ref.update(cursors, (current) => ({
1372
1571
  ...current,
@@ -1374,18 +1573,18 @@ const hint = Effect.fn("Projection.hint")(function* (input, address, offset, int
1374
1573
  }))), Effect.flatMap((result) => result.closed && result.messages.length === 0 ? Effect.never : Effect.void), Effect.catchTags({
1375
1574
  InvalidReadRequest: (cause) => new ProjectionFault({
1376
1575
  phase: "read",
1377
- reason: "invalid-source",
1378
1576
  input,
1379
- message: cause.message,
1380
- cause
1577
+ reason: new InvalidSource({
1578
+ message: cause.message,
1579
+ cause
1580
+ })
1381
1581
  }),
1382
1582
  StreamNotFound: () => Effect.void,
1383
1583
  StreamGone: () => Effect.void,
1384
1584
  NotSupported: (error) => new ProjectionFault({
1385
1585
  phase: "read",
1386
- reason: "unsupported-composition",
1387
1586
  input,
1388
- message: `${address.id} does not support ${error.feature}`
1587
+ reason: new UnsupportedComposition({ message: `${address.id} does not support ${error.feature}` })
1389
1588
  }),
1390
1589
  StorageFault: storageFailure,
1391
1590
  TransportFault: storageFailure
@@ -1410,15 +1609,11 @@ const hint = Effect.fn("Projection.hint")(function* (input, address, offset, int
1410
1609
  const follow = (projection, options = {}) => Stream.unwrap(Effect.gen(function* () {
1411
1610
  yield* validateOptions(options);
1412
1611
  const interval = options.repairIntervalMs ?? 3e4;
1413
- if (!Number.isSafeInteger(interval) || interval <= 0) return yield* new ProjectionFault({
1414
- phase: "load",
1415
- reason: "invalid-options",
1416
- message: "repairIntervalMs must be a positive safe integer"
1417
- });
1612
+ if (!Number.isSafeInteger(interval) || interval <= 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection.follow option repairIntervalMs must be a positive safe integer, got ${String(interval)}`));
1418
1613
  const cursors = yield* Ref.make({});
1419
- const schedule = (options.retry ?? (yield* ProjectionRetry)).pipe(Schedule.tap(({ input }) => Schema.is(ProjectionFault)(input) && input.retryable ? Effect.logWarning("Projection.follow retry", input) : Effect.void));
1614
+ const schedule = (options.retry ?? (yield* ProjectionRetry)).pipe(Schedule.tap(({ input }) => Schema.is(ProjectionFault)(input) && input.isRetryable ? Effect.logWarning("Projection.follow retry", input) : Effect.void));
1420
1615
  const retrying = (effect) => Effect.retry(effect, {
1421
- while: (fault) => Schema.is(ProjectionFault)(fault) && fault.retryable,
1616
+ while: (fault) => Schema.is(ProjectionFault)(fault) && fault.isRetryable,
1422
1617
  schedule
1423
1618
  });
1424
1619
  const wake = (offsets) => Effect.raceAllFirst(Array.map(inputEntries(projection.inputs), ([name, address]) => hint(name, address, offsets[name] ?? ZERO_OFFSET, interval, cursors)));
@@ -1460,28 +1655,38 @@ const bindingDelay = (schedule, attempts) => Effect.gen(function* () {
1460
1655
  return Option.some(delay);
1461
1656
  }).pipe(Pull.catchDone(() => Effect.succeedNone), Effect.catchCause((cause) => Effect.logError("Projection binding retry schedule failed", cause).pipe(Effect.as(Option.none()))));
1462
1657
  // src/registry.ts
1658
+ /** A declaration, as opposed to one of its bindings. */
1659
+ const isDeclarationTarget = (target) => "singleton" in target || "at" in target;
1463
1660
  const RunnerEvent = Data.taggedEnum();
1464
- const registrations = /* @__PURE__ */ new WeakMap();
1465
1661
  /** Optional in-process view of Projection.attach runners. */
1466
- var Registry = class Registry extends Context.Service()("@streamsy/projection/Registry") {
1662
+ var Registry = class extends Context.Service()("@streamsy/projection/Registry") {
1467
1663
  /** Match a binding's projection id and encoded params, independent of key order. */
1468
1664
  static isFor = (binding) => (event) => event.projection === binding.id && Record.size(event.params) === Record.size(binding.params) && Array.every(Record.toEntries(binding.params), ([key, value]) => event.params[key] === value);
1469
- /** Provide below the attach layers so they see this same registry. */
1470
- static layer = Layer.effect(this, Effect.gen(function* () {
1471
- const runners = /* @__PURE__ */ new Map();
1472
- let registered = false;
1473
- const updates = yield* Effect.acquireRelease(PubSub.sliding(1), PubSub.shutdown);
1474
- const events = yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown);
1475
- const status = Effect.suspend(() => Effect.forEach(runners.values(), (runner) => runner.status));
1476
- const find = (target) => Effect.suspend(() => {
1477
- const id = Predicate.isString(target) ? target : target.id;
1478
- const found = Option.fromUndefinedOr(runners.get(id));
1479
- return Effect.fromOption(found).pipe(Effect.mapError(() => new NotAttached({ projection: id })));
1480
- });
1481
- const publish = PubSub.publish(updates, void 0).pipe(Effect.asVoid);
1482
- const snapshot = status.pipe(Effect.asSome, Effect.catch((fault) => Effect.logWarning("Projection.Registry changes snapshot failed", fault).pipe(Effect.as(Option.none()))));
1483
- const observations = Stream.fromPull(Effect.map(PubSub.subscribe(events), PubSub.takeAll)).pipe(Stream.scoped);
1484
- const registry = Registry.of({
1665
+ /**
1666
+ * The runners attached to the storage owner. The state lives on the owner, so this
1667
+ * layer can sit anywhere beside the attach layers, and building it twice is harmless.
1668
+ */
1669
+ static layer = Layer.effect(this, Effect.map(StorageOwner, (owner) => registrationOf(owner).registry));
1670
+ };
1671
+ /**
1672
+ * The runners attached to one storage owner and their observations. Every
1673
+ * `Registry.layer` over the owner is a view of this one state.
1674
+ */
1675
+ const RegistrySlot = new OwnerSlot(() => {
1676
+ const runners = /* @__PURE__ */ new Map();
1677
+ const updates = Effect.runSync(PubSub.sliding(1));
1678
+ const events = Effect.runSync(PubSub.unbounded());
1679
+ const status = Effect.suspend(() => Effect.forEach(runners.values(), (runner) => runner.status));
1680
+ const find = (target) => Effect.suspend(() => {
1681
+ const id = Predicate.isString(target) ? target : target.id;
1682
+ const found = Option.fromUndefinedOr(runners.get(id));
1683
+ return Effect.fromOption(found).pipe(Effect.mapError(() => new NotAttached({ projection: id })));
1684
+ });
1685
+ const publish = PubSub.publish(updates, void 0).pipe(Effect.asVoid);
1686
+ const snapshot = status.pipe(Effect.asSome, Effect.catch((fault) => Effect.logWarning("Projection.Registry changes snapshot failed", fault).pipe(Effect.as(Option.none()))));
1687
+ const observations = Stream.fromPull(Effect.map(PubSub.subscribe(events), PubSub.takeAll)).pipe(Stream.scoped);
1688
+ return {
1689
+ registry: Registry.of({
1485
1690
  status,
1486
1691
  events: observations,
1487
1692
  awaitOffset: Effect.fn("Projection.Registry.awaitOffset")(function* (binding, input, offset) {
@@ -1490,8 +1695,7 @@ var Registry = class Registry extends Context.Service()("@streamsy/projection/Re
1490
1695
  const runner = yield* find(binding);
1491
1696
  if (runner.generation !== binding.generation) return yield* new ProjectionFault({
1492
1697
  phase: "load",
1493
- reason: "identity-mismatch",
1494
- message: `Attached generation of ${binding.id} is ${runner.generation}, but the binding uses generation ${binding.generation}`
1698
+ reason: new GenerationMismatch({ message: `Attached generation of ${binding.id} is ${runner.generation}, but the binding uses generation ${binding.generation}` })
1495
1699
  });
1496
1700
  const pull = yield* Stream.toPull(observations);
1497
1701
  const checkpoint = yield* read(binding);
@@ -1516,40 +1720,39 @@ var Registry = class Registry extends Context.Service()("@streamsy/projection/Re
1516
1720
  failed: Effect.fn("Projection.Registry.failed")(function* (target, options = {}) {
1517
1721
  const limit = options.limit ?? 100;
1518
1722
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) return yield* Effect.die(/* @__PURE__ */ new RangeError("failed limit must be an integer from 1 to 1,000"));
1519
- return yield* (yield* find(target)).failed(limit, Predicate.isString(target) || "at" in target ? void 0 : target);
1723
+ return yield* (yield* find(target)).failed(limit, Predicate.isString(target) || isDeclarationTarget(target) ? void 0 : target);
1520
1724
  }),
1521
1725
  retry: Effect.fn("Projection.Registry.retry")(function* (target) {
1522
- return yield* (yield* find(target)).retry(Predicate.isString(target) || "at" in target ? void 0 : target);
1726
+ return yield* (yield* find(target)).retry(Predicate.isString(target) || isDeclarationTarget(target) ? void 0 : target);
1523
1727
  }),
1524
1728
  changes: Stream.unwrap(Effect.gen(function* () {
1525
1729
  const subscription = yield* PubSub.subscribe(updates);
1526
1730
  return Stream.concat(Stream.fromEffect(snapshot), Stream.fromSubscription(subscription).pipe(Stream.mapEffect(() => snapshot))).pipe(Stream.filterMap((value) => Result.fromOption(value, () => void 0)));
1527
1731
  }))
1528
- });
1529
- registrations.set(registry, {
1530
- publish,
1531
- event: (event) => PubSub.publish(events, event).pipe(Effect.asVoid),
1532
- register: (runner) => Effect.acquireRelease(Effect.sync(() => {
1533
- registered = true;
1534
- if (runners.has(runner.id)) throw new RangeError(`Projection ${runner.id} is already attached to this registry`);
1535
- runners.set(runner.id, runner);
1536
- }).pipe(Effect.andThen(publish)), () => Effect.sync(() => {
1537
- runners.delete(runner.id);
1538
- }).pipe(Effect.andThen(publish))).pipe(Effect.asVoid)
1539
- });
1540
- yield* Effect.addFinalizer(() => registered ? Effect.void : Effect.logDebug("Projection.Registry closed without any runner registrations; provide Registry.layer below the attach layers"));
1541
- return registry;
1542
- }));
1543
- };
1544
- /** @internal The event publisher installed by Registry.layer. */
1545
- const eventPublisher = (registry) => registrations.get(registry)?.event;
1732
+ }),
1733
+ publish,
1734
+ event: (event) => PubSub.publish(events, event).pipe(Effect.asVoid),
1735
+ register: (runner) => Effect.acquireRelease(Effect.sync(() => {
1736
+ if (runners.has(runner.id)) throw new RangeError(`Projection ${runner.id} is already attached to this registry`);
1737
+ runners.set(runner.id, runner);
1738
+ }).pipe(Effect.andThen(publish)), () => Effect.sync(() => {
1739
+ runners.delete(runner.id);
1740
+ }).pipe(Effect.andThen(publish))).pipe(Effect.asVoid)
1741
+ };
1742
+ });
1743
+ /** @internal The registry state of a storage owner. */
1744
+ const registrationOf = (owner) => ownerParts(owner).slot(RegistrySlot);
1546
1745
  /** @internal Register in the attach scope and return its pass notification. */
1547
- const registerRunner = (registry, runner) => {
1548
- const registration = registrations.get(registry);
1549
- return registration === void 0 ? Effect.die(/* @__PURE__ */ new Error("Projection runners require Registry.layer; a hand-built Registry has no registration support")) : registration.register(runner).pipe(Effect.as(registration.publish));
1746
+ const registerRunner = (owner, runner) => {
1747
+ const registration = registrationOf(owner);
1748
+ return registration.register(runner).pipe(Effect.as(registration.publish));
1550
1749
  };
1551
1750
  // src/failure.ts
1552
- const nonRetryableHandlerReason = "non-retryable-handler";
1751
+ /** The stored mark reason of a binding that a non-retryable handler error stopped. */
1752
+ const nonRetryableHandlerReason = "NonRetryableHandler";
1753
+ const isMarkReason = Schema.is(Schema.Union([ProjectionFaultReasonTag, Schema.Literal(nonRetryableHandlerReason)]));
1754
+ /** A stored reason from an older release, such as `token-conflict`, reads as no reason. */
1755
+ const knownMarkReason = (reason) => Option.filter(reason, isMarkReason);
1553
1756
  const marked = (reason) => Cause.isFailReason(reason) && Predicate.hasProperty(reason.error, NonRetryable) && reason.error[NonRetryable] === true;
1554
1757
  const hasNonRetryableHandler = (cause) => Array.some(cause.reasons, marked);
1555
1758
  /** Unknown handler errors and defects retry; only a known non-retryable fault stops work. */
@@ -1557,57 +1760,48 @@ const retryable = (cause) => !Array.some(cause.reasons, (reason) => {
1557
1760
  if (!Cause.isFailReason(reason)) return false;
1558
1761
  const { error } = reason;
1559
1762
  if (marked(reason)) return true;
1560
- return (Schema.is(ProjectionFault)(error) || Schema.is(StorageFault)(error)) && !error.retryable;
1763
+ return (Schema.is(ProjectionFault)(error) || Schema.is(StorageFault)(error)) && !error.isRetryable;
1561
1764
  });
1562
1765
  const runnerFailure = (cause, at) => ({
1563
1766
  at,
1564
- retryable: retryable(cause),
1565
- reason: Cause.findErrorOption(cause).pipe(Option.filter(Schema.is(ProjectionFault)), Option.map((fault) => fault.reason)),
1767
+ isRetryable: retryable(cause),
1768
+ reason: Cause.findErrorOption(cause).pipe(Option.filter(Schema.is(ProjectionFault)), Option.map((fault) => fault.reason._tag)),
1566
1769
  message: Cause.pretty(cause).slice(0, 1e3)
1567
1770
  });
1568
- // src/storage-fault.ts
1569
- /** Preserve SQL retryability at the runner's storage boundary. */
1570
- const storageFault = (operation) => (cause) => new StorageFault({
1571
- operation,
1572
- message: cause.message,
1573
- retryable: cause.isRetryable,
1574
- cause
1575
- });
1576
1771
  // src/triggers.ts
1577
1772
  const DEFAULT_LIMIT$1 = 1e3;
1578
- const decodeWakeMessage = Schema.decodeEffect(Schema.fromJsonString(Streamsy.WakeMessage));
1773
+ const decodeFrontierMessage = Schema.decodeEffect(Schema.fromJsonString(Streamsy.FrontierMessage));
1579
1774
  const decoder = new TextDecoder();
1580
1775
  const invalid = (id, message, cause) => new ProjectionFault({
1581
1776
  phase: "read",
1582
- reason: "invalid-source",
1583
- message: `${message}: ${id}`,
1584
- cause
1777
+ reason: new InvalidSource({
1778
+ message: `${message}: ${id}`,
1779
+ cause
1780
+ })
1781
+ });
1782
+ const undecodable = (id, message, cause) => new ProjectionFault({
1783
+ phase: "read",
1784
+ reason: new DecodeFault({
1785
+ message: `${message}: ${id}`,
1786
+ cause
1787
+ })
1585
1788
  });
1586
1789
  /** Persistent local ingestion on both hosts; process hosts also ingest and follow other owners. */
1587
1790
  const triggersOf = (projection, generation, declarations, match, marks, host = "process") => Effect.gen(function* () {
1588
- const storage = yield* Storage;
1589
- const records = yield* Effect.serviceOption(OwnerRecords);
1590
- const boundary = yield* Effect.serviceOption(CommitBoundary);
1591
- if (Option.isNone(records) || Option.isNone(boundary)) return yield* Effect.die(/* @__PURE__ */ new Error(`Projection ${projection} cannot attach triggers: use a local memory or SQL storage layer.`));
1592
- const owner = records.value;
1593
- const transaction = boundary.value;
1791
+ const transaction = yield* StorageOwner;
1792
+ const { storage, records: owner } = ownerParts(transaction);
1594
1793
  const permit = yield* Semaphore.make(1);
1595
1794
  const cursors = /* @__PURE__ */ new Map();
1596
1795
  const stopped = /* @__PURE__ */ new Map();
1597
1796
  const streams = /* @__PURE__ */ new Map();
1598
1797
  const remote = /* @__PURE__ */ new Map();
1599
- const isRemote = (service) => Option.isSome(service) && !Array.some([
1600
- storage,
1601
- owner,
1602
- transaction
1603
- ], (local) => service.value.owner === ownerOf(local));
1604
1798
  for (const declaration of declarations) {
1605
1799
  const { id } = declaration.address({});
1606
- const service = yield* Effect.serviceOption(declaration);
1607
- if (Option.isSome(service) && isRemote(service)) {
1800
+ const service = yield* Effect.service(declaration);
1801
+ if (service.owner !== transaction.id) {
1608
1802
  if (host === "wakeup") return yield* Effect.die(/* @__PURE__ */ new RangeError(`Trigger ${id}: ProjectionWakeup.attach accepts only triggers on its own storage owner`));
1609
1803
  remote.set(id, {
1610
- wire: service.value.wire,
1804
+ wire: service.wire,
1611
1805
  ahead: true,
1612
1806
  changed: yield* Deferred.make()
1613
1807
  });
@@ -1628,9 +1822,9 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
1628
1822
  const cached = cursors.get(key);
1629
1823
  if (cached !== void 0) return cached;
1630
1824
  const saved = yield* owner.read(key);
1631
- const from = Option.isNone(saved) ? Offset.make(ZERO_OFFSET) : yield* Schema.decodeEffect(Offset)(saved.value).pipe(Effect.mapError((cause) => new StorageFault({
1825
+ const from = Option.isNone(saved) ? StreamsyOffset.make(ZERO_OFFSET) : yield* Schema.decodeEffect(StreamsyOffset)(saved.value).pipe(Effect.mapError((cause) => new StorageFault({
1632
1826
  operation: "projection.trigger.cursor",
1633
- retryable: false,
1827
+ isRetryable: false,
1634
1828
  message: `Invalid trigger cursor for ${projection}`,
1635
1829
  cause
1636
1830
  })));
@@ -1662,14 +1856,15 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
1662
1856
  limit: DEFAULT_LIMIT$1
1663
1857
  });
1664
1858
  for (const message of messages) {
1665
- const event = yield* decodeWakeMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => new ProjectionFault({
1859
+ const event = yield* decodeFrontierMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => new ProjectionFault({
1666
1860
  phase: "read",
1667
- reason: "invalid-source",
1668
- message: `Cannot decode trigger ${id} at offset ${message.offset}`,
1669
- cause
1861
+ reason: new DecodeFault({
1862
+ message: `Cannot decode trigger ${id} at offset ${message.offset}`,
1863
+ cause
1864
+ })
1670
1865
  })));
1671
- if (!StreamAddress.isChange(event)) continue;
1672
- const binding = match(StreamAddress.isUpsert(event) ? event.value.stream : StreamId.make(event.key));
1866
+ if (!DurableState.isChange(event)) continue;
1867
+ const binding = match(StreamId.make(DurableState.isUpsert(event) ? event.value.stream : event.key));
1673
1868
  if (Option.isSome(binding)) found.add(binding.value[0]);
1674
1869
  else yield* Effect.logWarning(`Projection ${projection} skipped unmatched trigger source ${event.key} from ${id}`);
1675
1870
  }
@@ -1700,13 +1895,13 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
1700
1895
  InvalidReadRequest: (cause) => Effect.fail(invalid(id, "Invalid trigger read", cause)),
1701
1896
  TransportFault: (cause) => Effect.fail(new StorageFault({
1702
1897
  operation: "projection.triggers.remote",
1703
- retryable: true,
1898
+ isRetryable: true,
1704
1899
  message: `Cannot read remote trigger ${id}`,
1705
1900
  cause
1706
1901
  })),
1707
1902
  StorageFault: (cause) => Effect.fail(new StorageFault({
1708
1903
  operation: "projection.triggers.remote",
1709
- retryable: true,
1904
+ isRetryable: true,
1710
1905
  message: `Cannot read remote trigger ${id}`,
1711
1906
  cause
1712
1907
  }))
@@ -1716,12 +1911,12 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
1716
1911
  return;
1717
1912
  }
1718
1913
  const result = page.value;
1719
- const offset = yield* Schema.decodeEffect(Offset)(result.nextOffset).pipe(Effect.mapError((cause) => invalid(id, "Invalid trigger page cursor", cause)));
1914
+ const offset = yield* Schema.decodeEffect(StreamsyOffset)(result.nextOffset).pipe(Effect.mapError((cause) => undecodable(id, "Invalid trigger page cursor", cause)));
1720
1915
  const found = /* @__PURE__ */ new Set();
1721
1916
  for (const message of result.messages) {
1722
- const event = yield* decodeWakeMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => invalid(id, `Cannot decode trigger page after ${from}`, cause)));
1723
- if (!StreamAddress.isChange(event)) continue;
1724
- const binding = match(StreamAddress.isUpsert(event) ? event.value.stream : StreamId.make(event.key));
1917
+ const event = yield* decodeFrontierMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => undecodable(id, `Cannot decode trigger page after ${from}`, cause)));
1918
+ if (!DurableState.isChange(event)) continue;
1919
+ const binding = match(StreamId.make(DurableState.isUpsert(event) ? event.value.stream : event.key));
1725
1920
  if (Option.isSome(binding)) found.add(binding.value[0]);
1726
1921
  else yield* Effect.logWarning(`Projection ${projection} skipped unmatched trigger source ${event.key} from ${id}`);
1727
1922
  }
@@ -1798,8 +1993,8 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
1798
1993
  const rescan = (id) => permit.withPermit(Effect.gen(function* () {
1799
1994
  const key = streams.get(StreamId.make(id));
1800
1995
  if (key === void 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection ${projection} has no trigger ${id}`));
1801
- yield* transaction.withTransaction(owner.write(key, ZERO_OFFSET)).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(storageFault("projection.triggers.rescan")(cause))), Effect.tap(() => Effect.sync(() => {
1802
- cursors.set(key, Offset.make(ZERO_OFFSET));
1996
+ yield* transaction.withTransaction(owner.write(key, ZERO_OFFSET)).pipe(Effect.tap(() => Effect.sync(() => {
1997
+ cursors.set(key, StreamsyOffset.make(ZERO_OFFSET));
1803
1998
  stopped.delete(id);
1804
1999
  const state = remote.get(StreamId.make(id));
1805
2000
  if (state !== void 0) state.ahead = true;
@@ -1836,44 +2031,46 @@ const Tail = Schema.Struct({
1836
2031
  });
1837
2032
  /** A serializable vector of fixed source tails, keyed by input name. */
1838
2033
  const Tails = Schema.Record(Schema.String, Tail);
1839
- const isOffset = Schema.is(Offset);
2034
+ const isOffset = Schema.is(StreamsyOffset);
1840
2035
  const historyUnavailable = (input, message, cause) => new ProjectionFault({
1841
2036
  phase: "read",
1842
- reason: "history-unavailable",
1843
2037
  input,
1844
- message,
1845
- cause
2038
+ reason: new HistoryUnavailable({
2039
+ message,
2040
+ cause
2041
+ })
1846
2042
  });
1847
- const head$1 = Effect.fn("Projection.catchUp.head")(function* (name, address) {
2043
+ const head = Effect.fn("Projection.catchUp.head")(function* (name, address) {
1848
2044
  const { wire } = yield* address.stream;
1849
2045
  const storageFailure = (cause) => new ProjectionFault({
1850
2046
  phase: "read",
1851
- reason: "storage-failure",
1852
2047
  input: name,
1853
- message: `Cannot read the head of ${address.id}`,
1854
- cause
2048
+ reason: cause
1855
2049
  });
1856
2050
  const result = yield* wire.head(address.id).pipe(Effect.catchTags({
1857
- StreamNotFound: (cause) => historyUnavailable(name, `Input stream ${address.id} is missing`, cause),
2051
+ StreamNotFound: (cause) => new ProjectionFault({
2052
+ phase: "read",
2053
+ input: name,
2054
+ reason: inputNotFound(address.id, cause)
2055
+ }),
1858
2056
  StreamGone: (cause) => historyUnavailable(name, `Input stream ${address.id} is gone`, cause),
1859
2057
  StorageFault: storageFailure,
1860
2058
  TransportFault: storageFailure
1861
2059
  }));
1862
- if (!isOffset(result.nextOffset)) return yield* new ProjectionFault({
2060
+ if (!isOffset(result.offset)) return yield* new ProjectionFault({
1863
2061
  phase: "read",
1864
- reason: "invalid-source",
1865
2062
  input: name,
1866
- message: `Head of ${address.id} has an invalid offset`
2063
+ reason: new InvalidSource({ message: `Head of ${address.id} has an invalid offset` })
1867
2064
  });
1868
2065
  return {
1869
2066
  stream: address.id,
1870
- offset: result.nextOffset,
2067
+ offset: result.offset,
1871
2068
  closed: result.closed
1872
2069
  };
1873
2070
  });
1874
2071
  /** Capture each resolved input head once. The vector can be reused while producers keep writing. */
1875
2072
  const tails = Effect.fn("Projection.tails")(function* (projection) {
1876
- const entries = yield* Effect.forEach(inputEntries(projection.inputs), ([name, address]) => head$1(name, address).pipe(Effect.map((value) => [name, value])));
2073
+ const entries = yield* Effect.forEach(inputEntries(projection.inputs), ([name, address]) => head(name, address).pipe(Effect.map((value) => [name, value])));
1877
2074
  return Record.fromEntries(entries);
1878
2075
  });
1879
2076
  const validateTails = Effect.fnUntraced(function* (projection, targets) {
@@ -1882,20 +2079,19 @@ const validateTails = Effect.fnUntraced(function* (projection, targets) {
1882
2079
  reportInput: true
1883
2080
  })(targets).pipe(Effect.mapError((cause) => new ProjectionFault({
1884
2081
  phase: "load",
1885
- reason: "invalid-options",
1886
- message: `Invalid tails for ${projection.id}: ${cause.message}`,
1887
- cause
2082
+ reason: new DecodeFault({
2083
+ message: `Invalid tails for ${projection.id}: ${cause.message}`,
2084
+ cause
2085
+ })
1888
2086
  })));
1889
2087
  for (const [name, address] of inputEntries(projection.inputs)) if (decoded[name]?.stream !== address.id) return yield* new ProjectionFault({
1890
2088
  phase: "load",
1891
- reason: "identity-mismatch",
1892
2089
  input: name,
1893
- message: `Tail for ${name} must name stream ${address.id}`
2090
+ reason: new IdentityMismatch({ message: `Tail for ${name} must name stream ${address.id}` })
1894
2091
  });
1895
2092
  if (Record.size(decoded) !== Record.size(projection.inputs)) return yield* new ProjectionFault({
1896
2093
  phase: "load",
1897
- reason: "identity-mismatch",
1898
- message: `Tail input names differ from the declaration of ${projection.id}`
2094
+ reason: new IdentityMismatch({ message: `Tail input names differ from the declaration of ${projection.id}` })
1899
2095
  });
1900
2096
  return decoded;
1901
2097
  });
@@ -1903,20 +2099,18 @@ const measure = Effect.fnUntraced(function* (projection, targets, verifyHeads) {
1903
2099
  const { record } = yield* restore(projection, projection.commit);
1904
2100
  if (record.ended) return yield* new ProjectionFault({
1905
2101
  phase: "load",
1906
- reason: "history-unavailable",
1907
- message: `Binding of ${projection.id} ended after an input was lost`
2102
+ reason: new HistoryUnavailable({ message: `Binding of ${projection.id} ended after an input was lost` })
1908
2103
  });
1909
2104
  const entries = yield* Effect.forEach(inputEntries(projection.inputs), Effect.fnUntraced(function* ([name, address]) {
1910
2105
  const committed = record.inputs[name];
1911
2106
  const target = targets[name];
1912
2107
  if (!isOffset(committed)) return yield* new ProjectionFault({
1913
2108
  phase: "load",
1914
- reason: "invalid-record",
1915
2109
  input: name,
1916
- message: `Stored offset for ${name} is not a valid offset`
2110
+ reason: new InvalidRecord({ message: `Stored offset for ${name} is not a valid offset` })
1917
2111
  });
1918
2112
  if (verifyHeads) {
1919
- const current = yield* head$1(name, address);
2113
+ const current = yield* head(name, address);
1920
2114
  const order = compare(current.offset, target.offset);
1921
2115
  if (order < 0 || target.closed && (!current.closed || order !== 0)) return yield* historyUnavailable(name, `Head of ${address.id} no longer contains its tail`);
1922
2116
  }
@@ -1967,7 +2161,7 @@ const matcher = (declaration) => {
1967
2161
  if (missing.length > 0) throw new RangeError(`Projection ${declaration.id} cannot attach: input ${name} does not give param ${Array.join(missing, ", ")}`);
1968
2162
  }
1969
2163
  const bound = (params) => {
1970
- const binding = declaration.at(params);
2164
+ const binding = bindDeclaration(declaration, params);
1971
2165
  return Option.some([canonicalParams(binding.params), binding]);
1972
2166
  };
1973
2167
  return (id) => {
@@ -1999,15 +2193,14 @@ const bindingOf = (declaration, key) => Option.flatMap(Schema.decodeOption(Param
1999
2193
  decoded[name] = result.value;
2000
2194
  }
2001
2195
  try {
2002
- const binding = declaration.at(decoded);
2196
+ const binding = bindDeclaration(declaration, decoded);
2003
2197
  return canonicalParams(binding.params) === key ? Option.some(binding) : Option.none();
2004
2198
  } catch {
2005
2199
  return Option.none();
2006
2200
  }
2007
2201
  });
2008
2202
  const startupInventory = Effect.fn("Projection.startupInventory")(function* (declaration) {
2009
- const store = yield* Effect.serviceOption(CheckpointStore);
2010
- const list = Option.getOrUndefined(store)?.list;
2203
+ const list = declaredOf(declaration)?.commit.list;
2011
2204
  const id = declaration.id;
2012
2205
  return yield* Effect.gen(function* () {
2013
2206
  if (list === void 0) return [];
@@ -2023,7 +2216,7 @@ const startupInventory = Effect.fn("Projection.startupInventory")(function* (dec
2023
2216
  else yield* Effect.logWarning(`Projection ${id} skipped startup params ${key}: they no longer decode`);
2024
2217
  }
2025
2218
  return candidates;
2026
- }).pipe(Effect.catchIf((fault) => fault.reason === "unsupported-composition" || fault.reason === "invalid-record", (fault) => Effect.logWarning(`Projection ${id} skipped startup inventory: ${fault.message}. Supply attach bindings explicitly.`).pipe(Effect.as([]))));
2219
+ }).pipe(Effect.catchIf((fault) => Predicate.isTagged(fault.reason, "UnsupportedComposition") || Predicate.isTagged(fault.reason, "InvalidRecord"), (fault) => Effect.logWarning(`Projection ${id} skipped startup inventory: ${fault.message}. Supply attach bindings explicitly.`).pipe(Effect.as([]))));
2027
2220
  });
2028
2221
  /**
2029
2222
  * A binding that faults with `history-unavailable` on an input whose head is
@@ -2032,7 +2225,7 @@ const startupInventory = Effect.fn("Projection.startupInventory")(function* (dec
2032
2225
  * with no checkpoint reaches here. Any other head answer keeps the fault.
2033
2226
  */
2034
2227
  const sourceGone = (inputs, cause) => Effect.gen(function* () {
2035
- const fault = Cause.findErrorOption(cause).pipe(Option.filter((error) => Schema.is(ProjectionFault)(error) && error.reason === "history-unavailable"));
2228
+ const fault = Cause.findErrorOption(cause).pipe(Option.filter((error) => Schema.is(ProjectionFault)(error) && isInputLoss(error)));
2036
2229
  if (Option.isNone(fault) || fault.value.input === void 0) return false;
2037
2230
  const input = fault.value.input;
2038
2231
  const address = Array.findFirst(inputEntries(inputs), ([name]) => name === input);
@@ -2043,25 +2236,24 @@ const sourceGone = (inputs, cause) => Effect.gen(function* () {
2043
2236
  StreamGone: () => Effect.succeed(true)
2044
2237
  }), Effect.orElseSucceed(() => false));
2045
2238
  });
2046
- /**
2047
- * Register the commit hook that marks each binding a transaction writes, in
2048
- * that transaction. Dies when the storage layer has no marks, for example
2049
- * over remote storage.
2050
- */
2051
- const durableMarks = (projection, match, marks) => Effect.gen(function* () {
2052
- const hooks = yield* Effect.serviceOption(CommitHooks);
2053
- if (Option.isNone(hooks) || Option.isNone(marks)) return yield* Effect.die(/* @__PURE__ */ new Error(`Projection ${projection} cannot attach durably: the storage layer keeps no projection marks. Use a local memory or SQL storage layer, or pass durable: false.`));
2054
- yield* hooks.value.beforeCommit((ids) => {
2239
+ /** Register the commit hook that marks each binding a transaction writes, in that transaction. */
2240
+ const durableMarks = (projection, match, owner) => Effect.gen(function* () {
2241
+ yield* owner.hooks.beforeCommit((ids) => {
2055
2242
  const keys = /* @__PURE__ */ new Set();
2056
2243
  for (const id of ids) {
2057
2244
  const found = match(id);
2058
2245
  if (Option.isSome(found)) keys.add(found.value[0]);
2059
2246
  }
2060
- return keys.size === 0 ? Effect.void : marks.value.mark(projection, [...keys]);
2247
+ return keys.size === 0 ? Effect.void : owner.marks.mark(projection, [...keys]);
2061
2248
  });
2062
- return marks.value;
2249
+ return owner.marks;
2063
2250
  });
2064
2251
  /**
2252
+ * A transactional output on another storage owner can never commit. Check each declared
2253
+ * output once at layer build, so the app does not start with that wiring.
2254
+ */
2255
+ const checkOwnedOutputs = (projection, owner, outputs) => Effect.forEach(outputs, ({ name, stream }) => Effect.flatMap(stream, (service) => service.owner === owner ? Effect.void : Effect.die(foreignOutput(projection, name, owner, service.owner))), { discard: true });
2256
+ /**
2065
2257
  * One scoped commit subscription and pending set, shared by the two host
2066
2258
  * adapters. The subscription exists when this effect returns, so a commit
2067
2259
  * after that point always marks its binding.
@@ -2085,16 +2277,15 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
2085
2277
  if (!Number.isSafeInteger(concurrency) || concurrency <= 0) throw new RangeError("Projection.attach concurrency must be a positive safe integer");
2086
2278
  const match = matcher(declaration);
2087
2279
  return Effect.gen(function* () {
2088
- const storage = yield* Storage;
2089
- const storedMarks = durable ? yield* Effect.serviceOption(ProjectionMarks) : Option.none();
2090
- const maxIdLength = Option.getOrUndefined(storedMarks)?.maxProjectionIdLength;
2280
+ const storage = yield* StorageOwner;
2281
+ const parts = ownerParts(storage);
2282
+ const maxIdLength = durable ? parts.marks.maxProjectionIdLength : void 0;
2091
2283
  if (maxIdLength !== void 0 && Array.fromIterable(declaration.id).length > maxIdLength) return yield* Effect.die(new StorageFault({
2092
2284
  operation: "projection.attach",
2093
2285
  message: `MySQL projection id must be at most ${maxIdLength} characters`,
2094
- retryable: false
2286
+ isRetryable: false
2095
2287
  }));
2096
- const registry = yield* Effect.serviceOption(Registry);
2097
- const publish = Option.isSome(registry) ? eventPublisher(registry.value) : void 0;
2288
+ const publish = registrationOf(storage).event;
2098
2289
  const committed = yield* storage.committed;
2099
2290
  const pending = /* @__PURE__ */ new Map();
2100
2291
  const working = /* @__PURE__ */ new Set();
@@ -2106,8 +2297,7 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
2106
2297
  const runActive = (binding, context) => Effect.acquireUseRelease(Effect.sync(() => {
2107
2298
  active += 1;
2108
2299
  }), () => {
2109
- const running = catchUp(binding, { limit }, context).pipe(Effect.flatMap((cycle) => progressOf(binding, cycle)));
2110
- return publish === void 0 ? running : running.pipe(Effect.tap((progress) => publish(RunnerEvent.Ran({
2300
+ return catchUp(binding, { limit }, context).pipe(Effect.flatMap((cycle) => progressOf(binding, cycle))).pipe(Effect.tap((progress) => publish(RunnerEvent.Ran({
2111
2301
  projection: declaration.id,
2112
2302
  params: binding.params,
2113
2303
  status: progress.status,
@@ -2118,7 +2308,8 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
2118
2308
  }, () => Effect.sync(() => {
2119
2309
  active -= 1;
2120
2310
  }));
2121
- const marks = durable ? yield* durableMarks(declaration.id, match, storedMarks) : memoryProjectionMarks();
2311
+ yield* checkOwnedOutputs(declaration.id, storage.id, declaredOf(declaration)?.ownedOutputs ?? []);
2312
+ const marks = durable ? yield* durableMarks(declaration.id, match, parts) : memoryProjectionMarks();
2122
2313
  let failure = Option.none();
2123
2314
  let started = false;
2124
2315
  const startPermit = yield* Semaphore.make(1);
@@ -2132,17 +2323,21 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
2132
2323
  return true;
2133
2324
  });
2134
2325
  const seed = Effect.gen(function* () {
2135
- const candidates = options.bindings === void 0 ? yield* startupInventory(declaration) : yield* options.bindings.pipe(Effect.map(Array.map((params) => declaration.at(params))), Effect.catch((error) => Effect.logError(`Projection ${declaration.id} skipped startup replay: the bindings option failed`, error).pipe(Effect.as([]))));
2326
+ const candidates = options.bindings === void 0 ? yield* startupInventory(declaration) : yield* options.bindings.pipe(Effect.map(Array.map((params) => bindDeclaration(declaration, params))), Effect.catch((error) => Effect.logError(`Projection ${declaration.id} skipped startup replay: the bindings option failed`, error).pipe(Effect.as([]))));
2136
2327
  const byKey = new Map(Array.map(candidates, (binding) => [canonicalParams(binding.params), binding]));
2137
2328
  for (const chunk of Array.chunksOf([...byKey], SCHEDULE_CHUNK)) {
2138
2329
  const keys = [];
2139
- for (const [key, binding] of chunk) if (yield* prepare(binding).pipe(Effect.catchIf((fault) => fault.reason === "retired-generation" || fault.reason === "history-unavailable", () => Effect.succeed(false)))) keys.push(key);
2330
+ for (const [key, binding] of chunk) if (yield* prepare(binding).pipe(Effect.catchReasons("ProjectionFault", {
2331
+ RetiredGeneration: () => Effect.succeed(false),
2332
+ HistoryUnavailable: () => Effect.succeed(false),
2333
+ InputNotFound: () => Effect.succeed(false)
2334
+ }))) keys.push(key);
2140
2335
  if (keys.length > 0) yield* marks.mark(declaration.id, keys).pipe(Effect.mapError(storageFault("marks.mark")));
2141
2336
  }
2142
2337
  }).pipe(Effect.mapError((cause) => new StorageFault({
2143
2338
  operation: "projection.startup",
2144
2339
  message: `Cannot queue startup replay for ${declaration.id}`,
2145
- retryable: retryable(Cause.fail(cause)),
2340
+ isRetryable: retryable(Cause.fail(cause)),
2146
2341
  cause
2147
2342
  })));
2148
2343
  const start = startPermit.withPermit(Effect.gen(function* () {
@@ -2189,7 +2384,7 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
2189
2384
  if (pending.size > 0 || triggers !== void 0 && (triggers.retrying() || (yield* triggers.next))) return void 0;
2190
2385
  return yield* waitDue;
2191
2386
  });
2192
- const dropped = (key, binding) => Effect.logWarning(`Projection ${declaration.id} dropped binding ${key}: its source was removed before its first run`).pipe(Effect.andThen(publish === void 0 ? Effect.void : publish(RunnerEvent.Dropped({
2387
+ const dropped = (key, binding) => Effect.logWarning(`Projection ${declaration.id} dropped binding ${key}: its source was removed before its first run`).pipe(Effect.andThen(publish(RunnerEvent.Dropped({
2193
2388
  projection: declaration.id,
2194
2389
  params: binding.params
2195
2390
  }))));
@@ -2243,8 +2438,8 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
2243
2438
  const attempts = (state?.attempts ?? 0) + 1;
2244
2439
  const failed = runnerFailure(exit.cause, yield* Clock.currentTimeMillis);
2245
2440
  const budgetEnded = attempts >= (declaration.retry?.maxAttempts ?? Number.POSITIVE_INFINITY);
2246
- const delay = !failed.retryable || budgetEnded ? Option.none() : yield* bindingDelay(declaration.retry?.schedule, attempts);
2247
- if (failed.retryable && Option.isNone(delay) && declaration.retry?.onExhausted !== void 0) {
2441
+ const delay = !failed.isRetryable || budgetEnded ? Option.none() : yield* bindingDelay(declaration.retry?.schedule, attempts);
2442
+ if (failed.isRetryable && Option.isNone(delay) && declaration.retry?.onExhausted !== void 0) {
2248
2443
  const hook = declaration.retry.onExhausted;
2249
2444
  const failedUnit = unit;
2250
2445
  if (failedUnit === void 0) yield* Effect.logWarning(`Projection ${id} binding ${key} exhausted; skipped onExhausted because no unit formed`);
@@ -2263,7 +2458,7 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
2263
2458
  reason
2264
2459
  }
2265
2460
  });
2266
- if (publish !== void 0) yield* publish(RunnerEvent.Failed({
2461
+ yield* publish(RunnerEvent.Failed({
2267
2462
  projection: id,
2268
2463
  params: binding.params,
2269
2464
  attempts,
@@ -2338,15 +2533,18 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
2338
2533
  return {
2339
2534
  params: yield* Schema.decodeEffect(ParamsJson)(row.params).pipe(Effect.mapError((cause) => new StorageFault({
2340
2535
  operation: "marks.failed",
2341
- retryable: false,
2536
+ isRetryable: false,
2342
2537
  message: "Invalid stored binding params",
2343
2538
  cause
2344
2539
  }))),
2345
2540
  attempts: row.attempts,
2346
2541
  dueAt: row.stopped ? Option.none() : Option.some(row.dueAt),
2347
2542
  stopped: row.stopped,
2348
- exhausted: row.stopped && !Option.contains(Option.flatMap(row.failure, (failed) => failed.reason), "non-retryable-handler") && (row.attempts >= (declaration.retry?.maxAttempts ?? Number.POSITIVE_INFINITY) || Option.isNone(yield* bindingDelay(declaration.retry?.schedule, row.attempts))),
2349
- failure: row.failure
2543
+ exhausted: row.stopped && !Option.contains(Option.flatMap(row.failure, (failed) => knownMarkReason(failed.reason)), "NonRetryableHandler") && (row.attempts >= (declaration.retry?.maxAttempts ?? Number.POSITIVE_INFINITY) || Option.isNone(yield* bindingDelay(declaration.retry?.schedule, row.attempts))),
2544
+ failure: Option.map(row.failure, (stored) => ({
2545
+ ...stored,
2546
+ reason: knownMarkReason(stored.reason)
2547
+ }))
2350
2548
  };
2351
2549
  }));
2352
2550
  }),
@@ -2370,13 +2568,16 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
2370
2568
  });
2371
2569
  };
2372
2570
  // src/attach.ts
2571
+ /** Look up each trigger class's service, with each class in the requirements. */
2572
+ const requireTriggers = (triggers) => Effect.forEach(triggers ?? [], (trigger) => Effect.service(trigger), { discard: true });
2373
2573
  /** A defect of one drain pass, captured for logging with typed failures. */
2374
2574
  var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Schema.Defect() }) {};
2375
2575
  /**
2376
2576
  * Run a projection whenever a local commit writes one of its inputs. The layer
2377
- * subscribes to `Storage.committed` when it is built, so build it with the
2577
+ * subscribes to `StorageOwner.committed` when it is built, so build it with the
2378
2578
  * storage layer and before the app writes. For each written id, the input's
2379
- * `parse` gives the params, and the runner runs `projection.at(params)`.
2579
+ * `parse` gives the params, and the runner runs `projection.at(params)`, or
2580
+ * `projection.singleton` for a projection without params.
2380
2581
  * The background runner also queues startup replays from the checkpoint
2381
2582
  * inventory or `options.bindings`.
2382
2583
  *
@@ -2389,7 +2590,7 @@ var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Sche
2389
2590
  * window, and the layer runs due marks when it starts. Recorded process timers
2390
2591
  * wake at their deadline; after host suspend, a capped wait rechecks within 30 s.
2391
2592
  * Return a time after unit.due to avoid repeatedly running a passed deadline.
2392
- * Inputs on another owner can use local or remote wake streams in `triggers`.
2593
+ * Inputs on another owner can use local or remote frontier streams in `triggers`.
2393
2594
  * A provided trigger service on another owner is read one page per pass outside
2394
2595
  * the local transaction; durable marks and the page cursor then commit together.
2395
2596
  * A scoped live-read follower signals new remote rows. Remote read failures use
@@ -2398,7 +2599,7 @@ var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Sche
2398
2599
  * an attached binding under `Projection.follow` too: use one writer per key.
2399
2600
  *
2400
2601
  * ```ts
2401
- * const app = Layer.mergeAll(Api, Projection.attach(filesWake)).pipe(
2602
+ * const app = Layer.mergeAll(Api, Projection.attach(filesFrontier)).pipe(
2402
2603
  * Layer.provideMerge(BunStorage.layer(streams, { path })),
2403
2604
  * );
2404
2605
  * ```
@@ -2417,8 +2618,7 @@ const attach$1 = (projection, options = {}) => {
2417
2618
  lastPassAt: Option.none(),
2418
2619
  step
2419
2620
  };
2420
- const registry = yield* Effect.serviceOption(Registry);
2421
- const changed = Option.isNone(registry) ? Effect.void : yield* registerRunner(registry.value, {
2621
+ const changed = yield* registerRunner(yield* StorageOwner, {
2422
2622
  id: projection.id,
2423
2623
  generation: projection.generation,
2424
2624
  schedule,
@@ -2479,7 +2679,7 @@ const current = Effect.fn("Projection.current")(function* (projection) {
2479
2679
  let state = yield* currentState(projection, projection.state, encoded);
2480
2680
  while (true) {
2481
2681
  const page = yield* readInputs(projection.inputs, offsets);
2482
- if (page.items === 0) return {
2682
+ if (Record.isEmptyRecord(page.counts)) return {
2483
2683
  state,
2484
2684
  offsets: offsetsOf$1({ inputs: offsets })
2485
2685
  };
@@ -2532,7 +2732,11 @@ const decide = Effect.fn("Projection.decide")(function* (projection, spec) {
2532
2732
  const address = projection.inputs[spec.input];
2533
2733
  const attempt = Effect.gen(function* () {
2534
2734
  const snapshot = yield* current(projection);
2535
- const offset = snapshot.offsets[spec.input];
2735
+ const offset = yield* storedOffset(snapshot.offsets[spec.input], {
2736
+ phase: "load",
2737
+ input: spec.input,
2738
+ what: `The snapshot offset of ${spec.input}`
2739
+ });
2536
2740
  const { value, items } = yield* spec.decide(snapshot);
2537
2741
  if (!Array.isReadonlyArrayNonEmpty(items)) return {
2538
2742
  value,
@@ -2585,20 +2789,22 @@ const cleanStream = (address, wire, mode) => {
2585
2789
  StreamGone: () => Effect.succeed("absent")
2586
2790
  }), Effect.mapError((cause) => new ProjectionFault({
2587
2791
  phase: "checkpoint",
2588
- reason: Predicate.isTagged(cause, "StreamBusy") ? "output-busy" : isStreamsFault(cause) ? "storage-failure" : "invalid-output",
2589
- message: `Cannot ${mode} output ${id}`,
2590
- cause
2792
+ reason: outputReason(`Cannot ${mode} output ${id}`, cause)
2591
2793
  })));
2592
2794
  };
2593
- /** Retire one binding and clean up its exclusively owned generation outputs. */
2594
- const retire = (declaration, params, options) => {
2795
+ const paramsAndOptions = (args) => args.length === 2 ? args : [{}, args[0]];
2796
+ /**
2797
+ * Retire one binding and clean up its exclusively owned generation outputs. A declaration
2798
+ * without params takes no params argument: `retire(declaration, { generation })`.
2799
+ */
2800
+ const retire = (declaration, ...args) => {
2801
+ const [params, options] = paramsAndOptions(args);
2595
2802
  const bound = bindAtGeneration(declaration, params, options.generation);
2596
2803
  const mode = options.streams ?? "remove";
2597
2804
  return Effect.gen(function* () {
2598
2805
  if (bound?.commit.retire === void 0) return yield* new ProjectionFault({
2599
2806
  phase: "checkpoint",
2600
- reason: "unsupported-composition",
2601
- message: "Retirement requires a projection declaration with a Commit that supports it"
2807
+ reason: new UnsupportedComposition({ message: "Retirement requires a projection declaration with a Commit that supports it" })
2602
2808
  });
2603
2809
  const shared = [];
2604
2810
  const owned = [];
@@ -2631,11 +2837,7 @@ const retire = (declaration, params, options) => {
2631
2837
  const owner = yield* CurrentOwner;
2632
2838
  const results = [...shared];
2633
2839
  const clean = (output, address, service) => {
2634
- if (owner !== void 0 && service.owner !== owner) return Effect.fail(new ProjectionFault({
2635
- phase: "checkpoint",
2636
- reason: "unsupported-composition",
2637
- message: `Output ${address.id} does not share the transaction owner`
2638
- }));
2840
+ if (owner !== void 0 && service.owner !== owner) return Effect.die(foreignOutput(bound.id, address.id, owner, service.owner));
2639
2841
  return cleanStream(address, service.wire, mode).pipe(Effect.map((result) => ({
2640
2842
  output,
2641
2843
  id: address.id,
@@ -2653,9 +2855,10 @@ const retire = (declaration, params, options) => {
2653
2855
  const definition = routes.get(output);
2654
2856
  const invalid = (cause) => new ProjectionFault({
2655
2857
  phase: "checkpoint",
2656
- reason: "invalid-record",
2657
- message: `Cannot restore routed output ${output} at ${id}`,
2658
- cause
2858
+ reason: new InvalidRecord({
2859
+ message: `Cannot restore routed output ${output} at ${id}`,
2860
+ cause
2861
+ })
2659
2862
  });
2660
2863
  const address = yield* Effect.try({
2661
2864
  try: () => definition?.restore(id),
@@ -2674,35 +2877,32 @@ const retire = (declaration, params, options) => {
2674
2877
  };
2675
2878
  });
2676
2879
  };
2677
- // src/wake.ts
2678
- const row = (stream, offset, closed) => DurableState.upsert("stream", closed ? {
2679
- stream,
2680
- offset: Offset.make(offset),
2681
- closed: true
2682
- } : {
2683
- stream,
2684
- offset: Offset.make(offset)
2685
- });
2880
+ // src/frontier-projection.ts
2686
2881
  /**
2687
- * A wake projection: one source stream gives one keyed row in one wake stream.
2882
+ * A frontier projection: one source stream gives one keyed row in one frontier stream.
2688
2883
  * Each unit appends one upsert `{ stream, offset, closed? }` with
2689
2884
  * `Commit.producer`, so several source writes in one unit fold into one row,
2690
- * and a retry answers `Duplicate`. The producer creates a missing wake stream
2691
- * on its own owner. A wake stream on another owner must exist before the first
2885
+ * and a retry answers `Duplicate`. The producer creates a missing frontier stream
2886
+ * on its own owner. A frontier stream on another owner must exist before the first
2692
2887
  * append: its owner creates it at start. When the source is removed or
2693
2888
  * expires, the binding appends a State delete for its row and forgets itself.
2694
2889
  *
2890
+ * The row is the one that `frontier: output` would publish for the source, except that a
2891
+ * gone source deletes its row, so that triggers clear their outputs. Rows that a State
2892
+ * source carries are not forwarded.
2893
+ *
2695
2894
  * ```ts
2696
- * const filesWake = Projection.wake({
2895
+ * const filesFrontier = Projection.frontier({
2697
2896
  * id: "files-wake",
2698
2897
  * params: { user: UserKey, folderId: FolderKey },
2699
2898
  * input: Files,
2700
- * output: UserWake,
2899
+ * output: UserFrontier,
2701
2900
  * });
2702
2901
  * ```
2703
2902
  */
2704
- function wake(definition) {
2903
+ function frontier(definition) {
2705
2904
  rejectProjectionVersion(definition.id, definition);
2905
+ rejectAccepted(definition.id, definition);
2706
2906
  const input = definition.input;
2707
2907
  return build("mapAccumBatch", {
2708
2908
  id: definition.id,
@@ -2711,15 +2911,17 @@ function wake(definition) {
2711
2911
  commit: producer,
2712
2912
  inputs: { source: input },
2713
2913
  outputs: { wake: definition.output },
2714
- accepted: definition.accepted,
2715
2914
  state: {
2716
2915
  schema: Schema.Null,
2717
2916
  initial: null
2718
2917
  },
2719
2918
  mapAccumBatch: (_state, batch, unit) => {
2720
- const source = isDeclaration(input) ? input.at(unit.params) : input;
2721
- const slice = batch.source;
2722
- return [null, { wake: [slice.gone ? DurableState.remove("stream", StreamId.make(source.id)) : row(StreamId.make(source.id), slice.nextOffset, slice.closed)] }];
2919
+ const source = isDeclaration(input) ? bindDeclaration(input, unit.params) : input;
2920
+ const stream = StreamId.make(source.id);
2921
+ if (batch.source.gone === true) return [null, { wake: [DurableState.remove("stream", stream)] }];
2922
+ const range = unit.ranges.source;
2923
+ const value = range === void 0 ? void 0 : inputFrontier(stream, range, false);
2924
+ return [null, { wake: value === void 0 ? [] : [DurableState.upsert("stream", value)] }];
2723
2925
  }
2724
2926
  });
2725
2927
  }
@@ -2739,6 +2941,7 @@ var projection_exports = /* @__PURE__ */ __exportAll({
2739
2941
  fold: () => fold,
2740
2942
  follow: () => follow,
2741
2943
  forget: () => forget,
2944
+ frontier: () => frontier,
2742
2945
  generationBinding: () => generationBinding,
2743
2946
  isPerGeneration: () => isPerGeneration,
2744
2947
  items: () => items,
@@ -2753,7 +2956,6 @@ var projection_exports = /* @__PURE__ */ __exportAll({
2753
2956
  retire: () => retire,
2754
2957
  run: () => run,
2755
2958
  tails: () => tails,
2756
- wake: () => wake,
2757
2959
  wakeAt: () => wakeAt
2758
2960
  });
2759
2961
  const key = (projection) => ({
@@ -2764,36 +2966,13 @@ const key = (projection) => ({
2764
2966
  /** Runs each tagged entry in order and discards its success value. */
2765
2967
  const each = (handle) => (batch, unit) => Effect.forEach(items(batch), (entry) => handle(entry, unit), { discard: true });
2766
2968
  // src/state-table-message.ts
2767
- const Message = Schema.Union([
2768
- Schema.Struct({ headers: Schema.Struct({ control: Schema.Literals([
2769
- "reset",
2770
- "snapshot-start",
2771
- "snapshot-end"
2772
- ]) }) }),
2773
- Schema.Struct({
2774
- type: Schema.String,
2775
- key: Schema.String,
2776
- headers: Schema.Struct({ operation: Schema.Literals([
2777
- "insert",
2778
- "update",
2779
- "upsert"
2780
- ]) }),
2781
- value: Schema.Unknown
2782
- }),
2783
- Schema.Struct({
2784
- type: Schema.String,
2785
- key: Schema.String,
2786
- headers: Schema.Struct({ operation: Schema.Literal("delete") })
2787
- })
2788
- ]);
2789
2969
  const Change = Data.taggedEnum();
2790
- const decode = Schema.decodeEffect(Schema.fromJsonString(Message));
2791
2970
  /**
2792
2971
  * Only the protocol envelope is decoded; collection values never pass through a codec.
2793
2972
  * `JSON.stringify` gives the bytes that storage holds, because core stores each JSON
2794
2973
  * message as `JSON.stringify` of the parsed item.
2795
2974
  */
2796
- const message = (json) => Effect.map(decode(json), (decoded) => {
2975
+ const message = (json) => Effect.map(decodeStateWire(json), (decoded) => {
2797
2976
  if (!("type" in decoded)) return Change.Control({ control: decoded.headers.control });
2798
2977
  return "value" in decoded ? Change.Upsert({
2799
2978
  collection: decoded.type,
@@ -2817,60 +2996,412 @@ const deleteJson = (collection, key) => JSON.stringify({
2817
2996
  const decodeRow = (schema, json) => Schema.decodeEffect(Schema.fromJsonString(Schema.toCodecJson(schema)))(json);
2818
2997
  /** Encode one row to the canonical JSON that the table stores for it. */
2819
2998
  const encodeRow = (schema, value) => Schema.encodeEffect(Schema.fromJsonString(Schema.toCodecJson(schema)))(value);
2820
- /** The stored JSON of each key that has a row. A missing key has no entry. */
2821
- const storedValues = Effect.fn("StateTable.storedValues")(function* (sql, id, collection, keys) {
2822
- const values = /* @__PURE__ */ new Map();
2823
- for (const chunk of Array.chunksOf(keys, 50)) {
2824
- const found = yield* sql`SELECT row_key, value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND ${sql.in("row_key", chunk)}`;
2825
- for (const row of found) values.set(row.row_key, row.value);
2999
+ /**
3000
+ * The stored JSON of each key that has a row. A missing key has no entry, and nor has a
3001
+ * key that the table cannot store.
3002
+ */
3003
+ const storedValues = (store, id, collection, keys) => store.values(id, collection, Array.filter(keys, (key) => Option.isNone(store.unstorable(collection, key))));
3004
+ // src/state-table-memory.ts
3005
+ const tombstone = Symbol("@streamsy/projection/StateTableMemory/tombstone");
3006
+ /** Private: the committed rows and head of one stream, for test dumps. */
3007
+ const MemoryRows = Symbol.for("@streamsy/projection/internal/StateTableMemoryRows");
3008
+ /**
3009
+ * Compare by code point, which is UTF-8 byte order and SQL's binary collations.
3010
+ * JavaScript's `<` compares UTF-16 code units, so it sorts U+1F600 before U+E000.
3011
+ */
3012
+ const compareCodePoints = (left, right) => {
3013
+ const length = Math.min(left.length, right.length);
3014
+ for (let index = 0; index < length; index++) {
3015
+ const a = left.charCodeAt(index);
3016
+ const b = right.charCodeAt(index);
3017
+ if (a !== b) return rank(a) - rank(b);
2826
3018
  }
2827
- return values;
3019
+ return left.length - right.length;
3020
+ };
3021
+ /** Code point order as an `Order`, for sorting keys. */
3022
+ const byCodePoint = (left, right) => {
3023
+ const order = compareCodePoints(left, right);
3024
+ return order < 0 ? -1 : order > 0 ? 1 : 0;
3025
+ };
3026
+ const rank = (unit) => unit >= 55296 && unit <= 57343 ? unit + 8192 : unit >= 57344 ? unit - 2048 : unit;
3027
+ /** The first index of `keys` that sorts after `after`. */
3028
+ const upperBound = (keys, after) => {
3029
+ let first = 0;
3030
+ let end = keys.length;
3031
+ while (first < end) {
3032
+ const mid = Math.floor((first + end) / 2);
3033
+ if (compareCodePoints(keys[mid], after) <= 0) first = mid + 1;
3034
+ else end = mid;
3035
+ }
3036
+ return first;
3037
+ };
3038
+ const unwritable = (id) => new ProjectionFault({
3039
+ phase: "process",
3040
+ reason: new UnsupportedComposition({ message: `The rows of ${id} have no open memory owner transaction on this fiber. Write them inside the storage owner's transaction.` })
3041
+ });
3042
+ const page = (keys, rows, options) => {
3043
+ const first = options.after === void 0 ? 0 : upperBound(keys, options.after);
3044
+ const selected = keys.slice(first, options.limit === void 0 ? void 0 : first + options.limit);
3045
+ return Array.map(selected, (row_key) => ({
3046
+ row_key,
3047
+ value: rows.get(row_key).value
3048
+ }));
3049
+ };
3050
+ /**
3051
+ * Rows in the heap of one memory owner. A unit writes to a private write set that
3052
+ * commits with the owner's transaction and is dropped on rollback, so a read outside
3053
+ * the unit sees committed rows only. A read inside the transaction but on a forked
3054
+ * fiber cannot enlist either, so it also sees committed rows only.
3055
+ */
3056
+ const memoryStore = (enlist) => {
3057
+ const committed = /* @__PURE__ */ new Map();
3058
+ /** Sorted keys of committed rows, by stream and collection, dropped when a commit changes them. */
3059
+ const sorted = /* @__PURE__ */ new Map();
3060
+ /** The open unit's writes. The owner runs one transaction at a time. */
3061
+ let written;
3062
+ /** True on the owner fiber inside its transaction, which then commits or drops `written`. */
3063
+ const inUnit = Effect.match(enlist({
3064
+ onCommit: () => {
3065
+ const writes = written;
3066
+ written = void 0;
3067
+ if (writes === void 0) return;
3068
+ for (const [id, write] of writes) {
3069
+ const base = committed.get(id) ?? {
3070
+ head: void 0,
3071
+ rows: /* @__PURE__ */ new Map()
3072
+ };
3073
+ const keys = sorted.get(id);
3074
+ if (write.cleared) {
3075
+ base.rows.clear();
3076
+ sorted.delete(id);
3077
+ }
3078
+ for (const [collection, pending] of write.rows) {
3079
+ let rows = base.rows.get(collection);
3080
+ for (const [key, row] of pending) if (row === tombstone) {
3081
+ if (rows?.delete(key) === true) keys?.delete(collection);
3082
+ } else {
3083
+ if (rows === void 0) {
3084
+ rows = /* @__PURE__ */ new Map();
3085
+ base.rows.set(collection, rows);
3086
+ }
3087
+ if (!rows.has(key)) keys?.delete(collection);
3088
+ rows.set(key, row);
3089
+ }
3090
+ if (rows?.size === 0) base.rows.delete(collection);
3091
+ }
3092
+ if (write.head === null) base.head = void 0;
3093
+ else if (write.head !== void 0) base.head = write.head;
3094
+ if (base.head === void 0 && base.rows.size === 0) {
3095
+ committed.delete(id);
3096
+ sorted.delete(id);
3097
+ } else committed.set(id, base);
3098
+ }
3099
+ },
3100
+ onRollback: () => {
3101
+ written = void 0;
3102
+ }
3103
+ }), {
3104
+ onFailure: () => false,
3105
+ onSuccess: () => true
3106
+ });
3107
+ const writeSet = (id) => Effect.flatMap(inUnit, (enlisted) => {
3108
+ if (!enlisted) return Effect.fail(unwritable(id));
3109
+ written ??= /* @__PURE__ */ new Map();
3110
+ let write = written.get(id);
3111
+ if (write === void 0) {
3112
+ write = {
3113
+ cleared: false,
3114
+ head: void 0,
3115
+ rows: /* @__PURE__ */ new Map()
3116
+ };
3117
+ written.set(id, write);
3118
+ }
3119
+ return Effect.succeed(write);
3120
+ });
3121
+ /** Run `body` on the stream's write set. A store write without a unit is a defect. */
3122
+ const write = (id, body) => Effect.asVoid(Effect.map(Effect.orDie(writeSet(id)), (state) => {
3123
+ body(state);
3124
+ }));
3125
+ const pendingRows = (state, collection) => {
3126
+ let rows = state.rows.get(collection);
3127
+ if (rows === void 0) {
3128
+ rows = /* @__PURE__ */ new Map();
3129
+ state.rows.set(collection, rows);
3130
+ }
3131
+ return rows;
3132
+ };
3133
+ /** The write set of `id` that this fiber sees, if any. */
3134
+ const visible = (id) => Effect.map(inUnit, (enlisted) => enlisted && written !== void 0 ? written.get(id) : void 0);
3135
+ const committedRow = (id, collection, key) => committed.get(id)?.rows.get(collection)?.get(key);
3136
+ const rowOf = (state, id, collection, key) => {
3137
+ const pending = state?.rows.get(collection)?.get(key);
3138
+ if (pending === tombstone) return void 0;
3139
+ if (pending !== void 0) return pending;
3140
+ if (state?.cleared === true) return void 0;
3141
+ return committedRow(id, collection, key);
3142
+ };
3143
+ /** Every row of `collection` that `state` leaves, by key. */
3144
+ const rowsOf = (state, id, collection) => {
3145
+ const rows = new Map(state?.cleared === true ? [] : committed.get(id)?.rows.get(collection) ?? []);
3146
+ for (const [key, row] of state?.rows.get(collection) ?? []) if (row === tombstone) rows.delete(key);
3147
+ else rows.set(key, row);
3148
+ return rows;
3149
+ };
3150
+ const committedKeys = (id, collection) => {
3151
+ let streams = sorted.get(id);
3152
+ const cached = streams?.get(collection);
3153
+ if (cached !== void 0) return cached;
3154
+ const keys = Array.sort(committed.get(id)?.rows.get(collection)?.keys() ?? [], byCodePoint);
3155
+ if (streams === void 0) {
3156
+ streams = /* @__PURE__ */ new Map();
3157
+ sorted.set(id, streams);
3158
+ }
3159
+ streams.set(collection, keys);
3160
+ return keys;
3161
+ };
3162
+ return {
3163
+ writer: (id) => Effect.asVoid(writeSet(id)),
3164
+ head: (id) => Effect.map(visible(id), (state) => {
3165
+ if (state?.head === null) return Option.none();
3166
+ if (state?.head !== void 0) return Option.some(state.head);
3167
+ return Option.fromUndefinedOr(committed.get(id)?.head);
3168
+ }),
3169
+ saveHead: (id, head) => write(id, (state) => {
3170
+ state.head = { ...head };
3171
+ }),
3172
+ deleteHead: (id) => write(id, (state) => {
3173
+ state.head = null;
3174
+ }),
3175
+ clearRows: (id) => write(id, (state) => {
3176
+ state.cleared = true;
3177
+ state.rows.clear();
3178
+ }),
3179
+ deleteBefore: (id, epoch) => write(id, (state) => {
3180
+ const collections = /* @__PURE__ */ new Set([...state.cleared ? [] : committed.get(id)?.rows.keys() ?? [], ...state.rows.keys()]);
3181
+ for (const collection of collections) {
3182
+ const pending = pendingRows(state, collection);
3183
+ for (const [key, row] of rowsOf(state, id, collection)) if (row.epoch < epoch) pending.set(key, tombstone);
3184
+ }
3185
+ }),
3186
+ upsertRow: (id, row, epoch) => write(id, (state) => {
3187
+ pendingRows(state, row.collection).set(row.key, {
3188
+ value: row.value,
3189
+ epoch
3190
+ });
3191
+ }),
3192
+ deleteRow: (id, collection, key) => write(id, (state) => {
3193
+ pendingRows(state, collection).set(key, tombstone);
3194
+ }),
3195
+ value: (id, collection, key) => Effect.map(visible(id), (state) => Option.map(Option.fromUndefinedOr(rowOf(state, id, collection, key)), (row) => row.value)),
3196
+ values: (id, collection, keys) => Effect.map(visible(id), (state) => {
3197
+ const values = /* @__PURE__ */ new Map();
3198
+ for (const key of keys) {
3199
+ const row = rowOf(state, id, collection, key);
3200
+ if (row !== void 0) values.set(key, row.value);
3201
+ }
3202
+ return values;
3203
+ }),
3204
+ list: (id, collection, options) => Effect.map(visible(id), (state) => {
3205
+ if (state === void 0 || !state.cleared && !state.rows.has(collection)) {
3206
+ const rows = committed.get(id)?.rows.get(collection);
3207
+ return rows === void 0 ? [] : page(committedKeys(id, collection), rows, options);
3208
+ }
3209
+ const rows = rowsOf(state, id, collection);
3210
+ return page(Array.sort(rows.keys(), byCodePoint), rows, options);
3211
+ }),
3212
+ unstorable: () => Option.none(),
3213
+ [MemoryRows]: (id) => ({
3214
+ head: committed.get(id)?.head,
3215
+ rows: Array.flatMap(Array.fromIterable(committed.get(id)?.rows ?? []), ([collection, rows]) => Array.map(Array.fromIterable(rows), ([key, row]) => ({
3216
+ collection,
3217
+ key,
3218
+ ...row
3219
+ })))
3220
+ })
3221
+ };
3222
+ };
3223
+ const MYSQL_TEXT_KEY = "CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin";
3224
+ const unsupported = () => Effect.fail(new ProjectionFault({
3225
+ phase: "load",
3226
+ reason: new UnsupportedComposition({ message: "Unsupported SQL dialect; StateTable supports sqlite, pg and mysql" })
3227
+ }));
3228
+ /** Create both tables. The SQLite DDL is unchanged since StateTable was added. */
3229
+ const createTables = (sql) => sql.onDialectOrElse({
3230
+ sqlite: () => Effect.gen(function* () {
3231
+ yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_heads (
3232
+ stream_id TEXT PRIMARY KEY,
3233
+ applied_offset TEXT NOT NULL,
3234
+ epoch INTEGER NOT NULL DEFAULT 0,
3235
+ snapshot_open INTEGER NOT NULL DEFAULT 0
3236
+ ) WITHOUT ROWID`;
3237
+ yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_rows (
3238
+ stream_id TEXT NOT NULL,
3239
+ collection TEXT NOT NULL,
3240
+ row_key TEXT NOT NULL,
3241
+ value TEXT NOT NULL,
3242
+ epoch INTEGER NOT NULL DEFAULT 0,
3243
+ PRIMARY KEY (stream_id, collection, row_key)
3244
+ ) WITHOUT ROWID`;
3245
+ }),
3246
+ pg: () => Effect.gen(function* () {
3247
+ yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_heads (
3248
+ stream_id TEXT COLLATE "C" PRIMARY KEY,
3249
+ applied_offset TEXT NOT NULL,
3250
+ epoch INTEGER NOT NULL DEFAULT 0,
3251
+ snapshot_open INTEGER NOT NULL DEFAULT 0
3252
+ )`;
3253
+ yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_rows (
3254
+ stream_id TEXT COLLATE "C" NOT NULL,
3255
+ collection TEXT COLLATE "C" NOT NULL,
3256
+ row_key TEXT COLLATE "C" NOT NULL,
3257
+ value TEXT NOT NULL,
3258
+ epoch INTEGER NOT NULL DEFAULT 0,
3259
+ PRIMARY KEY (stream_id, collection, row_key)
3260
+ )`;
3261
+ }),
3262
+ mysql: () => Effect.gen(function* () {
3263
+ yield* sql.unsafe(`CREATE TABLE IF NOT EXISTS streamsy_state_heads (
3264
+ stream_id VARCHAR(512) ${MYSQL_TEXT_KEY} PRIMARY KEY,
3265
+ applied_offset TEXT NOT NULL,
3266
+ epoch INT NOT NULL DEFAULT 0,
3267
+ snapshot_open INT NOT NULL DEFAULT 0
3268
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`);
3269
+ yield* sql.unsafe(`CREATE TABLE IF NOT EXISTS streamsy_state_rows (
3270
+ stream_id VARCHAR(512) ${MYSQL_TEXT_KEY} NOT NULL,
3271
+ collection VARCHAR(64) ${MYSQL_TEXT_KEY} NOT NULL,
3272
+ row_key VARCHAR(192) ${MYSQL_TEXT_KEY} NOT NULL,
3273
+ value LONGTEXT NOT NULL,
3274
+ epoch INT NOT NULL DEFAULT 0,
3275
+ PRIMARY KEY (stream_id, collection, row_key)
3276
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`);
3277
+ }),
3278
+ orElse: unsupported
2828
3279
  });
3280
+ /**
3281
+ * Lock the head row on server dialects, so that concurrent units apply one gap in turn
3282
+ * and the second sees the first's head. SQLite already has one writer.
3283
+ */
3284
+ const lockHead = (sql) => sql.onDialectOrElse({
3285
+ sqlite: () => sql``,
3286
+ orElse: () => sql`FOR UPDATE`
3287
+ });
3288
+ const saveHead = (sql, id, state) => {
3289
+ const values = sql`(stream_id, applied_offset, epoch, snapshot_open)
3290
+ VALUES (${id}, ${state.applied_offset}, ${state.epoch}, ${state.snapshot_open})`;
3291
+ return sql.onDialectOrElse({
3292
+ mysql: () => sql`INSERT INTO streamsy_state_heads ${values}
3293
+ ON DUPLICATE KEY UPDATE applied_offset = VALUES(applied_offset),
3294
+ epoch = VALUES(epoch), snapshot_open = VALUES(snapshot_open)`,
3295
+ orElse: () => sql`INSERT INTO streamsy_state_heads ${values}
3296
+ ON CONFLICT (stream_id) DO UPDATE SET applied_offset = excluded.applied_offset,
3297
+ epoch = excluded.epoch, snapshot_open = excluded.snapshot_open`
3298
+ });
3299
+ };
3300
+ const upsertRow = (sql, id, row, epoch) => {
3301
+ const values = sql`(stream_id, collection, row_key, value, epoch)
3302
+ VALUES (${id}, ${row.collection}, ${row.key}, ${row.value}, ${epoch})`;
3303
+ return sql.onDialectOrElse({
3304
+ mysql: () => sql`INSERT INTO streamsy_state_rows ${values}
3305
+ ON DUPLICATE KEY UPDATE value = VALUES(value), epoch = VALUES(epoch)`,
3306
+ orElse: () => sql`INSERT INTO streamsy_state_rows ${values}
3307
+ ON CONFLICT (stream_id, collection, row_key) DO UPDATE SET value = excluded.value, epoch = excluded.epoch`
3308
+ });
3309
+ };
3310
+ const tooLong = (column, value, limit) => {
3311
+ const length = [...value].length;
3312
+ return length > limit ? Option.some(`StateTable ${column} has ${length} characters; the MySQL limit is ${limit}`) : Option.none();
3313
+ };
3314
+ const hasNul = (column, value) => value.includes("\0") ? Option.some(`StateTable ${column} contains a NUL character, which Postgres text cannot store`) : Option.none();
3315
+ /**
3316
+ * Why the table cannot store a row of `collection` under `key`, if it cannot. MySQL
3317
+ * keys are bounded, and Postgres text rejects NUL. SQLite stores every string.
3318
+ */
3319
+ const unstorable = (sql, collection, key) => sql.onDialectOrElse({
3320
+ mysql: () => Option.orElse(tooLong("collection", collection, 64), () => tooLong("row_key", key, 192)),
3321
+ pg: () => Option.orElse(hasNul("collection", collection), () => hasNul("row_key", key)),
3322
+ orElse: () => Option.none()
3323
+ });
3324
+ /** The store over the storage owner's SQL client. Statements are unchanged per dialect. */
3325
+ const sqlStore = (sql) => ({
3326
+ writer: (id) => Effect.flatMap(Effect.serviceOption(sql.transactionService), (transaction) => Option.isSome(transaction) ? Effect.void : Effect.fail(new ProjectionFault({
3327
+ phase: "process",
3328
+ reason: new UnsupportedComposition({ message: `The rows of ${id} have no open transaction on the storage owner's SQL client. Write them inside the storage owner's transaction.` })
3329
+ }))),
3330
+ head: (id, locked) => Effect.map(sql`SELECT applied_offset, epoch, snapshot_open FROM streamsy_state_heads WHERE stream_id = ${id} ${locked ? lockHead(sql) : sql``}`, Array.head),
3331
+ saveHead: (id, head) => Effect.asVoid(saveHead(sql, id, head)),
3332
+ deleteHead: (id) => Effect.asVoid(sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`),
3333
+ clearRows: (id) => Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}`),
3334
+ deleteBefore: (id, epoch) => Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id} AND epoch < ${epoch}`),
3335
+ upsertRow: (id, row, epoch) => Effect.asVoid(upsertRow(sql, id, row, epoch)),
3336
+ deleteRow: (id, collection, key) => Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}
3337
+ AND collection = ${collection} AND row_key = ${key}`),
3338
+ value: (id, collection, key) => Effect.map(sql`SELECT value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND row_key = ${key}`, (rows) => Option.map(Array.head(rows), (row) => row.value)),
3339
+ values: Effect.fn("StateTable.storedValues")(function* (id, collection, keys) {
3340
+ const values = /* @__PURE__ */ new Map();
3341
+ for (const chunk of Array.chunksOf(keys, 50)) {
3342
+ const found = yield* sql`SELECT row_key, value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND ${sql.in("row_key", chunk)}`;
3343
+ for (const row of found) values.set(row.row_key, row.value);
3344
+ }
3345
+ return values;
3346
+ }),
3347
+ list: (id, collection, options) => sql`SELECT row_key, value FROM streamsy_state_rows
3348
+ WHERE stream_id = ${id} AND collection = ${collection}
3349
+ ${options.after === void 0 ? sql`` : sql`AND row_key > ${options.after}`}
3350
+ ORDER BY row_key ${options.limit === void 0 ? sql`` : sql`LIMIT ${options.limit}`}`,
3351
+ unstorable: (collection, key) => unstorable(sql, collection, key)
3352
+ });
3353
+ // src/state-table-owner.ts
3354
+ /**
3355
+ * The one row store of each owner, so that every StateTable and FoldByKey over the owner
3356
+ * shares its rows. A SQL owner keeps them on its client, a memory owner in the heap.
3357
+ */
3358
+ const storeSlot = new OwnerSlot(({ backend }) => OwnerBackend.$match(backend, {
3359
+ Sql: ({ client }) => sqlStore(client),
3360
+ Memory: ({ enlist }) => memoryStore(enlist)
3361
+ }));
3362
+ /** The row store of `owner`. */
3363
+ const ownerStore = (owner) => ownerParts(owner).slot(storeSlot);
3364
+ /** The row store of the storage owner in context. */
3365
+ const currentStore = Effect.map(StorageOwner, ownerStore);
2829
3366
  // src/state-table.ts
2830
3367
  var state_table_exports = /* @__PURE__ */ __exportAll({
2831
3368
  clear: () => clear,
2832
3369
  define: () => define,
2833
3370
  migrate: () => migrate,
2834
3371
  rebuild: () => rebuild,
2835
- reset: () => reset
3372
+ reset: () => reset,
3373
+ unit: () => unit
2836
3374
  });
2837
3375
  const empty = {
2838
3376
  applied_offset: ZERO_OFFSET,
2839
3377
  epoch: 0,
2840
3378
  snapshot_open: 0
2841
3379
  };
2842
- const head = (sql, id) => Effect.map(sql`SELECT applied_offset, epoch, snapshot_open FROM streamsy_state_heads WHERE stream_id = ${id}`, Array.head);
2843
3380
  /** The offset that the rows reflect. A table with no head has no rows. */
2844
- const appliedOffset = (sql, id) => Effect.map(head(sql, id), (stored) => Option.getOrElse(stored, () => empty).applied_offset);
2845
- const clearRows = (sql, id) => sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}`;
2846
- const save = (sql, id, state) => sql`INSERT INTO streamsy_state_heads (stream_id, applied_offset, epoch, snapshot_open)
2847
- VALUES (${id}, ${state.applied_offset}, ${state.epoch}, ${state.snapshot_open})
2848
- ON CONFLICT (stream_id) DO UPDATE SET applied_offset = excluded.applied_offset,
2849
- epoch = excluded.epoch, snapshot_open = excluded.snapshot_open`;
3381
+ const appliedOffset = (store, id) => Effect.map(store.head(id, false), (stored) => Option.getOrElse(stored, () => empty).applied_offset);
2850
3382
  const sqlFault = (id) => (cause) => new ProjectionFault({
2851
3383
  phase: "process",
2852
- reason: "storage-failure",
2853
- message: `Cannot update the rows of ${id}`,
2854
- cause
2855
- });
2856
- /** Statements of a client without an open transaction would outlive a rolled-back unit. */
2857
- const transactionClient = (id) => Effect.gen(function* () {
2858
- const sql = yield* SqlClient.SqlClient;
2859
- if (Option.isNone(yield* Effect.serviceOption(sql.transactionService))) return yield* new ProjectionFault({
2860
- phase: "process",
2861
- reason: "unsupported-composition",
2862
- message: `The SqlClient for the rows of ${id} has no open transaction. Use the storage owner's client inside its transaction.`
2863
- });
2864
- return sql;
3384
+ reason: storageFault(`stateTable.update ${id}`)(cause)
2865
3385
  });
2866
- const apply = Effect.fn("StateTable.apply")(function* (sql, id, before, items) {
3386
+ /** A storage or transport fault of a read is the reason of the fault. */
3387
+ const readFault = (cause) => new ProjectionFault({
3388
+ phase: "read",
3389
+ reason: cause
3390
+ });
3391
+ /** Writes outside the storage owner's transaction would outlive a rolled-back unit. */
3392
+ const writer = (id) => Effect.gen(function* () {
3393
+ const store = yield* currentStore;
3394
+ yield* store.writer(id);
3395
+ return store;
3396
+ });
3397
+ const apply = Effect.fn("StateTable.apply")(function* (store, id, before, items) {
2867
3398
  let epoch = before.epoch;
2868
3399
  let open = before.snapshot_open;
2869
3400
  for (const item of items) yield* Change.$match(yield* message(item), {
2870
3401
  Control: ({ control }) => {
2871
3402
  if (control === "reset") {
2872
3403
  open = 0;
2873
- return Effect.asVoid(clearRows(sql, id));
3404
+ return store.clearRows(id);
2874
3405
  }
2875
3406
  if (control === "snapshot-start") {
2876
3407
  epoch += 1;
@@ -2879,103 +3410,92 @@ const apply = Effect.fn("StateTable.apply")(function* (sql, id, before, items) {
2879
3410
  }
2880
3411
  if (open === 0) return Effect.void;
2881
3412
  open = 0;
2882
- return Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id} AND epoch < ${epoch}`);
3413
+ return store.deleteBefore(id, epoch);
2883
3414
  },
2884
- Upsert: ({ collection, key, value }) => Effect.asVoid(sql`INSERT INTO streamsy_state_rows (stream_id, collection, row_key, value, epoch)
2885
- VALUES (${id}, ${collection}, ${key}, ${value}, ${epoch})
2886
- ON CONFLICT (stream_id, collection, row_key) DO UPDATE SET value = excluded.value, epoch = excluded.epoch`),
2887
- Delete: ({ collection, key }) => Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}
2888
- AND collection = ${collection} AND row_key = ${key}`)
3415
+ Upsert: (row) => Option.match(store.unstorable(row.collection, row.key), {
3416
+ onNone: () => store.upsertRow(id, row, epoch),
3417
+ onSome: (reason) => Effect.fail(new ProjectionFault({
3418
+ phase: "process",
3419
+ reason: new InvalidRecord({ message: `A stored message of ${id} has a row that the table cannot store. ${reason}` })
3420
+ }))
3421
+ }),
3422
+ Delete: ({ collection, key }) => Option.isSome(store.unstorable(collection, key)) ? Effect.void : store.deleteRow(id, collection, key)
2889
3423
  });
2890
3424
  return {
2891
3425
  epoch,
2892
3426
  snapshot_open: open
2893
3427
  };
2894
- }, (effect, _sql, id) => Effect.catchTag(effect, "SchemaError", (cause) => new ProjectionFault({
3428
+ }, (effect, _store, id) => Effect.catchTag(effect, "SchemaError", (cause) => new ProjectionFault({
2895
3429
  phase: "process",
2896
- reason: "invalid-record",
2897
- message: `A stored message of ${id} is not a State message`,
2898
- cause
3430
+ reason: new InvalidRecord({
3431
+ message: `A stored message of ${id} is not a State message`,
3432
+ cause
3433
+ })
2899
3434
  })));
2900
- /** Create the SQLite row index at host startup, outside storage migrations. */
2901
- const migrate = Effect.fn("StateTable.migrate")(function* (sql) {
2902
- yield* sql.onDialectOrElse({
2903
- sqlite: () => Effect.void,
2904
- orElse: () => Effect.fail(new ProjectionFault({
2905
- phase: "load",
2906
- reason: "unsupported-composition",
2907
- message: "StateTable requires SQLite"
2908
- }))
2909
- });
2910
- yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_heads (
2911
- stream_id TEXT PRIMARY KEY,
2912
- applied_offset TEXT NOT NULL,
2913
- epoch INTEGER NOT NULL DEFAULT 0,
2914
- snapshot_open INTEGER NOT NULL DEFAULT 0
2915
- ) WITHOUT ROWID`;
2916
- yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_rows (
2917
- stream_id TEXT NOT NULL,
2918
- collection TEXT NOT NULL,
2919
- row_key TEXT NOT NULL,
2920
- value TEXT NOT NULL,
2921
- epoch INTEGER NOT NULL DEFAULT 0,
2922
- PRIMARY KEY (stream_id, collection, row_key)
2923
- ) WITHOUT ROWID`;
2924
- });
3435
+ /**
3436
+ * Create the row index on a SQL storage owner (SQLite, Postgres or MySQL) at host
3437
+ * startup, outside storage migrations. A memory owner needs none, so it does nothing.
3438
+ */
3439
+ const migrate = Effect.gen(function* () {
3440
+ const { backend } = ownerParts(yield* StorageOwner);
3441
+ if (OwnerBackend.$is("Sql")(backend)) yield* createTables(backend.client);
3442
+ }).pipe(Effect.withSpan("StateTable.migrate"));
2925
3443
  const synchronize = (address) => Effect.gen(function* () {
2926
- const sql = yield* transactionClient(address.id);
3444
+ const store = yield* writer(address.id);
2927
3445
  const { wire } = yield* address.stream;
2928
3446
  const unavailable = () => new ProjectionFault({
2929
3447
  phase: "read",
2930
- reason: "history-unavailable",
2931
- message: `Required history of ${address.id} is unavailable`
3448
+ reason: new HistoryUnavailable({ message: `Required history of ${address.id} is unavailable` })
2932
3449
  });
2933
- const storage = (cause) => new ProjectionFault({
3450
+ const notFound = (cause) => new ProjectionFault({
2934
3451
  phase: "read",
2935
- reason: "storage-failure",
2936
- message: `Cannot read ${address.id}`,
2937
- cause
3452
+ reason: inputNotFound(address.id, cause)
2938
3453
  });
2939
- const stored = yield* head(sql, address.id);
3454
+ const stored = yield* store.head(address.id, true);
2940
3455
  const tail = yield* wire.head(address.id).pipe(Effect.catchTags({
2941
- StreamNotFound: unavailable,
3456
+ StreamNotFound: notFound,
2942
3457
  StreamGone: unavailable,
2943
- StorageFault: storage,
2944
- TransportFault: storage
3458
+ StorageFault: readFault,
3459
+ TransportFault: readFault
2945
3460
  }));
2946
3461
  let state = Option.getOrElse(stored, () => empty);
2947
- if (Option.isNone(stored) || compare(state.applied_offset, tail.nextOffset) > 0) {
2948
- yield* clearRows(sql, address.id);
3462
+ if (Option.isNone(stored) || compare(state.applied_offset, tail.offset) > 0) {
3463
+ yield* store.clearRows(address.id);
2949
3464
  state = empty;
2950
3465
  }
2951
- while (compare(state.applied_offset, tail.nextOffset) < 0) {
2952
- const page = yield* wire.read(address.id, { offset: state.applied_offset }).pipe(Effect.catchTags({
3466
+ while (compare(state.applied_offset, tail.offset) < 0) {
3467
+ const start = yield* storedOffset(state.applied_offset, {
3468
+ phase: "read",
3469
+ what: `The applied offset of ${address.id}`
3470
+ });
3471
+ const page = yield* wire.read(address.id, { offset: start }).pipe(Effect.catchTags({
2953
3472
  InvalidReadRequest: (cause) => new ProjectionFault({
2954
3473
  phase: "read",
2955
- reason: "invalid-source",
2956
- message: cause.message,
2957
- cause
3474
+ reason: new InvalidSource({
3475
+ message: cause.message,
3476
+ cause
3477
+ })
2958
3478
  }),
2959
- StreamNotFound: unavailable,
3479
+ StreamNotFound: notFound,
2960
3480
  StreamGone: unavailable,
2961
- StorageFault: storage,
2962
- TransportFault: storage
3481
+ StorageFault: readFault,
3482
+ TransportFault: readFault
2963
3483
  }));
2964
3484
  if (compare(page.nextOffset, state.applied_offset) <= 0) return yield* unavailable();
2965
3485
  state = {
2966
- ...yield* apply(sql, address.id, state, Array.map(page.messages, (item) => new TextDecoder().decode(item.data))),
3486
+ ...yield* apply(store, address.id, state, Array.map(page.messages, (item) => new TextDecoder().decode(item.data))),
2967
3487
  applied_offset: page.nextOffset
2968
3488
  };
2969
3489
  }
2970
- return yield* save(sql, address.id, state);
3490
+ return yield* store.saveHead(address.id, state);
2971
3491
  }).pipe(Effect.catchTag("SqlError", sqlFault(address.id)), Effect.asVoid, Effect.withSpan("StateTable.sync"));
2972
3492
  const applySlice = (address, slice) => Effect.gen(function* () {
2973
- const sql = yield* transactionClient(address.id);
2974
- const stored = yield* head(sql, address.id);
3493
+ const store = yield* writer(address.id);
3494
+ const stored = yield* store.head(address.id, true);
2975
3495
  if (Option.isSome(stored) && stored.value.applied_offset === slice.from || Option.isNone(stored) && slice.from === ZERO_OFFSET) {
2976
- if (Option.isNone(stored)) yield* clearRows(sql, address.id);
2977
- const next = yield* apply(sql, address.id, Option.getOrElse(stored, () => empty), slice.items);
2978
- yield* save(sql, address.id, {
3496
+ if (Option.isNone(stored)) yield* store.clearRows(address.id);
3497
+ const next = yield* apply(store, address.id, Option.getOrElse(stored, () => empty), slice.items);
3498
+ yield* store.saveHead(address.id, {
2979
3499
  ...next,
2980
3500
  applied_offset: slice.nextOffset
2981
3501
  });
@@ -2989,39 +3509,32 @@ const reads = (id, collections) => {
2989
3509
  };
2990
3510
  return {
2991
3511
  offset: Effect.fn("StateTable.offset")(function* () {
2992
- return yield* appliedOffset(yield* SqlClient.SqlClient, id);
3512
+ return yield* appliedOffset(yield* currentStore, id);
2993
3513
  }),
2994
3514
  get: Effect.fn("StateTable.get")(function* (collection, key) {
2995
- const sql = yield* SqlClient.SqlClient;
2996
- const offset = yield* appliedOffset(sql, id);
2997
- const row = (yield* sql`SELECT value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND row_key = ${key}`)[0];
3515
+ const store = yield* currentStore;
3516
+ const offset = yield* appliedOffset(store, id);
3517
+ const row = Option.isSome(store.unstorable(collection, key)) ? Option.none() : yield* store.value(id, collection, key);
2998
3518
  return {
2999
3519
  offset,
3000
- value: row === void 0 ? void 0 : yield* readValue(collection, row.value)
3520
+ value: Option.isNone(row) ? void 0 : yield* readValue(collection, row.value)
3001
3521
  };
3002
3522
  }),
3003
3523
  getMany: Effect.fn("StateTable.getMany")(function* (collection, keys) {
3004
- const sql = yield* SqlClient.SqlClient;
3005
- const offset = yield* appliedOffset(sql, id);
3524
+ const store = yield* currentStore;
3525
+ const offset = yield* appliedOffset(store, id);
3006
3526
  const rows = /* @__PURE__ */ new Map();
3007
- for (const [key, value] of yield* storedValues(sql, id, collection, keys)) rows.set(key, yield* readValue(collection, value));
3527
+ for (const [key, value] of yield* storedValues(store, id, collection, keys)) rows.set(key, yield* readValue(collection, value));
3008
3528
  return {
3009
3529
  offset,
3010
3530
  rows
3011
3531
  };
3012
3532
  }),
3013
3533
  list: Effect.fn("StateTable.list")(function* (collection, options = {}) {
3014
- if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit <= 0)) return yield* new ProjectionFault({
3015
- phase: "load",
3016
- reason: "invalid-options",
3017
- message: "StateTable list limit must be a positive safe integer"
3018
- });
3019
- const sql = yield* SqlClient.SqlClient;
3020
- const offset = yield* appliedOffset(sql, id);
3021
- const found = yield* sql`SELECT row_key, value FROM streamsy_state_rows
3022
- WHERE stream_id = ${id} AND collection = ${collection}
3023
- ${options.after === void 0 ? sql`` : sql`AND row_key > ${options.after}`}
3024
- ORDER BY row_key ${options.limit === void 0 ? sql`` : sql`LIMIT ${options.limit}`}`;
3534
+ if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit <= 0)) return yield* Effect.die(/* @__PURE__ */ new RangeError(`StateTable list option limit must be a positive safe integer, got ${String(options.limit)}`));
3535
+ const store = yield* currentStore;
3536
+ const offset = yield* appliedOffset(store, id);
3537
+ const found = yield* store.list(id, collection, options);
3025
3538
  const rows = yield* Effect.forEach(found, (row) => Effect.map(readValue(collection, row.value), (value) => ({
3026
3539
  key: row.row_key,
3027
3540
  value
@@ -3034,24 +3547,34 @@ const reads = (id, collections) => {
3034
3547
  })
3035
3548
  };
3036
3549
  };
3550
+ /** The collections of a bound table, for `unit`. */
3551
+ const TableCollections = Symbol.for("@streamsy/projection/internal/StateTableCollections");
3552
+ /** Private: tests read a memory store's committed rows through the owner's row store. */
3553
+ const TableStore = Symbol.for("@streamsy/projection/internal/StateTableStore");
3037
3554
  /** A State stream's declaration, kept current by the ordinary projection runners. */
3038
3555
  function define(state, options = {}) {
3039
3556
  const id = `state-table/${state.key}`;
3040
3557
  rejectProjectionVersion(id, options);
3041
- validateAccepted(options.accepted, state.paramCodecs, [state.template], transaction);
3558
+ rejectAccepted(id, options);
3559
+ validateFrontier(options.frontier, {
3560
+ commit: transaction,
3561
+ params: state.paramCodecs,
3562
+ inputTemplates: [state.template]
3563
+ });
3042
3564
  const declaration = declare({
3043
3565
  id,
3044
3566
  params: state.paramCodecs,
3045
3567
  inputs: {}
3046
3568
  }, ({ decoded, ...key }) => {
3047
- const address = state.at(decoded);
3569
+ const address = bindDeclaration(state, decoded);
3048
3570
  const raw = Object.assign(StreamAddress.json(address.id, { schema: Schema.String }), {
3049
3571
  stream: address.stream,
3050
3572
  codec: Schema.String
3051
3573
  });
3052
- const accepted = options.accepted?.at(decoded);
3053
- if (accepted?.id === address.id) throw new RangeError("An accepted stream may not name an input stream");
3054
- return {
3574
+ Object.defineProperty(raw, RawCollections, { value: state.collections });
3575
+ const accepted = options.frontier === void 0 ? void 0 : bindDeclaration(options.frontier, decoded);
3576
+ if (accepted?.id === address.id) throw new RangeError("A frontier stream may not name an input stream");
3577
+ const bound = {
3055
3578
  ...key,
3056
3579
  accepted,
3057
3580
  inputs: { state: raw },
@@ -3060,6 +3583,16 @@ function define(state, options = {}) {
3060
3583
  ...reads(address.id, state.collections),
3061
3584
  sync: () => synchronize(raw)
3062
3585
  };
3586
+ return Object.defineProperties(bound, {
3587
+ [TableCollections]: { value: state.collections },
3588
+ [TableStore]: { value: ownerStore }
3589
+ });
3590
+ }, {
3591
+ commit: transaction,
3592
+ ownedOutputs: options.frontier === void 0 ? [] : [{
3593
+ name: "frontier",
3594
+ stream: outputService(options.frontier)
3595
+ }]
3063
3596
  });
3064
3597
  return Object.assign(declaration, {
3065
3598
  inputs: { state },
@@ -3067,24 +3600,109 @@ function define(state, options = {}) {
3067
3600
  });
3068
3601
  }
3069
3602
  const clearIndex = (id) => Effect.gen(function* () {
3070
- const sql = yield* transactionClient(id);
3071
- yield* clearRows(sql, id);
3072
- yield* sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`;
3603
+ const store = yield* writer(id);
3604
+ yield* store.clearRows(id);
3605
+ yield* store.deleteHead(id);
3073
3606
  }).pipe(Effect.catchTag("SqlError", sqlFault(id)));
3074
3607
  /** Delete cached rows and their applied offset, even if the State stream has been removed. */
3075
3608
  const clear = Effect.fn("StateTable.clear")(function* (table) {
3076
- yield* (yield* Transaction).withTransaction(clearIndex(table.inputs.state.id));
3609
+ const owner = yield* StorageOwner;
3610
+ yield* inOwnerTransaction(owner)(clearIndex(table.inputs.state.id));
3077
3611
  });
3078
3612
  /** Discard the index and replay the State stream atomically, retaining the binding checkpoint. */
3079
3613
  const rebuild = Effect.fn("StateTable.rebuild")(function* (table) {
3080
- yield* (yield* Transaction).withTransaction(clearIndex(table.inputs.state.id).pipe(Effect.andThen(table.sync())));
3614
+ const owner = yield* StorageOwner;
3615
+ yield* inOwnerTransaction(owner)(clearIndex(table.inputs.state.id).pipe(Effect.andThen(table.sync())));
3081
3616
  });
3082
3617
  /** Append a reset to the State stream. The next table run applies it. */
3083
3618
  const reset = Effect.fn("StateTable.reset")(function* (table) {
3084
3619
  const address = table.inputs.state;
3085
3620
  const { wire } = yield* address.stream;
3086
3621
  const state = StreamAddress.state(address.id, { collections: {} });
3087
- return yield* Streams.append(state, [StreamAddress.reset()]).pipe(Effect.provideService(StreamsWriter, wire));
3622
+ return yield* Streams.append(state, [DurableState.reset()]).pipe(Effect.provideService(StreamsWriter, wire));
3623
+ });
3624
+ const unitFault = (reason) => new ProjectionFault({
3625
+ phase: "process",
3626
+ reason
3627
+ });
3628
+ /** The unit's map key for one row. */
3629
+ const rowId = (collection, key) => `${collection}\u0000${key}`;
3630
+ const isBoundTable = (table) => Predicate.hasProperty(table, TableCollections);
3631
+ /**
3632
+ * Create a missing unwrapped output, call `sync`, and open the unit's rows. Call it once
3633
+ * for each unit, inside a `Commit.transaction` handler, and return `changes()`.
3634
+ */
3635
+ const unit = Effect.fn("StateTable.unit")(function* (table) {
3636
+ if (!isBoundTable(table)) return yield* Effect.die(/* @__PURE__ */ new RangeError("StateTable.unit requires a table from define"));
3637
+ const collections = table[TableCollections];
3638
+ const address = table.inputs.state;
3639
+ const id = address.id;
3640
+ const store = yield* writer(id);
3641
+ const { wire } = yield* address.stream;
3642
+ const managed = yield* TransactionGenerationOutputs;
3643
+ const generationBound = managed !== void 0 && Array.some([...managed.values()], (output) => output.address.id === id);
3644
+ if (!generationBound) yield* wire.create(id, { contentType: address.contentType }).pipe(Effect.mapError((cause) => unitFault(outputReason(`Cannot write output ${id}`, cause))));
3645
+ yield* table.sync().pipe(Effect.mapError((cause) => generationBound && isInputLoss(cause) ? unitFault(new OutputRejected({
3646
+ message: `Cannot write output ${id}`,
3647
+ cause
3648
+ })) : cause));
3649
+ const known = /* @__PURE__ */ new Map();
3650
+ const entries = [];
3651
+ const collectionOf = (collection) => {
3652
+ const entry = collections[collection];
3653
+ if (entry === void 0) throw new RangeError(`Unknown State collection ${collection}`);
3654
+ return entry;
3655
+ };
3656
+ const read = (collection, keys) => storedValues(store, id, collection, keys).pipe(Effect.mapError((cause) => unitFault(storageFault("stateTable.values")(cause))), Effect.map((found) => {
3657
+ for (const key of keys) known.set(rowId(collection, key), { json: found.get(key) });
3658
+ }));
3659
+ const current = (collection, key) => Effect.gen(function* () {
3660
+ const found = known.get(rowId(collection, key));
3661
+ if (found !== void 0) return found;
3662
+ yield* read(collection, [key]);
3663
+ return known.get(rowId(collection, key)) ?? { json: void 0 };
3664
+ });
3665
+ return {
3666
+ load: (collection, keys) => Effect.suspend(() => {
3667
+ const missing = Array.filter([...new Set(keys)], (key) => !known.has(rowId(collection, key)));
3668
+ return missing.length === 0 ? Effect.void : read(collection, missing);
3669
+ }),
3670
+ get: (collection, key) => Effect.gen(function* () {
3671
+ const schema = collectionOf(collection).schema;
3672
+ const found = yield* current(collection, key);
3673
+ if (found.json === void 0) return void 0;
3674
+ if (!("value" in found)) found.value = yield* decodeRow(schema, found.json).pipe(Effect.mapError((cause) => unitFault(new InvalidRecord({
3675
+ message: `Row ${key} of ${id} does not decode`,
3676
+ cause
3677
+ }))));
3678
+ return found.value;
3679
+ }),
3680
+ upsert: (collection, row, options = {}) => Effect.gen(function* () {
3681
+ const entry = collectionOf(collection);
3682
+ const schema = entry.schema;
3683
+ const field = entry.key;
3684
+ const key = Predicate.hasProperty(row, field) ? String(row[field]) : "undefined";
3685
+ const before = yield* current(collection, key);
3686
+ const after = yield* encodeRow(schema, row).pipe(Effect.mapError((cause) => unitFault(new EncodeFault({
3687
+ message: `Cannot encode row ${key} of ${id}`,
3688
+ cause
3689
+ }))));
3690
+ if (after === before.json) return false;
3691
+ known.set(rowId(collection, key), {
3692
+ json: after,
3693
+ value: row
3694
+ });
3695
+ entries.push(DurableState.upsert(collection, row, options));
3696
+ return true;
3697
+ }),
3698
+ remove: (collection, key, options = {}) => Effect.gen(function* () {
3699
+ if ((yield* current(collection, key)).json === void 0) return false;
3700
+ known.set(rowId(collection, key), { json: void 0 });
3701
+ entries.push(DurableState.remove(collection, key, options));
3702
+ return true;
3703
+ }),
3704
+ changes: () => [...entries]
3705
+ };
3088
3706
  });
3089
3707
  // src/fold-by-key-error.ts
3090
3708
  /** A folded row disagreed with the key that was used to load its previous row. */
@@ -3097,13 +3715,11 @@ var fold_by_key_exports = /* @__PURE__ */ __exportAll({
3097
3715
  /** Return this from a fold to delete its row. The next record receives undefined. */
3098
3716
  const remove = Symbol("@streamsy/projection/FoldByKey.remove");
3099
3717
  const isEffect = (step) => Effect.isEffect(step);
3100
- const fault = (reason, message) => (cause) => new ProjectionFault({
3718
+ const processFault = (reason) => new ProjectionFault({
3101
3719
  phase: "process",
3102
- reason,
3103
- message,
3104
- cause
3720
+ reason
3105
3721
  });
3106
- const writeFault = (id) => (cause) => fault(isStreamsFault(cause) ? "storage-failure" : Predicate.isTagged(cause, "StreamBusy") ? "output-busy" : "invalid-output", `Cannot write output ${id}`)(cause);
3722
+ const writeFault = (id) => (cause) => processFault(outputReason(`Cannot write output ${id}`, cause));
3107
3723
  const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function* () {
3108
3724
  const output = outputs[spec.output];
3109
3725
  const collection = output.collections[spec.collection];
@@ -3112,7 +3728,10 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
3112
3728
  const { wire } = yield* output.stream;
3113
3729
  const generationBound = (yield* TransactionGenerationOutputs)?.get(spec.output)?.address.id === output.id;
3114
3730
  if (!generationBound) yield* wire.create(output.id, { contentType: output.contentType }).pipe(Effect.mapError(writeFault(output.id)));
3115
- yield* table.at(params.value).sync().pipe(Effect.mapError((cause) => generationBound && cause.reason === "history-unavailable" ? fault("invalid-output", `Cannot write output ${output.id}`)(cause) : cause));
3731
+ yield* bindDeclaration(table, params.value).sync().pipe(Effect.mapError((cause) => generationBound && isInputLoss(cause) ? processFault(new OutputRejected({
3732
+ message: `Cannot write output ${output.id}`,
3733
+ cause
3734
+ })) : cause));
3116
3735
  const groups = /* @__PURE__ */ new Map();
3117
3736
  for (const { item } of items(batch)) for (const record of spec.records(item, unit)) {
3118
3737
  const key = spec.key(record, unit);
@@ -3121,12 +3740,16 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
3121
3740
  if (group === void 0) groups.set(key, [record]);
3122
3741
  else group.push(record);
3123
3742
  }
3124
- const stored = yield* storedValues(yield* SqlClient.SqlClient, output.id, spec.collection, [...groups.keys()]).pipe(Effect.mapError(fault("storage-failure", `Cannot read the rows of ${output.id}`)));
3743
+ const store = yield* currentStore;
3744
+ const stored = yield* storedValues(store, output.id, spec.collection, [...groups.keys()]).pipe(Effect.mapError((cause) => processFault(storageFault("stateTable.values")(cause))));
3125
3745
  const schema = collection.schema;
3126
3746
  const changes = [];
3127
3747
  for (const [key, records] of groups) {
3128
3748
  const before = stored.get(key);
3129
- let value = before === void 0 ? void 0 : yield* decodeRow(schema, before).pipe(Effect.mapError(fault("invalid-record", `Row ${key} of ${output.id} does not decode`)));
3749
+ let value = before === void 0 ? void 0 : yield* decodeRow(schema, before).pipe(Effect.mapError((cause) => processFault(new InvalidRecord({
3750
+ message: `Row ${key} of ${output.id} does not decode`,
3751
+ cause
3752
+ }))));
3130
3753
  for (const record of records) {
3131
3754
  const step = spec.fold(value, record, unit);
3132
3755
  const next = isEffect(step) ? yield* step : step;
@@ -3139,7 +3762,12 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
3139
3762
  const field = collection.key;
3140
3763
  const actual = Predicate.hasProperty(value, field) ? String(value[field]) : "undefined";
3141
3764
  if (actual !== key) return yield* new FoldByKeyError({ message: `FoldByKey key "${key}" differs from folded row key "${actual}"` });
3142
- const after = yield* encodeRow(schema, value).pipe(Effect.mapError(fault("invalid-output", `Cannot encode row ${key} of ${output.id}`)));
3765
+ const rejected = store.unstorable(spec.collection, key);
3766
+ if (Option.isSome(rejected)) return yield* processFault(new OutputRejected({ message: `Cannot write a row of ${output.id}. ${rejected.value}` }));
3767
+ const after = yield* encodeRow(schema, value).pipe(Effect.mapError((cause) => processFault(new EncodeFault({
3768
+ message: `Cannot encode row ${key} of ${output.id}`,
3769
+ cause
3770
+ }))));
3143
3771
  if (after !== before) changes.push(upsertJson(spec.collection, key, after));
3144
3772
  }
3145
3773
  if (Array.isReadonlyArrayNonEmpty(changes)) yield* wire.append(output.id, {
@@ -3176,12 +3804,12 @@ function process(table, spec) {
3176
3804
  const attach = (projection, options = {}) => {
3177
3805
  const runner = runnerOf(projection, options, true, "wakeup");
3178
3806
  return Effect.gen(function* () {
3807
+ yield* requireTriggers(options.triggers);
3179
3808
  const { next, drain, deferred, status, schedule, rescan, retry, failed } = yield* runner;
3180
3809
  let host;
3181
3810
  let running = false;
3182
3811
  let lastPassAt = Option.none();
3183
- const registry = yield* Effect.serviceOption(Registry);
3184
- const changed = Option.isNone(registry) ? Effect.void : yield* registerRunner(registry.value, {
3812
+ const changed = yield* registerRunner(yield* StorageOwner, {
3185
3813
  id: projection.id,
3186
3814
  generation: projection.generation,
3187
3815
  status: Effect.gen(function* () {
@@ -3230,4 +3858,4 @@ const attach = (projection, options = {}) => {
3230
3858
  });
3231
3859
  };
3232
3860
  const ProjectionWakeup = { attach };
3233
- export { CheckpointRecord, CheckpointStore, commit_exports as Commit, fold_by_key_exports as FoldByKey, FoldByKeyError, HandlerFailed, InvalidBinding, NonRetryable, NotAttached, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, RunnerEvent, state_table_exports as StateTable, Transaction };
3861
+ export { CheckpointRecord, CheckpointStore, commit_exports as Commit, fold_by_key_exports as FoldByKey, FoldByKeyError, GenerationMismatch, HandlerFailed, HistoryUnavailable, IdentityMismatch, InputNotFound, InvalidBinding, InvalidRecord, InvalidSource, InvalidWakeTime, NonRetryable, NotAttached, OutputRejected, projection_exports as Projection, ProjectionFault, ProjectionFaultReason, ProjectionRetry, ProjectionWakeup, RangeUnreproducible, RetiredGeneration, RunnerEvent, state_table_exports as StateTable, SupersededGeneration, TokenConflict, UnsupportedComposition, isFrontierCollection, unitFrontiers, validateFrontier };