@streamsy/projection 0.11.0 → 0.13.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,15 +1,16 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { a as rangesOf, c as canonicalParams, d as withParams, f as ProjectionFault, l as terminalOf, n as CheckpointStore, r as advance, s as restore, t as CheckpointRecord, u as unitOf } from "./checkpoint-store-Bm8z-f-l.js";
3
- import { Array, Cause, Clock, Context, Data, Duration, Effect, Exit, Function, Layer, Option, Pipeable, Predicate, PubSub, Record, Ref, Result, Schedule, Schema, Stream } from "effect";
4
- import { CommitBoundary, DurableState, Offset, Storage, StreamAddress, StreamId, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
2
+ import { _ as ProjectionFault, a as rangesOf, c as unsupportedBindingList, d as terminalOf, f as unitOf, g as NotAttached, h as NonRetryable, l as canonicalParams, m as InvalidBinding, n as CheckpointStore, o as recordKey, p as withParams, r as advance, s as restore, t as CheckpointRecord, u as encodeKey } from "./checkpoint-store-ViVETLzZ.js";
3
+ import { Array, Cause, Clock, Context, Data, DateTime, Deferred, Duration, Effect, Exit, Function, Layer, Option, 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";
5
6
  import { Streams, StreamsWriter } from "@streamsy/core/protocol";
6
- import { CommitHooks, CurrentOwner, MAX_PRODUCER_ID_LENGTH, ProjectionMarks, compileSegments, fitKey, isForeignOwner, ownerOf } from "@streamsy/core/internal";
7
7
  import { SqlClient } from "effect/sql";
8
8
  // src/batch.ts
9
9
  /** An input that was skipped this pass: nothing read, nothing known beyond its cursor. */
10
10
  const emptySlice = (from) => ({
11
11
  from,
12
12
  items: [],
13
+ offsets: [],
13
14
  nextOffset: from,
14
15
  upToDate: false,
15
16
  closed: false
@@ -64,14 +65,26 @@ const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, f
64
65
  input,
65
66
  message: `Read of ${address.id} did not advance past ${from}`
66
67
  });
67
- return { slice: {
68
+ const items = yield* decodeMessages(input, address, result.messages);
69
+ const offsets = pageOffsets(result);
70
+ const slice = {
68
71
  from,
69
- items: yield* decodeMessages(input, address, result.messages),
72
+ items,
70
73
  nextOffset: result.nextOffset,
71
74
  upToDate: result.upToDate,
72
75
  closed: result.closed
76
+ };
77
+ return { slice: offsets === void 0 ? slice : {
78
+ ...slice,
79
+ offsets
73
80
  } };
74
81
  });
82
+ /** Empty reads know all their offsets; malformed metadata is treated as unavailable. */
83
+ const pageOffsets = (result) => {
84
+ if (result.messages.length === 0) return [];
85
+ const offsets = offsetsOf(result);
86
+ return offsets?.length === result.messages.length ? offsets : void 0;
87
+ };
75
88
  /**
76
89
  * A lost history is terminal only when a known input's head confirms it is gone.
77
90
  * A pinned unit is replayed with `reproduce` and never takes this path: a
@@ -128,6 +141,7 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
128
141
  } };
129
142
  }
130
143
  let messages = [];
144
+ let offsets = [];
131
145
  let cursor = range.from;
132
146
  let last;
133
147
  while (messages.length < range.count) {
@@ -157,6 +171,9 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
157
171
  })
158
172
  }));
159
173
  if (page.messages.length === 0) return yield* unreproducible("the input ended early");
174
+ const pageOffsetsValue = pageOffsets(page);
175
+ if (offsets !== void 0 && pageOffsetsValue !== void 0) offsets.push(...pageOffsetsValue);
176
+ else offsets = void 0;
160
177
  messages.push(...page.messages);
161
178
  cursor = page.nextOffset;
162
179
  last = page;
@@ -167,14 +184,19 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
167
184
  if (cursor !== range.nextOffset) return yield* unreproducible(`the range ends at ${cursor}, not ${range.nextOffset}`);
168
185
  } else {
169
186
  messages = messages.slice(0, range.count);
187
+ offsets = offsets?.slice(0, range.count);
170
188
  if (compare(cursor, range.nextOffset) < 0) return yield* unreproducible("the input is shorter than the pin");
171
189
  }
172
- return { slice: {
190
+ const slice = {
173
191
  from: range.from,
174
192
  items: yield* decodeMessages(input, address, messages),
175
193
  nextOffset: range.nextOffset,
176
194
  upToDate: range.upToDate ?? (last.upToDate && cursor === range.nextOffset),
177
195
  closed: range.closed === true
196
+ };
197
+ return { slice: offsets === void 0 ? slice : {
198
+ ...slice,
199
+ offsets
178
200
  } };
179
201
  });
180
202
  /** Read one server page per input in declaration order. */
@@ -195,102 +217,56 @@ const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets
195
217
  /** Tagged items in declaration order, then stream order within each input. */
196
218
  const items = (batch) => {
197
219
  const out = [];
198
- for (const [input, slice] of Record.toEntries(batch)) for (const item of slice.items) out.push({
199
- input,
200
- item,
201
- index: out.length
202
- });
203
- return out;
204
- };
205
- // src/outputs.ts
206
- /** Resolve routes just like inputs, retaining the route codec and collection names. */
207
- const resolveOutputs = (outputs, params, inputs) => {
208
- const streams = addressesOf(outputs, params);
209
- const ids = Array.map(Record.values(streams), (address) => address.id);
210
- if (new Set(ids).size !== ids.length) throw new RangeError("Two outputs may not name the same stream");
211
- const inputIds = new Set(Array.map(Record.values(inputs), (address) => address.id));
212
- if (Array.some(ids, (id) => inputIds.has(id))) throw new RangeError("An output may not name an input stream");
213
- if (Array.some(Record.values(streams), (address) => !Predicate.isTagged(address, "Json"))) throw new RangeError("Projection outputs require JSON or state routes");
214
- return streams;
215
- };
216
- const collect = (outputs, buffers, emitted) => Effect.gen(function* () {
217
- for (const [name, entries] of Record.toEntries(emitted)) {
218
- const output = outputs[name];
219
- if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* new ProjectionFault({
220
- phase: "process",
221
- reason: "invalid-output",
222
- message: `Invalid output array ${name}`
223
- });
224
- const values = yield* Effect.try({
225
- try: () => "collections" in output ? DurableState.changes(output, {}, entries) : entries,
226
- catch: (cause) => new ProjectionFault({
227
- phase: "process",
228
- reason: "invalid-output",
229
- message: `Invalid row change for ${name}`,
230
- cause
231
- })
220
+ for (const [input, slice] of Record.toEntries(batch)) for (const [i, item] of slice.items.entries()) {
221
+ const offset = slice.offsets?.[i];
222
+ const entry = {
223
+ input,
224
+ item,
225
+ index: out.length
226
+ };
227
+ out.push(offset === void 0 ? entry : {
228
+ ...entry,
229
+ offset
232
230
  });
233
- (buffers[name] ??= []).push(...values);
234
231
  }
235
- return yield* Effect.void;
236
- });
237
- const pin$1 = (reason, message, cause) => new ProjectionFault({
238
- phase: "pin",
239
- reason,
240
- message,
241
- cause
242
- });
243
- /** Append one unit under its pinned tuple; appended and duplicate are one outcome. */
244
- const appendPinned = Effect.fn("Projection.appendPinned")(function* (output, wire, items, position) {
245
- return yield* Streams.append(output, items, { producer: position }).pipe(Effect.provideService(StreamsWriter, wire), Effect.catchTags({
246
- EncodeFault: () => new ProjectionFault({
247
- phase: "process",
248
- reason: "invalid-output",
249
- message: `Cannot encode output for ${output.id}`
250
- }),
251
- StaleEpoch: (error) => pin$1("stale-epoch", `Epoch ${position.producerEpoch} of ${output.id} is behind ${error.currentEpoch}`),
252
- ProducerGap: (error) => pin$1("invalid-record", `Sequence ${error.receivedSeq} of ${output.id} does not follow ${error.expectedSeq}`),
253
- NotSupported: (error) => pin$1("unsupported-composition", `${output.id} does not support ${error.feature}`),
254
- StorageFault: (cause) => pin$1("storage-failure", `Cannot append to ${output.id}`, cause),
255
- TransportFault: (cause) => pin$1("storage-failure", `Cannot append to ${output.id}`, cause),
256
- StreamNotFound: () => pin$1("invalid-output", `Output ${output.id} does not exist`),
257
- StreamGone: () => pin$1("invalid-output", `Output ${output.id} is gone`),
258
- StreamClosed: () => pin$1("invalid-output", `Output ${output.id} is closed`),
259
- AppendConflict: () => pin$1("invalid-output", `Output ${output.id} refused the append`),
260
- StreamBusy: () => pin$1("invalid-output", `Output ${output.id} is busy`)
261
- }));
262
- });
232
+ return out;
233
+ };
263
234
  // src/commit/range.ts
264
235
  const RangeKey = Symbol.for("@streamsy/projection/internal/Range");
265
236
  const extend = (commit) => Object.defineProperty(commit, RangeKey, {
266
237
  value: "extend",
267
238
  configurable: true
268
239
  });
269
- const pin = (commit) => Object.defineProperty(commit, RangeKey, {
240
+ const pin$1 = (commit) => Object.defineProperty(commit, RangeKey, {
270
241
  value: "pin",
271
242
  configurable: true
272
243
  });
273
244
  const isPinned = (commit) => RangeKey in commit && commit[RangeKey] === "pin";
274
245
  const inherit = (source, target) => {
275
246
  if (supportsPrepare(source)) withPrepare(target);
276
- return isPinned(source) ? pin(target) : extend(target);
247
+ if (supportsAccepted(source)) withAccepted(target);
248
+ return isPinned(source) ? pin$1(target) : extend(target);
277
249
  };
278
250
  const PrepareKey = Symbol.for("@streamsy/projection/internal/Prepare");
279
251
  const withPrepare = (commit) => Object.defineProperty(commit, PrepareKey, { value: true });
280
252
  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;
281
256
  // src/commit/model.ts
282
- const TypeId = "~@streamsy/projection/Commit";
257
+ const TypeId$1 = "~@streamsy/projection/Commit";
283
258
  /** Opaque to Commit authors; the kernel restores the original typed handler error. */
284
259
  var HandlerFailed = class extends Schema.TaggedError()("HandlerFailed", { error: Schema.Unknown }) {};
285
260
  const { Folded, Emitted, Accumulated } = Data.taggedEnum();
286
261
  /** Custom Commits extend the input range on retry. Never store next when run fails;
287
262
  * condition the write on loaded.token (checkpoint / token-conflict when it moved),
288
263
  * and return token "0" for an absent record.
264
+ * Custom Commits do not support timer handlers in this release.
289
265
  * load must return the stored state. If run and the write are not atomic,
290
266
  * declare at-least-once. The guarantee must describe the actual write. */
291
267
  const make$1 = (options) => extend({
292
268
  ...options,
293
- [TypeId]: {
269
+ [TypeId$1]: {
294
270
  result: () => {},
295
271
  provides: () => {},
296
272
  requires: () => {
@@ -312,10 +288,22 @@ const detailsOf = (pending) => {
312
288
  };
313
289
  const load = (key) => CheckpointStore.use((store) => store.load(key));
314
290
  const remove$1 = (key) => CheckpointStore.use((store) => store.remove(key));
315
- const withState = (next, result) => result !== void 0 && "encoded" in result ? {
316
- ...next,
317
- state: result.encoded
318
- } : next;
291
+ const retire$1 = ({ key, cleanup }) => CheckpointStore.use((store) => store.retire === void 0 ? Effect.fail(new ProjectionFault({
292
+ phase: "checkpoint",
293
+ reason: "unsupported-composition",
294
+ message: `The checkpoint store cannot retire ${key.id}`
295
+ })) : store.retire(key).pipe(Effect.tap(() => cleanup)));
296
+ /** Merge the handler's state and timer into the same checkpoint write. */
297
+ const withState = (next, result) => {
298
+ const stored = result !== void 0 && "encoded" in result ? {
299
+ ...next,
300
+ state: result.encoded
301
+ } : next;
302
+ return result !== void 0 && "wakeAt" in result ? {
303
+ ...stored,
304
+ wakeAt: result.wakeAt
305
+ } : stored;
306
+ };
319
307
  const beforeRecord = (pending) => Option.getOrElse(pending.loaded.record, () => ({
320
308
  ...pending.next,
321
309
  inputs: Record.fromEntries(Array.map(Record.toEntries(pending.next.inputs), ([name, offset]) => [name, pending.unit.ranges[name]?.from ?? offset]))
@@ -327,6 +315,7 @@ const checkpoint = make$1({
327
315
  guarantee: "exactly-once",
328
316
  load,
329
317
  remove: remove$1,
318
+ retire: retire$1,
330
319
  apply: (pending) => Effect.flatMap(pending.run, (result) => settle(pending, result))
331
320
  });
332
321
  // src/transaction.ts
@@ -351,30 +340,170 @@ var Transaction = class extends Context.Service()("@streamsy/projection/Transact
351
340
  };
352
341
  }));
353
342
  };
343
+ // src/per-generation.ts
344
+ const TypeId = Symbol.for("@streamsy/projection/PerGeneration");
345
+ function perGeneration(route, param, options) {
346
+ const shared = options?.shared ?? false;
347
+ const routeBy = options?.routeBy;
348
+ return { [TypeId]: routeBy === void 0 ? {
349
+ route,
350
+ param,
351
+ shared
352
+ } : {
353
+ route,
354
+ param,
355
+ shared,
356
+ routeBy: Object.freeze([...routeBy])
357
+ } };
358
+ }
359
+ const isPerGeneration = (value) => TypeId in value;
360
+ const generationBinding = (binding) => binding[TypeId];
361
+ const validateGenerationParam = (output, params) => {
362
+ if (!isPerGeneration(output)) return;
363
+ const { route, param, routeBy, shared } = generationBinding(output);
364
+ if (Record.has(params, param)) throw new RangeError(`Generation-bound parameter ${param} must not be a projection parameter`);
365
+ if (routeBy === void 0) return;
366
+ if (shared) throw new RangeError("Routed outputs cannot be shared");
367
+ if (routeBy.length === 0 || new Set(routeBy).size !== routeBy.length) throw new RangeError("routeBy requires one or more distinct route parameters");
368
+ const names = Array.filterMap(route.template.split("/"), (part) => part.startsWith(":") ? Result.succeed(part.slice(1)) : Result.fail(void 0));
369
+ for (const name of routeBy) {
370
+ if (!names.includes(name)) throw new RangeError(`Routed parameter ${name} must be a route parameter`);
371
+ if (name === param || Record.has(params, name)) throw new RangeError(`Routed parameter ${name} must not be a generation or projection parameter`);
372
+ }
373
+ for (const name of names) if (name !== param && !routeBy.includes(name) && !Record.has(params, name)) throw new RangeError(`Missing projection parameter ${name} for routed output`);
374
+ };
375
+ /** Private metadata on the bound value. */
376
+ const GenerationOutputs = Symbol.for("@streamsy/projection/internal/GenerationOutputs");
377
+ /** Outputs whose creation is managed by the current transaction. */
378
+ const TransactionGenerationOutputs = Context.Reference("@streamsy/projection/internal/TransactionGenerationOutputs", { defaultValue: () => void 0 });
379
+ // src/routed-outputs.ts
380
+ const RoutedOutputs = Symbol.for("@streamsy/projection/internal/RoutedOutputs");
381
+ const processFault = (reason, message, cause) => new ProjectionFault({
382
+ phase: "process",
383
+ reason,
384
+ message,
385
+ cause
386
+ });
387
+ const requireRouteRecords = (store, phase) => store?.routes === void 0 ? Effect.fail(new ProjectionFault({
388
+ phase,
389
+ reason: "unsupported-composition",
390
+ message: "This CheckpointStore does not support routed outputs"
391
+ })) : Effect.succeed(store.routes);
392
+ const currentRouteRecords = Effect.serviceOption(CheckpointStore).pipe(Effect.flatMap((store) => requireRouteRecords(Option.getOrUndefined(store), "checkpoint")));
393
+ const routedUnit = (key, store) => ({
394
+ key: recordKey(key),
395
+ store,
396
+ opened: /* @__PURE__ */ new Map(),
397
+ lock: Semaphore.makeUnsafe(1)
398
+ });
399
+ const TransactionRoutedOutputs = Context.Reference("@streamsy/projection/internal/TransactionRoutedOutputs", { defaultValue: () => void 0 });
400
+ const routedDefinition = (route) => ({
401
+ matches: route.match,
402
+ restore: (id) => {
403
+ const parsed = route.parse(id);
404
+ if (Option.isNone(parsed)) return void 0;
405
+ const address = route.at(parsed.value);
406
+ return address.id === id ? address : void 0;
407
+ }
408
+ });
409
+ const routedHandle = (name, route, names, params, key, occupied, routed) => ({ open: (values) => Effect.gen(function* () {
410
+ const unit = yield* TransactionRoutedOutputs;
411
+ if (unit === void 0 || unit.key !== recordKey(key)) return yield* processFault("unsupported-composition", `Routed output ${name} requires its binding's process transaction`);
412
+ const address = yield* Effect.try({
413
+ try: () => {
414
+ if (Record.keys(values).length !== names.length || !Array.every(names, (param) => Record.has(values, param))) throw new RangeError(`Expected route parameters ${Array.join(names, ", ")}`);
415
+ return route.at({
416
+ ...params,
417
+ ...values
418
+ });
419
+ },
420
+ catch: (cause) => processFault("invalid-output", `Cannot resolve routed output ${name}: ${cause instanceof RangeError ? cause.message : String(cause)}`, cause)
421
+ });
422
+ if (occupied.has(address.id)) return yield* processFault("invalid-output", `Routed output ${name} overlaps an input or output at ${address.id}`);
423
+ if (!Predicate.isTagged(address, "Json")) return yield* processFault("invalid-output", "Projection outputs require JSON or state routes");
424
+ const service = yield* address.stream;
425
+ const owner = yield* CurrentOwner;
426
+ if (service.owner !== owner) return yield* processFault("unsupported-composition", `Output ${address.id} does not share the transaction owner`);
427
+ return yield* unit.lock.withPermits(1)(Effect.gen(function* () {
428
+ const opened = unit.opened.get(address.id);
429
+ if (opened === name) return address;
430
+ if (opened !== void 0) return yield* processFault("invalid-output", `Routed outputs ${opened} and ${name} both name ${address.id}`);
431
+ const records = yield* requireRouteRecords(unit.store, "process");
432
+ if (!(yield* records.has(key, name, address.id))) {
433
+ 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}`);
434
+ const created = yield* createOutput(address, service.wire);
435
+ if (created.closed || created.nextOffset !== ZERO_OFFSET) return yield* processFault("invalid-output", `Generation-bound output ${address.id} must start empty and open`);
436
+ yield* records.add(key, name, address.id);
437
+ }
438
+ unit.opened.set(address.id, name);
439
+ return address;
440
+ }));
441
+ }) });
354
442
  // src/commit/transaction.ts
443
+ const removeWithRoutes = (key) => Effect.gen(function* () {
444
+ const store = yield* CheckpointStore;
445
+ const tx = yield* Transaction;
446
+ if (ownerOf(store.load) !== tx.owner) return yield* new ProjectionFault({
447
+ phase: "checkpoint",
448
+ reason: "unsupported-composition",
449
+ message: `The checkpoint store for ${key.id} does not share the transaction owner`
450
+ });
451
+ const records = yield* requireRouteRecords(store, "checkpoint");
452
+ if (yield* store.load(key).pipe(Effect.map(({ record }) => Option.isSome(record)), Effect.catchIf((fault) => fault.reason === "retired-generation", () => Effect.succeed(false)), Effect.catchIf((fault) => fault.reason === "invalid-record", () => Effect.succeed(true)))) {
453
+ yield* records.clear(key);
454
+ yield* store.remove(key);
455
+ }
456
+ return yield* Effect.void;
457
+ });
458
+ const retireInTransaction = (request) => Effect.gen(function* () {
459
+ const tx = yield* Transaction;
460
+ const store = yield* CheckpointStore;
461
+ if (ownerOf(store.load) !== tx.owner) return yield* new ProjectionFault({
462
+ phase: "checkpoint",
463
+ reason: "unsupported-composition",
464
+ message: `The checkpoint store for ${request.key.id} does not share the transaction owner`
465
+ });
466
+ return yield* tx.withTransaction(retire$1(request).pipe(Effect.provideService(CurrentOwner, tx.owner)));
467
+ });
355
468
  const transaction = withPrepare(make$1({
356
469
  name: "transaction",
357
470
  guarantee: "exactly-once",
358
471
  load,
359
- remove: remove$1,
472
+ remove: (key) => RoutedOutputs in key ? Transaction.use((tx) => tx.withTransaction(removeWithRoutes(key))) : remove$1(key),
473
+ retire: retireInTransaction,
360
474
  apply: (pending) => Effect.gen(function* () {
361
475
  const tx = yield* Transaction;
362
476
  const store = yield* CheckpointStore;
363
- const outputs = detailsOf(pending).outputs;
477
+ const { outputs, prepare } = detailsOf(pending);
478
+ const hasRoutes = RoutedOutputs in pending.key;
479
+ if (hasRoutes && ownerOf(store.load) !== tx.owner) return yield* new ProjectionFault({
480
+ phase: "checkpoint",
481
+ reason: "unsupported-composition",
482
+ message: `The checkpoint store for ${pending.key.id} does not share the transaction owner`
483
+ });
364
484
  for (const { address, service } of Record.values(outputs)) if (service.owner !== tx.owner) return yield* new ProjectionFault({
365
485
  phase: "load",
366
486
  reason: "unsupported-composition",
367
487
  message: `Output ${address.id} does not share the transaction owner`
368
488
  });
369
- const prepare = detailsOf(pending).prepare;
370
489
  if (prepare !== void 0) yield* prepare;
371
490
  yield* tx.withTransaction(Effect.gen(function* () {
372
- if ((yield* store.load(pending.key)).token !== pending.loaded.token) return yield* new ProjectionFault({
491
+ const again = yield* store.load(pending.key);
492
+ if (again.token !== pending.loaded.token) return yield* new ProjectionFault({
373
493
  phase: "checkpoint",
374
494
  reason: "token-conflict",
375
495
  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.`
376
496
  });
377
- const result = yield* pending.run.pipe(Effect.provideService(SqlClient.SqlClient, tx.sql), Effect.provideService(CurrentOwner, tx.owner), Effect.catchDefect((defect) => isForeignOwner(defect) ? Effect.fail(new ProjectionFault({
497
+ if (Option.isNone(again.record)) for (const { address, service, generation } of Record.values(outputs)) {
498
+ if (generation === void 0) continue;
499
+ const created = yield* createOutput(address, service.wire);
500
+ if (!generation.shared && (created.closed || created.nextOffset !== ZERO_OFFSET)) return yield* new ProjectionFault({
501
+ phase: "process",
502
+ reason: "invalid-output",
503
+ message: `Generation-bound output ${address.id} must start empty and open`
504
+ });
505
+ }
506
+ const result = yield* pending.run.pipe(Effect.provideService(SqlClient.SqlClient, tx.sql), Effect.provideService(CurrentOwner, tx.owner), Effect.provideService(TransactionGenerationOutputs, pending.generationOutputs), Effect.provideService(TransactionRoutedOutputs, hasRoutes ? routedUnit(pending.key, store) : void 0), Effect.catchDefect((defect) => isForeignOwner(defect) ? Effect.fail(new ProjectionFault({
378
507
  phase: "process",
379
508
  reason: "unsupported-composition",
380
509
  message: defect.message
@@ -389,7 +518,7 @@ const transaction = withPrepare(make$1({
389
518
  });
390
519
  yield* Streams.append(output.address, output.items).pipe(Effect.provideService(StreamsWriter, resolved.service.wire), Effect.mapError((cause) => new ProjectionFault({
391
520
  phase: "process",
392
- reason: "invalid-output",
521
+ reason: isStreamsFault(cause) ? "storage-failure" : Predicate.isTagged(cause, "StreamBusy") ? "output-busy" : "invalid-output",
393
522
  message: `Cannot append to ${output.address.id}`,
394
523
  cause
395
524
  })));
@@ -399,7 +528,16 @@ const transaction = withPrepare(make$1({
399
528
  }));
400
529
  return yield* Effect.void;
401
530
  })
402
- }));
531
+ })).pipe(withAccepted);
532
+ /** Clean up binding state in the owner transaction on both forget and retire. */
533
+ const transactionWithCleanup = (cleanup) => inherit(transaction, {
534
+ ...transaction,
535
+ remove: (key) => Transaction.use((tx) => tx.withTransaction((RoutedOutputs in key ? removeWithRoutes(key) : remove$1(key)).pipe(Effect.andThen(() => cleanup(key, tx.sql))))),
536
+ retire: (request) => Transaction.use((tx) => retireInTransaction({
537
+ ...request,
538
+ cleanup: request.cleanup.pipe(Effect.andThen(() => cleanup(request.key, tx.sql)))
539
+ }))
540
+ });
403
541
  // src/commit/producer.ts
404
542
  /**
405
543
  * The pinned tuple identity: the params join the id so two parameterisations never share a sequence.
@@ -409,9 +547,9 @@ const transaction = withPrepare(make$1({
409
547
  */
410
548
  const producerId = (id, version, params) => fitKey(`${id}/v${version}${Record.keys(params).length === 0 ? "" : `/${canonicalParams(params)}`}`, MAX_PRODUCER_ID_LENGTH, `${id}/v${version}/`);
411
549
  /** The head of one output. A missing output on the checkpoint's owner is created here. */
412
- const prepareOutput = (output, store) => {
550
+ const prepareOutput = (output, store, beforeCreate) => {
413
551
  const { wire, owner: outputOwner } = output.service;
414
- return wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== ownerOf(store.load) ? Effect.fail(cause) : Streams.create(output.address).pipe(Effect.provideService(StreamsWriter, wire), Effect.andThen(wire.head(output.address.id)))), Effect.mapError((cause) => new ProjectionFault({
552
+ 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({
415
553
  phase: "pin",
416
554
  reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
417
555
  message: `Cannot prepare output ${output.address.id}`,
@@ -424,10 +562,11 @@ const asPin = (fault) => fault.phase === "checkpoint" && fault.reason === "token
424
562
  reason: fault.reason,
425
563
  message: fault.message
426
564
  }) : fault;
427
- const producer = pin(make$1({
565
+ const producer = pin$1(make$1({
428
566
  name: "producer",
429
567
  guarantee: "effectively-once",
430
568
  remove: remove$1,
569
+ retire: retire$1,
431
570
  load: (key) => Effect.gen(function* () {
432
571
  const loaded = yield* load(key);
433
572
  if (Option.isSome(loaded.record)) {
@@ -477,13 +616,27 @@ const producer = pin(make$1({
477
616
  }
478
617
  let token = before.token;
479
618
  if (pending === void 0 && Record.keys(seqs).length > 0) {
619
+ const checkBeforeCreate = Effect.gen(function* () {
620
+ if ((yield* owner.load(projection)).token !== before.token) return yield* new ProjectionFault({
621
+ phase: "pin",
622
+ reason: "token-conflict",
623
+ message: `Record for ${projection.id} changed before creating an output`
624
+ });
625
+ return yield* Effect.void;
626
+ });
480
627
  for (const [name, output] of Record.toEntries(streams)) {
481
628
  if (seqs[name] === void 0) continue;
482
- if ((yield* prepareOutput(output, owner)).closed) return yield* new ProjectionFault({
629
+ const head = yield* prepareOutput(output, owner, output.generation === void 0 ? Effect.void : checkBeforeCreate);
630
+ if (head.closed) return yield* new ProjectionFault({
483
631
  phase: "pin",
484
632
  reason: "invalid-output",
485
633
  message: `Output ${output.address.id} is closed`
486
634
  });
635
+ if (output.generation?.shared === false && positions[name] === void 0 && head.nextOffset !== ZERO_OFFSET) return yield* new ProjectionFault({
636
+ phase: "pin",
637
+ reason: "invalid-output",
638
+ message: `Generation-bound output ${output.address.id} must start empty and open`
639
+ });
487
640
  positions[name] = positions[name] ?? {
488
641
  epoch: projection.generation,
489
642
  nextSeq: 0
@@ -528,22 +681,28 @@ const producer = pin(make$1({
528
681
  }, result));
529
682
  return yield* Effect.void;
530
683
  })
531
- }));
684
+ })).pipe(withAccepted);
532
685
  // src/commit/at-least-once.ts
533
- const atLeastOnce = pin(make$1({
686
+ const atLeastOnce = pin$1(make$1({
534
687
  name: "atLeastOnce",
535
688
  guarantee: "at-least-once",
536
689
  load,
537
690
  remove: remove$1,
691
+ retire: retire$1,
538
692
  apply: (pending) => Effect.gen(function* () {
539
693
  const store = yield* CheckpointStore;
540
694
  const before = beforeRecord(pending);
695
+ const ranges = detailsOf(pending).ranges;
696
+ const unit = Option.isSome(pending.unit.due) ? {
697
+ ranges,
698
+ due: pending.unit.due.value
699
+ } : { ranges };
541
700
  const token = before.pending === void 0 ? yield* store.compareAndSet(pending.key, pending.loaded.token, {
542
701
  ...before,
543
- pending: { ranges: detailsOf(pending).ranges }
702
+ pending: unit
544
703
  }) : pending.loaded.token;
545
- yield* pending.run;
546
- yield* store.compareAndSet(pending.key, token, pending.next);
704
+ const result = yield* pending.run;
705
+ yield* store.compareAndSet(pending.key, token, withState(pending.next, result));
547
706
  })
548
707
  }));
549
708
  // src/commit/compensation.ts
@@ -566,14 +725,196 @@ var commit_exports = /* @__PURE__ */ __exportAll({
566
725
  Emitted: () => Emitted,
567
726
  Folded: () => Folded,
568
727
  HandlerFailed: () => HandlerFailed,
569
- TypeId: () => TypeId,
728
+ TypeId: () => TypeId$1,
570
729
  atLeastOnce: () => atLeastOnce,
571
730
  checkpoint: () => checkpoint,
572
731
  make: () => make$1,
573
732
  producer: () => producer,
574
733
  transaction: () => transaction,
734
+ transactionWithCleanup: () => transactionWithCleanup,
575
735
  withCompensation: () => withCompensation
576
736
  });
737
+ // src/accepted.ts
738
+ /** Private output name, stable across producer retries. */
739
+ const acceptedKey = "@streamsy/accepted";
740
+ const validateAccepted = (output, params, inputTemplates, commit, outputNames = []) => {
741
+ if (output === void 0) return;
742
+ if (!supportsAccepted(commit)) throw new RangeError("accepted requires Commit.transaction or Commit.producer");
743
+ validateGenerationParam(output, params);
744
+ const { route: accepted, param, routeBy } = isPerGeneration(output) ? generationBinding(output) : {
745
+ route: output,
746
+ param: void 0,
747
+ routeBy: void 0
748
+ };
749
+ if (routeBy !== void 0) throw new RangeError("accepted does not support routed outputs");
750
+ if (accepted.collections !== Streamsy.wakeCollections) {
751
+ if (accepted.collections.stream?.schema !== Streamsy.WakeRow || accepted.collections.stream.key !== "stream") throw new RangeError("accepted requires a wake stream declaration");
752
+ }
753
+ 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`);
754
+ for (const template of inputTemplates) if (template === accepted.template) throw new RangeError("An accepted stream may not name an input stream");
755
+ if (Array.contains(outputNames, "@streamsy/accepted")) throw new RangeError(`Output name ${acceptedKey} is reserved for accepted`);
756
+ };
757
+ /** Only moved inputs contribute a row; terminal closes retain their final offset. */
758
+ const acceptedOutput = (address, inputs, unit, closed = {}) => {
759
+ const items = [];
760
+ for (const [name, range] of Record.toEntries(unit.ranges)) {
761
+ const input = inputs[name];
762
+ if (input === void 0 || range.gone || compare(range.nextOffset, range.from) <= 0 && (!range.closed || closed[name])) continue;
763
+ const stream = StreamId.make(input.id);
764
+ const offset = Offset.make(range.nextOffset);
765
+ const value = range.closed ? {
766
+ stream,
767
+ offset,
768
+ closed: true
769
+ } : {
770
+ stream,
771
+ offset
772
+ };
773
+ items.push({
774
+ type: "stream",
775
+ key: stream,
776
+ value,
777
+ headers: { operation: "upsert" }
778
+ });
779
+ }
780
+ return {
781
+ address,
782
+ items
783
+ };
784
+ };
785
+ /** Adapt every handler kind to the existing output-writing Commit result. */
786
+ const acceptedResult = (result, output) => {
787
+ const outputs = result !== void 0 && "outputs" in result ? {
788
+ ...result.outputs,
789
+ [acceptedKey]: output
790
+ } : { [acceptedKey]: output };
791
+ if (result !== void 0 && "encoded" in result) return Accumulated({
792
+ value: result.value,
793
+ encoded: result.encoded,
794
+ outputs
795
+ });
796
+ const emitted = Emitted({ outputs });
797
+ return result !== void 0 && "wakeAt" in result ? {
798
+ ...emitted,
799
+ wakeAt: result.wakeAt
800
+ } : emitted;
801
+ };
802
+ // src/outputs.ts
803
+ const resolveOutputs = (outputs, acceptedOutput, params, key, inputs) => {
804
+ const generationOutputs = /* @__PURE__ */ new Map();
805
+ const resolve = (name, output) => {
806
+ if (isPerGeneration(output)) {
807
+ const { route, param, shared } = generationBinding(output);
808
+ generationOutputs.set(name, { shared });
809
+ return route.at({
810
+ ...params,
811
+ [param]: key.generation
812
+ });
813
+ }
814
+ return isDeclaration(output) ? output.at(params) : output;
815
+ };
816
+ const routed = /* @__PURE__ */ new Map();
817
+ const streams = Record.fromEntries(Array.flatMap(Record.toEntries(outputs), ([name, output]) => {
818
+ if (isPerGeneration(output) && generationBinding(output).routeBy !== void 0) {
819
+ routed.set(name, routedDefinition(generationBinding(output).route));
820
+ return [];
821
+ }
822
+ return [[name, resolve(name, output)]];
823
+ }));
824
+ const accepted = acceptedOutput === void 0 ? void 0 : resolve(acceptedKey, acceptedOutput);
825
+ const addresses = accepted === void 0 ? Record.values(streams) : [...Record.values(streams), accepted];
826
+ const ids = Array.map(addresses, (address) => address.id);
827
+ if (new Set(ids).size !== ids.length) throw new RangeError("Two outputs may not name the same stream");
828
+ const inputIds = new Set(Array.map(Record.values(inputs), (address) => address.id));
829
+ if (Array.some(ids, (id) => inputIds.has(id))) throw new RangeError("An output may not name an input stream");
830
+ if (Array.some(addresses, (address) => !Predicate.isTagged(address, "Json"))) throw new RangeError("Projection outputs require JSON or state routes");
831
+ const occupied = /* @__PURE__ */ new Set([...inputIds, ...ids]);
832
+ const handles = Record.fromEntries(Array.flatMap(Record.toEntries(outputs), ([name, output]) => {
833
+ if (!isPerGeneration(output)) return [];
834
+ const { route, param, routeBy } = generationBinding(output);
835
+ return routeBy === void 0 ? [] : [[name, routedHandle(name, route, routeBy, {
836
+ ...params,
837
+ [param]: key.generation
838
+ }, key, occupied, routed)]];
839
+ }));
840
+ return {
841
+ streams,
842
+ accepted,
843
+ generationOutputs,
844
+ routed,
845
+ handlerOutputs: routed.size === 0 ? streams : {
846
+ ...streams,
847
+ ...handles
848
+ }
849
+ };
850
+ };
851
+ const createOutput = (address, wire) => Streams.create(address).pipe(Effect.provideService(StreamsWriter, wire), Effect.mapError((cause) => new ProjectionFault({
852
+ phase: "process",
853
+ reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
854
+ message: `Cannot create output ${address.id}`,
855
+ cause
856
+ })));
857
+ const boundOutputs = (bound) => bound.accepted === void 0 ? bound.streams ?? {} : {
858
+ ...bound.streams,
859
+ [acceptedKey]: bound.accepted
860
+ };
861
+ /** Create the generation-bound outputs of one binding, using each output's owner. */
862
+ const createOutputs = (bound) => Effect.gen(function* () {
863
+ const bindings = bound[GenerationOutputs];
864
+ if (bindings === void 0) return;
865
+ for (const [name, address] of Record.toEntries(boundOutputs(bound))) {
866
+ if (!bindings.has(name)) continue;
867
+ const { wire } = yield* address.stream;
868
+ yield* createOutput(address, wire);
869
+ }
870
+ });
871
+ const collect = (outputs, buffers, emitted) => Effect.gen(function* () {
872
+ for (const [name, entries] of Record.toEntries(emitted)) {
873
+ const output = outputs[name];
874
+ if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* new ProjectionFault({
875
+ phase: "process",
876
+ reason: "invalid-output",
877
+ message: `Invalid output array ${name}`
878
+ });
879
+ const values = yield* Effect.try({
880
+ try: () => "collections" in output ? DurableState.changes(output, {}, entries) : entries,
881
+ catch: (cause) => new ProjectionFault({
882
+ phase: "process",
883
+ reason: "invalid-output",
884
+ message: `Invalid row change for ${name}`,
885
+ cause
886
+ })
887
+ });
888
+ (buffers[name] ??= []).push(...values);
889
+ }
890
+ return yield* Effect.void;
891
+ });
892
+ const pin = (reason, message, cause) => new ProjectionFault({
893
+ phase: "pin",
894
+ reason,
895
+ message,
896
+ cause
897
+ });
898
+ /** Append one unit under its pinned tuple; appended and duplicate are one outcome. */
899
+ const appendPinned = Effect.fn("Projection.appendPinned")(function* (output, wire, items, position) {
900
+ return yield* Streams.append(output, items, { producer: position }).pipe(Effect.provideService(StreamsWriter, wire), Effect.catchTags({
901
+ EncodeFault: () => new ProjectionFault({
902
+ phase: "process",
903
+ reason: "invalid-output",
904
+ message: `Cannot encode output for ${output.id}`
905
+ }),
906
+ StaleEpoch: (error) => pin("stale-epoch", `Epoch ${position.producerEpoch} of ${output.id} is behind ${error.currentEpoch}`),
907
+ ProducerGap: (error) => pin("invalid-record", `Sequence ${error.receivedSeq} of ${output.id} does not follow ${error.expectedSeq}`),
908
+ NotSupported: (error) => pin("unsupported-composition", `${output.id} does not support ${error.feature}`),
909
+ StorageFault: (cause) => pin("storage-failure", `Cannot append to ${output.id}`, cause),
910
+ TransportFault: (cause) => pin("storage-failure", `Cannot append to ${output.id}`, cause),
911
+ StreamNotFound: () => pin("invalid-output", `Output ${output.id} does not exist`),
912
+ StreamGone: () => pin("invalid-output", `Output ${output.id} is gone`),
913
+ StreamClosed: () => pin("invalid-output", `Output ${output.id} is closed`),
914
+ AppendConflict: () => pin("invalid-output", `Output ${output.id} refused the append`),
915
+ StreamBusy: () => pin("output-busy", `Output ${output.id} is busy`)
916
+ }));
917
+ });
577
918
  // src/state.ts
578
919
  const bindState = (definition, params) => {
579
920
  const initial = definition.initial;
@@ -600,13 +941,24 @@ const encodeState = (key, schema, value) => Schema.encodeEffect(Schema.fromJsonS
600
941
  message: `Cannot encode state for ${key.id}`,
601
942
  cause
602
943
  })));
944
+ // src/wake-at.ts
945
+ const request = Data.taggedEnum().WakeAt;
946
+ /** Return this request from process; returning void clears the previous deadline. */
947
+ const wakeAt = (time) => {
948
+ const millis = Predicate.isNumber(time) ? time : DateTime.toEpochMillis(time);
949
+ if (!Number.isSafeInteger(millis) || millis < 0) throw new RangeError("wakeAt must be a non-negative safe integer in epoch milliseconds");
950
+ return request({ wakeAt: millis });
951
+ };
952
+ /** Internal: discard ordinary process return values while keeping wake requests. */
953
+ const isWakeAt = (value) => Predicate.isTagged(value, "WakeAt");
603
954
  // src/step.ts
604
955
  /** One adapter invocation is one unit. Per-entry variants thread state and preserve order. */
605
- const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepared) => Effect.gen(function* () {
606
- if (kind === "process") return yield* Effect.asVoid(handler(batch, unit, {
956
+ const adapt = (kind, key, state, streams, outputs, handler, batch, unit, encoded, prepared, attempt = 1) => Effect.gen(function* () {
957
+ if (kind === "process") return yield* Effect.map(handler(batch, unit, {
607
958
  prepared,
608
- outputs: streams
609
- }));
959
+ outputs,
960
+ attempt
961
+ }), (result) => isWakeAt(result) ? result : void 0);
610
962
  let value = state === void 0 ? void 0 : yield* currentState(key, state, encoded);
611
963
  const buffers = Record.fromEntries(Array.map(Record.keys(streams), (name) => [name, []]));
612
964
  const steps = kind === "mapAccumBatch" ? [batch] : items(batch);
@@ -636,6 +988,9 @@ const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepare
636
988
  });
637
989
  });
638
990
  // src/declaration.ts
991
+ /** Internal access to the same binding at a chosen generation. */
992
+ const BindGeneration = Symbol.for("@streamsy/projection/internal/BindGeneration");
993
+ const bindAtGeneration = (declaration, params, generation) => declaration[BindGeneration]?.(params, generation);
639
994
  const isDeclaration = (input) => "at" in input;
640
995
  const encodeParams = (id, codecs, params) => {
641
996
  const values = params;
@@ -651,19 +1006,21 @@ const addressesOf = (inputs, params) => {
651
1006
  const declare = (definition, bind) => {
652
1007
  const version = definition.version ?? 1;
653
1008
  const generation = definition.generation ?? 1;
654
- return {
1009
+ const atGeneration = (params, selected) => bind({
1010
+ id: definition.id,
1011
+ version,
1012
+ generation: selected,
1013
+ params: encodeParams(definition.id, definition.params, params),
1014
+ decoded: params
1015
+ });
1016
+ const declaration = {
1017
+ retry: definition.retry,
655
1018
  id: definition.id,
656
1019
  version,
657
1020
  generation,
658
1021
  params: definition.params,
659
1022
  inputs: definition.inputs,
660
- at: (params) => bind({
661
- id: definition.id,
662
- version,
663
- generation,
664
- params: encodeParams(definition.id, definition.params, params),
665
- decoded: params
666
- }),
1023
+ at: (params) => atGeneration(params, generation),
667
1024
  parse: (id) => {
668
1025
  for (const input of Record.values(definition.inputs)) {
669
1026
  if (!isDeclaration(input)) continue;
@@ -673,23 +1030,37 @@ const declare = (definition, bind) => {
673
1030
  return Option.none();
674
1031
  }
675
1032
  };
1033
+ return Object.defineProperty(declaration, BindGeneration, { value: atGeneration });
676
1034
  };
677
1035
  const build = (kind, definition) => {
678
1036
  const commit = definition.commit ?? checkpoint;
1037
+ const outputs = definition.outputs ?? {};
1038
+ for (const output of Record.values(outputs)) {
1039
+ validateGenerationParam(output, definition.params);
1040
+ if (isPerGeneration(output) && generationBinding(output).routeBy !== void 0) {
1041
+ if (kind !== "process") throw new RangeError("Routed outputs require Projection.process");
1042
+ if (!supportsPrepare(commit)) throw new RangeError("Routed outputs require Commit.transaction");
1043
+ }
1044
+ }
1045
+ validateAccepted(definition.accepted, definition.params, Array.map(Array.filter(Record.values(definition.inputs), isDeclaration), (input) => input.template), commit, Record.keys(outputs));
679
1046
  if (definition.prepare !== void 0 && !supportsPrepare(commit)) throw new RangeError("prepare requires Commit.transaction");
680
1047
  return declare(definition, ({ decoded, ...key }) => {
681
1048
  const state = definition.state === void 0 ? void 0 : bindState(definition.state, decoded);
682
1049
  const inputs = addressesOf(definition.inputs, decoded);
683
- const streams = resolveOutputs(definition.outputs ?? {}, decoded, inputs);
684
- return {
1050
+ const { streams, accepted, generationOutputs, routed, handlerOutputs } = resolveOutputs(outputs, definition.accepted, decoded, key, inputs);
1051
+ const bound = {
685
1052
  ...key,
686
1053
  inputs,
687
1054
  state,
688
1055
  streams,
1056
+ accepted,
689
1057
  commit,
690
- prepare: definition.prepare === void 0 ? void 0 : (batch, unit) => definition.prepare(batch, withParams(unit, decoded), { outputs: streams }),
691
- process: (batch, unit, encoded, prepared) => adapt(kind, key, state, streams, definition[kind], batch, withParams(unit, decoded), encoded, prepared)
1058
+ prepare: definition.prepare === void 0 ? void 0 : (batch, unit) => definition.prepare(batch, withParams(unit, decoded), { outputs: handlerOutputs }),
1059
+ process: (batch, unit, encoded, prepared, attempt = 1) => adapt(kind, key, state, streams, handlerOutputs, definition[kind], batch, withParams(unit, decoded), encoded, prepared, attempt)
692
1060
  };
1061
+ if (generationOutputs.size > 0) Object.assign(bound, { [GenerationOutputs]: generationOutputs });
1062
+ if (routed.size > 0) Object.assign(bound, { [RoutedOutputs]: routed });
1063
+ return bound;
693
1064
  });
694
1065
  };
695
1066
  // src/fold.ts
@@ -713,7 +1084,8 @@ function mapAccumBatch(definition) {
713
1084
  }
714
1085
  // src/forget.ts
715
1086
  /**
716
- * Deletes the record. Stop the follower first, or use a new generation.
1087
+ * Deletes a live record and preserves retirement tombstones. Stop the follower first,
1088
+ * or use a new generation.
717
1089
  * Delete stream outputs first, because forgetting restarts their producer sequences.
718
1090
  */
719
1091
  const forget = (projection) => Effect.gen(function* () {
@@ -727,7 +1099,7 @@ const forget = (projection) => Effect.gen(function* () {
727
1099
  });
728
1100
  // src/snapshot.ts
729
1101
  /** Internal: the offsets of a record, typed by the declared inputs. */
730
- const offsetsOf = (record) => record.inputs;
1102
+ const offsetsOf$1 = (record) => record.inputs;
731
1103
  /**
732
1104
  * Internal: decodes one encoded state field. The result is the declared initial value
733
1105
  * when no state is stored, and `undefined` when the declaration has no `state:`.
@@ -746,7 +1118,7 @@ const read = Effect.fn("Projection.read")(function* (projection) {
746
1118
  const restored = yield* restore(projection, projection.commit);
747
1119
  return {
748
1120
  state: yield* stateOf(projection, restored.record.state),
749
- offsets: offsetsOf(restored.record)
1121
+ offsets: offsetsOf$1(restored.record)
750
1122
  };
751
1123
  });
752
1124
  // src/run.ts
@@ -754,7 +1126,8 @@ const read = Effect.fn("Projection.read")(function* (projection) {
754
1126
  * Internal: one pass that also returns the encoded state it committed, or the stored
755
1127
  * state when it found no input.
756
1128
  */
757
- const step = Effect.fn("Projection.pass")(function* (projection) {
1129
+ const step = Effect.fn("Projection.pass")(function* (projection, context, allowEmptyDue = true) {
1130
+ context?.unit(void 0);
758
1131
  const before = yield* restore(projection, projection.commit);
759
1132
  if (before.record.ended) {
760
1133
  yield* forget(projection);
@@ -762,8 +1135,9 @@ const step = Effect.fn("Projection.pass")(function* (projection) {
762
1135
  status: "source-closed",
763
1136
  units: 0,
764
1137
  items: 0,
765
- offsets: offsetsOf(before.record),
766
- encoded: before.record.state
1138
+ offsets: offsetsOf$1(before.record),
1139
+ encoded: before.record.state,
1140
+ wakeAt: Option.fromUndefinedOr(before.record.wakeAt)
767
1141
  };
768
1142
  }
769
1143
  const pending = before.record.pending;
@@ -774,6 +1148,12 @@ const step = Effect.fn("Projection.pass")(function* (projection) {
774
1148
  });
775
1149
  let batch;
776
1150
  let count = 0;
1151
+ let due = pending?.due;
1152
+ let dueOnly = pending !== void 0 && due !== void 0 && Record.isEmptyRecord(pending.ranges);
1153
+ if (pending === void 0 && before.record.wakeAt !== void 0) {
1154
+ const now = yield* Clock.currentTimeMillis;
1155
+ if (before.record.wakeAt <= now) due = before.record.wakeAt;
1156
+ }
777
1157
  if (pending !== void 0) {
778
1158
  const slices = {};
779
1159
  for (const [name, address] of inputEntries(projection.inputs)) {
@@ -791,18 +1171,22 @@ const step = Effect.fn("Projection.pass")(function* (projection) {
791
1171
  batch = read.slices;
792
1172
  count = read.items;
793
1173
  const terminal = Array.some(Record.toEntries(batch), ([name, slice]) => slice.gone === true || slice.closed && slice.upToDate && !before.record.closed?.[name]);
794
- if (count === 0 && !terminal) return {
1174
+ if (count === 0 && !terminal && (due === void 0 || !allowEmptyDue)) return {
795
1175
  status: Array.every(Record.values(batch), (slice) => slice.closed) ? "source-closed" : "caught-up",
796
1176
  units: 0,
797
1177
  items: 0,
798
- offsets: offsetsOf(before.record),
799
- encoded: before.record.state
1178
+ offsets: offsetsOf$1(before.record),
1179
+ encoded: before.record.state,
1180
+ wakeAt: Option.fromUndefinedOr(before.record.wakeAt)
800
1181
  };
1182
+ dueOnly = count === 0 && !terminal;
1183
+ if (dueOnly) batch = Record.map(batch, (_slice, name) => emptySlice(before.record.inputs[name] ?? ""));
801
1184
  }
802
1185
  const gone = Array.some(Record.values(batch), (slice) => slice.gone === true);
803
- const ranges = pending?.ranges ?? rangesOf(batch);
804
- const unit = unitOf(projection.id, projection.version, projection.generation, projection.params, ranges);
805
- const { pending: _pending, ...record } = before.record;
1186
+ const ranges = pending?.ranges ?? (dueOnly ? {} : rangesOf(batch));
1187
+ const unit = unitOf(projection.id, projection.version, projection.generation, projection.params, ranges, due);
1188
+ context?.unit(unit);
1189
+ const { pending: _pending, wakeAt: _wakeAt, ...record } = before.record;
806
1190
  const closed = { ...record.closed };
807
1191
  for (const [name, slice] of Record.toEntries(batch)) if (slice.closed && slice.upToDate) closed[name] = true;
808
1192
  const next = {
@@ -812,13 +1196,26 @@ const step = Effect.fn("Projection.pass")(function* (projection) {
812
1196
  };
813
1197
  if (gone) Object.assign(next, { ended: true });
814
1198
  const outputs = {};
815
- for (const [name, address] of Record.toEntries(projection.streams ?? {})) outputs[name] = {
816
- address,
817
- service: yield* address.stream
818
- };
1199
+ let generationOutputs;
1200
+ for (const [name, address] of Record.toEntries(boundOutputs(projection))) {
1201
+ const service = yield* address.stream;
1202
+ const generation = projection[GenerationOutputs]?.get(name);
1203
+ const output = {
1204
+ address,
1205
+ service,
1206
+ generation
1207
+ };
1208
+ outputs[name] = output;
1209
+ if (generation !== void 0) (generationOutputs ??= /* @__PURE__ */ new Map()).set(name, output);
1210
+ }
819
1211
  let prepared;
820
1212
  let result;
821
- const run = Effect.suspend(() => projection.process(batch, unit, before.record.state, prepared)).pipe(Effect.tap((value) => Effect.sync(() => {
1213
+ const run = Effect.suspend(() => projection.process(batch, unit, before.record.state, prepared, context?.attempt ?? 1)).pipe(Effect.map((value) => {
1214
+ if (projection.accepted === void 0) return value;
1215
+ const handled = value;
1216
+ const output = acceptedOutput(projection.accepted, projection.inputs, unit, before.record.closed);
1217
+ return acceptedResult(handled, output);
1218
+ }), Effect.tap((value) => Effect.sync(() => {
822
1219
  result = value;
823
1220
  })), Effect.mapError((error) => new HandlerFailed({ error })));
824
1221
  const prepare = projection.prepare === void 0 ? void 0 : Effect.suspend(() => projection.prepare(batch, unit)).pipe(Effect.tap((value) => Effect.sync(() => {
@@ -840,6 +1237,7 @@ const step = Effect.fn("Projection.pass")(function* (projection) {
840
1237
  upToDate: batch[name]?.upToDate ?? false
841
1238
  }]))
842
1239
  });
1240
+ if (generationOutputs !== void 0) Object.assign(request, { generationOutputs });
843
1241
  yield* projection.commit.apply(request).pipe(Effect.catchTag("HandlerFailed", (failure) => Effect.fail(failure.error)));
844
1242
  const stored = withState(next, result);
845
1243
  if (gone) yield* forget(projection);
@@ -847,31 +1245,40 @@ const step = Effect.fn("Projection.pass")(function* (projection) {
847
1245
  status: gone ? "source-closed" : "progress",
848
1246
  units: 1,
849
1247
  items: count,
850
- offsets: offsetsOf(next),
851
- encoded: stored.state
1248
+ offsets: offsetsOf$1(next),
1249
+ encoded: stored.state,
1250
+ wakeAt: Option.fromUndefinedOr(stored.wakeAt),
1251
+ dueOnly
852
1252
  };
853
1253
  });
854
1254
  /** Restore and adapt one input unit; the Commit owns every write. */
855
- const pass = (projection) => Effect.map(step(projection), ({ encoded: _encoded, ...result }) => result);
856
- /** Internal: repeats pass until caught up, closed, or limited. The caller validates options. */
857
- const catchUp = Effect.fnUntraced(function* (projection, options) {
1255
+ const pass = (projection) => Effect.map(step(projection), ({ encoded: _encoded, wakeAt: _wakeAt, dueOnly: _dueOnly, ...result }) => result);
1256
+ /** Internal: repeats pass until caught up, closed, or limited. At most one empty due
1257
+ * unit runs per cycle, so a handler returning a past deadline cannot loop forever.
1258
+ * The caller validates options. */
1259
+ const catchUp = Effect.fnUntraced(function* (projection, options, context) {
858
1260
  const cap = options.limit ?? Number.POSITIVE_INFINITY;
859
1261
  let units = 0;
860
1262
  let items = 0;
861
1263
  let offsets;
862
1264
  let encoded;
1265
+ let wakeAt;
1266
+ let allowEmptyDue = true;
863
1267
  do {
864
- const result = yield* step(projection);
1268
+ const result = yield* step(projection, context, allowEmptyDue);
1269
+ if (result.dueOnly) allowEmptyDue = false;
865
1270
  units += result.units;
866
1271
  items += result.items;
867
1272
  offsets = result.offsets;
868
1273
  encoded = result.encoded;
1274
+ wakeAt = result.wakeAt;
869
1275
  if (result.status !== "progress") return {
870
1276
  status: result.status,
871
1277
  units,
872
1278
  items,
873
1279
  offsets,
874
- encoded
1280
+ encoded,
1281
+ wakeAt
875
1282
  };
876
1283
  } while (units < cap);
877
1284
  return {
@@ -879,7 +1286,8 @@ const catchUp = Effect.fnUntraced(function* (projection, options) {
879
1286
  units,
880
1287
  items,
881
1288
  offsets,
882
- encoded
1289
+ encoded,
1290
+ wakeAt
883
1291
  };
884
1292
  });
885
1293
  /** Internal: a cycle with its state decoded once. It reads no checkpoint. */
@@ -889,7 +1297,8 @@ const progressOf = (projection, { encoded, ...cycle }) => Effect.map(stateOf(pro
889
1297
  }));
890
1298
  /**
891
1299
  * Repeats pass until caught up, closed, or limited, then decodes the state of the last
892
- * pass once. After a gone input, the result holds the state that the final unit
1300
+ * pass once. Recorded wakes run when due; this call does not wait for a future wake.
1301
+ * At most one due unit without input runs per cycle. After a gone input, the result holds the state that the final unit
893
1302
  * committed, although the kernel then deletes the record. Use one writer per key.
894
1303
  */
895
1304
  const run = Effect.fn("Projection.run")(function* (projection, options = {}) {
@@ -898,7 +1307,10 @@ const run = Effect.fn("Projection.run")(function* (projection, options = {}) {
898
1307
  });
899
1308
  // src/retry.ts
900
1309
  const defaultRetry = Schedule.exponential("200 millis").pipe(Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.millis(Math.min(3e4, Duration.toMillis(duration))))), Schedule.jittered, Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.millis(Math.min(3e4, Duration.toMillis(duration))))));
901
- /** Default retry for following and attached runners; an explicit options.retry takes precedence. */
1310
+ /**
1311
+ * Default retry for following and attached runners; options.passRetry on attach and options.retry on follow take precedence.
1312
+ * For attached runners: timing only. The runner calls the schedule once per retryable failed pass with no input.
1313
+ */
902
1314
  const ProjectionRetry = Context.Reference("@streamsy/projection/ProjectionRetry", { defaultValue: () => defaultRetry });
903
1315
  // src/follow.ts
904
1316
  /**
@@ -955,7 +1367,8 @@ const hint = Effect.fn("Projection.hint")(function* (input, address, offset, int
955
1367
  * after each cycle that commits a unit or reaches `limit`, and after the last cycle
956
1368
  * when every input is closed or an input is gone; then it ends. After a gone input, the
957
1369
  * last element holds the state that the final unit committed, and the kernel then
958
- * deletes the record. A wake that finds no input emits nothing.
1370
+ * deletes the record. A cycle that finds no input or due timer emits nothing.
1371
+ * Recorded timers run on the next cycle; follow does not wait for their deadlines.
959
1372
  * Options are checked at the first pull. On HTTP backends a parked hint is cancelled
960
1373
  * and replaced once per `repairIntervalMs` until an input changes. One
961
1374
  * `Projection.follow` span covers the whole stream.
@@ -1000,9 +1413,509 @@ const follow = (projection, options = {}) => Stream.unwrap(Effect.gen(function*
1000
1413
  return [yield* progressOf(projection, result), result];
1001
1414
  }));
1002
1415
  })).pipe(Stream.withSpan("Projection.follow"));
1003
- const MAX_DEFER_MS = 36e5;
1004
- /** The wait before a failed binding runs again: 1 s, doubling, at most 1 hour. */
1005
- const deferDelay = (attempts) => Math.min(1e3 * 2 ** Math.max(0, attempts - 1), MAX_DEFER_MS);
1416
+ // src/binding-retry.ts
1417
+ const defaultSchedule = Schedule.exponential("1 second").pipe(Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.millis(Math.min(36e5, Duration.toMillis(duration))))));
1418
+ /** Replay timing from the step count; persisted deadlines are never recomputed. */
1419
+ const bindingDelay = (schedule, attempts) => Effect.gen(function* () {
1420
+ const step = yield* Schedule.toStep(schedule ?? defaultSchedule);
1421
+ let delay = 0;
1422
+ for (let n = 0; n < attempts; n += 1) {
1423
+ const [, duration] = yield* step(0, void 0);
1424
+ delay = Duration.toMillis(duration);
1425
+ }
1426
+ return Option.some(delay);
1427
+ }).pipe(Pull.catchDone(() => Effect.succeedNone), Effect.catchCause((cause) => Effect.logError("Projection binding retry schedule failed", cause).pipe(Effect.as(Option.none()))));
1428
+ // src/registry.ts
1429
+ const RunnerEvent = Data.taggedEnum();
1430
+ const registrations = /* @__PURE__ */ new WeakMap();
1431
+ /** Optional in-process view of Projection.attach runners. */
1432
+ var Registry = class Registry extends Context.Service()("@streamsy/projection/Registry") {
1433
+ /** Match a binding's projection id and encoded params, independent of key order. */
1434
+ 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);
1435
+ /** Provide below the attach layers so they see this same registry. */
1436
+ static layer = Layer.effect(this, Effect.gen(function* () {
1437
+ const runners = /* @__PURE__ */ new Map();
1438
+ let registered = false;
1439
+ const updates = yield* Effect.acquireRelease(PubSub.sliding(1), PubSub.shutdown);
1440
+ const events = yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown);
1441
+ const status = Effect.suspend(() => Effect.forEach(runners.values(), (runner) => runner.status));
1442
+ const find = (target) => Effect.suspend(() => {
1443
+ const id = Predicate.isString(target) ? target : target.id;
1444
+ const found = Option.fromUndefinedOr(runners.get(id));
1445
+ return Effect.fromOption(found).pipe(Effect.mapError(() => new NotAttached({ projection: id })));
1446
+ });
1447
+ const publish = PubSub.publish(updates, void 0).pipe(Effect.asVoid);
1448
+ const snapshot = status.pipe(Effect.asSome, Effect.catch((fault) => Effect.logWarning("Projection.Registry changes snapshot failed", fault).pipe(Effect.as(Option.none()))));
1449
+ const observations = Stream.fromPull(Effect.map(PubSub.subscribe(events), PubSub.takeAll)).pipe(Stream.scoped);
1450
+ const registry = Registry.of({
1451
+ status,
1452
+ events: observations,
1453
+ awaitOffset: Effect.fn("Projection.Registry.awaitOffset")(function* (binding, input, offset) {
1454
+ const reached = (value) => value !== void 0 && compare(value, offset) >= 0;
1455
+ return yield* Effect.scoped(Effect.gen(function* () {
1456
+ const runner = yield* find(binding);
1457
+ if (runner.version !== binding.version || runner.generation !== binding.generation) return yield* new ProjectionFault({
1458
+ phase: "load",
1459
+ reason: "identity-mismatch",
1460
+ message: `Attached identity of ${binding.id} is version ${runner.version}, generation ${runner.generation}; binding is version ${binding.version}, generation ${binding.generation}`
1461
+ });
1462
+ const pull = yield* Stream.toPull(observations);
1463
+ const checkpoint = yield* read(binding);
1464
+ if (reached(checkpoint.offsets[input])) return yield* Effect.void;
1465
+ return yield* Stream.fromPull(Effect.succeed(pull)).pipe(Stream.filter(Registry.isFor(binding)), Stream.mapEffect(RunnerEvent.$match({
1466
+ Ran: (event) => Effect.succeed(reached(event.offsets[input])),
1467
+ Failed: () => read(binding).pipe(Effect.map((value) => reached(value.offsets[input]))),
1468
+ Dropped: () => Effect.succeed(false)
1469
+ })), Stream.filter((satisfied) => satisfied), Stream.runHead, Effect.flatMap((event) => Option.isSome(event) ? Effect.void : Effect.never));
1470
+ }));
1471
+ }),
1472
+ schedule: Effect.fn("Projection.Registry.schedule")(function* (binding) {
1473
+ const bindings = "id" in binding ? [binding] : binding;
1474
+ const first = bindings[0];
1475
+ if (first === void 0) return yield* Effect.void;
1476
+ if (Array.some(bindings, (item) => item.id !== first.id)) return yield* Effect.die(/* @__PURE__ */ new RangeError("schedule bindings must have one projection id"));
1477
+ yield* (yield* find(first)).schedule(bindings);
1478
+ }),
1479
+ rescan: Effect.fn("Projection.Registry.rescan")(function* (target, trigger) {
1480
+ yield* (yield* find(target)).rescan(Predicate.isString(trigger) ? trigger : trigger.address({}).id);
1481
+ }),
1482
+ failed: Effect.fn("Projection.Registry.failed")(function* (target, options = {}) {
1483
+ const limit = options.limit ?? 100;
1484
+ 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"));
1485
+ return yield* (yield* find(target)).failed(limit, Predicate.isString(target) || "at" in target ? void 0 : target);
1486
+ }),
1487
+ retry: Effect.fn("Projection.Registry.retry")(function* (target) {
1488
+ return yield* (yield* find(target)).retry(Predicate.isString(target) || "at" in target ? void 0 : target);
1489
+ }),
1490
+ changes: Stream.unwrap(Effect.gen(function* () {
1491
+ const subscription = yield* PubSub.subscribe(updates);
1492
+ return Stream.concat(Stream.fromEffect(snapshot), Stream.fromSubscription(subscription).pipe(Stream.mapEffect(() => snapshot))).pipe(Stream.filterMap((value) => Result.fromOption(value, () => void 0)));
1493
+ }))
1494
+ });
1495
+ registrations.set(registry, {
1496
+ publish,
1497
+ event: (event) => PubSub.publish(events, event).pipe(Effect.asVoid),
1498
+ register: (runner) => Effect.acquireRelease(Effect.sync(() => {
1499
+ registered = true;
1500
+ if (runners.has(runner.id)) throw new RangeError(`Projection ${runner.id} is already attached to this registry`);
1501
+ runners.set(runner.id, runner);
1502
+ }).pipe(Effect.andThen(publish)), () => Effect.sync(() => {
1503
+ runners.delete(runner.id);
1504
+ }).pipe(Effect.andThen(publish))).pipe(Effect.asVoid)
1505
+ });
1506
+ yield* Effect.addFinalizer(() => registered ? Effect.void : Effect.logDebug("Projection.Registry closed without any runner registrations; provide Registry.layer below the attach layers"));
1507
+ return registry;
1508
+ }));
1509
+ };
1510
+ /** @internal The event publisher installed by Registry.layer. */
1511
+ const eventPublisher = (registry) => registrations.get(registry)?.event;
1512
+ /** @internal Register in the attach scope and return its pass notification. */
1513
+ const registerRunner = (registry, runner) => {
1514
+ const registration = registrations.get(registry);
1515
+ 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));
1516
+ };
1517
+ // src/failure.ts
1518
+ const nonRetryableHandlerReason = "non-retryable-handler";
1519
+ const marked = (reason) => Cause.isFailReason(reason) && Predicate.hasProperty(reason.error, NonRetryable) && reason.error[NonRetryable] === true;
1520
+ const hasNonRetryableHandler = (cause) => Array.some(cause.reasons, marked);
1521
+ /** Unknown handler errors and defects retry; only a known non-retryable fault stops work. */
1522
+ const retryable = (cause) => !Array.some(cause.reasons, (reason) => {
1523
+ if (!Cause.isFailReason(reason)) return false;
1524
+ const { error } = reason;
1525
+ if (marked(reason)) return true;
1526
+ return (Schema.is(ProjectionFault)(error) || Schema.is(StorageFault)(error)) && !error.retryable;
1527
+ });
1528
+ const runnerFailure = (cause, at) => ({
1529
+ at,
1530
+ retryable: retryable(cause),
1531
+ reason: Cause.findErrorOption(cause).pipe(Option.filter(Schema.is(ProjectionFault)), Option.map((fault) => fault.reason)),
1532
+ message: Cause.pretty(cause).slice(0, 1e3)
1533
+ });
1534
+ // src/storage-fault.ts
1535
+ /** Preserve SQL retryability at the runner's storage boundary. */
1536
+ const storageFault = (operation) => (cause) => new StorageFault({
1537
+ operation,
1538
+ message: cause.message,
1539
+ retryable: cause.isRetryable,
1540
+ cause
1541
+ });
1542
+ // src/triggers.ts
1543
+ const DEFAULT_LIMIT$1 = 1e3;
1544
+ const decodeWakeMessage = Schema.decodeEffect(Schema.fromJsonString(Streamsy.WakeMessage));
1545
+ const decoder = new TextDecoder();
1546
+ const invalid = (id, message, cause) => new ProjectionFault({
1547
+ phase: "read",
1548
+ reason: "invalid-source",
1549
+ message: `${message}: ${id}`,
1550
+ cause
1551
+ });
1552
+ /** Persistent local ingestion on both hosts; process hosts also ingest and follow other owners. */
1553
+ const triggersOf = (projection, generation, declarations, match, marks, host = "process") => Effect.gen(function* () {
1554
+ const storage = yield* Storage;
1555
+ const records = yield* Effect.serviceOption(OwnerRecords);
1556
+ const boundary = yield* Effect.serviceOption(CommitBoundary);
1557
+ 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.`));
1558
+ const owner = records.value;
1559
+ const transaction = boundary.value;
1560
+ const permit = yield* Semaphore.make(1);
1561
+ const cursors = /* @__PURE__ */ new Map();
1562
+ const stopped = /* @__PURE__ */ new Map();
1563
+ const streams = /* @__PURE__ */ new Map();
1564
+ const remote = /* @__PURE__ */ new Map();
1565
+ const isRemote = (service) => Option.isSome(service) && !Array.some([
1566
+ storage,
1567
+ owner,
1568
+ transaction
1569
+ ], (local) => service.value.owner === ownerOf(local));
1570
+ for (const declaration of declarations) {
1571
+ const { id } = declaration.address({});
1572
+ const service = yield* Effect.serviceOption(declaration);
1573
+ if (Option.isSome(service) && isRemote(service)) {
1574
+ if (host === "wakeup") return yield* Effect.die(/* @__PURE__ */ new RangeError(`Trigger ${id}: ProjectionWakeup.attach accepts only triggers on its own storage owner`));
1575
+ remote.set(id, {
1576
+ wire: service.value.wire,
1577
+ ahead: true,
1578
+ changed: yield* Deferred.make()
1579
+ });
1580
+ }
1581
+ streams.set(id, encodeKey([
1582
+ "streamsy.projection.trigger.v1",
1583
+ projection,
1584
+ String(generation),
1585
+ id
1586
+ ]));
1587
+ }
1588
+ const changed = (state) => Effect.gen(function* () {
1589
+ const previous = state.changed;
1590
+ state.changed = yield* Deferred.make();
1591
+ yield* Deferred.succeed(previous, void 0);
1592
+ });
1593
+ const cursor = (key) => Effect.gen(function* () {
1594
+ const cached = cursors.get(key);
1595
+ if (cached !== void 0) return cached;
1596
+ const saved = yield* owner.read(key);
1597
+ const from = Option.isNone(saved) ? Offset.make(ZERO_OFFSET) : yield* Schema.decodeEffect(Offset)(saved.value).pipe(Effect.mapError((cause) => new StorageFault({
1598
+ operation: "projection.trigger.cursor",
1599
+ retryable: false,
1600
+ message: `Invalid trigger cursor for ${projection}`,
1601
+ cause
1602
+ })));
1603
+ cursors.set(key, from);
1604
+ return from;
1605
+ });
1606
+ const ahead = (id, key) => permit.withPermit(Effect.gen(function* () {
1607
+ if (stopped.has(id)) return false;
1608
+ const state = remote.get(id);
1609
+ if (state !== void 0) return state.ahead;
1610
+ const record = yield* storage.record(id);
1611
+ return Option.isSome(record) && !record.value.lifecycle.softDeleted && record.value.currentOffset > (yield* cursor(key));
1612
+ }));
1613
+ const next = Effect.gen(function* () {
1614
+ for (const [id, key] of streams) if (yield* ahead(id, key)) return true;
1615
+ return false;
1616
+ });
1617
+ const read = Effect.gen(function* () {
1618
+ for (const [id, key] of streams) {
1619
+ if (remote.has(id)) continue;
1620
+ yield* permit.withPermit(Effect.suspend(() => stopped.has(id) ? Effect.void : transaction.withTransaction(Effect.gen(function* () {
1621
+ const record = yield* storage.record(id);
1622
+ const found = /* @__PURE__ */ new Set();
1623
+ if (Option.isNone(record) || record.value.lifecycle.softDeleted) return { offset: void 0 };
1624
+ const from = yield* cursor(key);
1625
+ const messages = yield* storage.messages(id, {
1626
+ after: from,
1627
+ until: record.value.currentOffset,
1628
+ limit: DEFAULT_LIMIT$1
1629
+ });
1630
+ for (const message of messages) {
1631
+ const event = yield* decodeWakeMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => new ProjectionFault({
1632
+ phase: "read",
1633
+ reason: "invalid-source",
1634
+ message: `Cannot decode trigger ${id} at offset ${message.offset}`,
1635
+ cause
1636
+ })));
1637
+ if (!StreamAddress.isChange(event)) continue;
1638
+ const binding = match(StreamAddress.isUpsert(event) ? event.value.stream : StreamId.make(event.key));
1639
+ if (Option.isSome(binding)) found.add(binding.value[0]);
1640
+ else yield* Effect.logWarning(`Projection ${projection} skipped unmatched trigger source ${event.key} from ${id}`);
1641
+ }
1642
+ const last = messages.at(-1);
1643
+ if (last === void 0) return { offset: from };
1644
+ if (found.size > 0) yield* marks.mark(projection, [...found]);
1645
+ yield* owner.write(key, last.offset);
1646
+ return { offset: last.offset };
1647
+ })).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(storageFault("projection.triggers")(cause))), Effect.tap(({ offset }) => Effect.sync(() => {
1648
+ if (offset !== void 0) cursors.set(key, offset);
1649
+ })), Effect.onError(() => Effect.sync(() => cursors.delete(key))), Effect.catchTag("ProjectionFault", (fault) => Effect.gen(function* () {
1650
+ const failure = runnerFailure(Cause.fail(fault), yield* Clock.currentTimeMillis);
1651
+ stopped.set(id, failure);
1652
+ yield* Effect.logError(`Projection ${projection} trigger ${id} stopped`, fault);
1653
+ })))));
1654
+ }
1655
+ });
1656
+ let remoteFailed = false;
1657
+ const readRemote = Effect.gen(function* () {
1658
+ let first;
1659
+ for (const [id, state] of remote) {
1660
+ const key = streams.get(id);
1661
+ const attempt = yield* permit.withPermit(Effect.suspend(() => stopped.has(id) ? Effect.void : Effect.gen(function* () {
1662
+ const from = yield* cursor(key);
1663
+ const page = yield* state.wire.read(id, { offset: from }).pipe(Effect.asSome, Effect.catchTags({
1664
+ StreamNotFound: () => Effect.succeedNone,
1665
+ StreamGone: () => Effect.succeedNone,
1666
+ InvalidReadRequest: (cause) => Effect.fail(invalid(id, "Invalid trigger read", cause)),
1667
+ TransportFault: (cause) => Effect.fail(new StorageFault({
1668
+ operation: "projection.triggers.remote",
1669
+ retryable: true,
1670
+ message: `Cannot read remote trigger ${id}`,
1671
+ cause
1672
+ })),
1673
+ StorageFault: (cause) => Effect.fail(new StorageFault({
1674
+ operation: "projection.triggers.remote",
1675
+ retryable: true,
1676
+ message: `Cannot read remote trigger ${id}`,
1677
+ cause
1678
+ }))
1679
+ }));
1680
+ if (Option.isNone(page)) {
1681
+ state.ahead = false;
1682
+ return;
1683
+ }
1684
+ const result = page.value;
1685
+ const offset = yield* Schema.decodeEffect(Offset)(result.nextOffset).pipe(Effect.mapError((cause) => invalid(id, "Invalid trigger page cursor", cause)));
1686
+ const found = /* @__PURE__ */ new Set();
1687
+ for (const message of result.messages) {
1688
+ const event = yield* decodeWakeMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => invalid(id, `Cannot decode trigger page after ${from}`, cause)));
1689
+ if (!StreamAddress.isChange(event)) continue;
1690
+ const binding = match(StreamAddress.isUpsert(event) ? event.value.stream : StreamId.make(event.key));
1691
+ if (Option.isSome(binding)) found.add(binding.value[0]);
1692
+ else yield* Effect.logWarning(`Projection ${projection} skipped unmatched trigger source ${event.key} from ${id}`);
1693
+ }
1694
+ yield* transaction.withTransaction(Effect.gen(function* () {
1695
+ if (found.size > 0) yield* marks.mark(projection, [...found]);
1696
+ if (offset !== from) yield* owner.write(key, offset);
1697
+ }));
1698
+ cursors.set(key, offset);
1699
+ state.ahead = !result.upToDate;
1700
+ yield* changed(state);
1701
+ }).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(storageFault("projection.triggers")(cause))), Effect.onError(() => Effect.sync(() => {
1702
+ cursors.delete(key);
1703
+ state.ahead = false;
1704
+ })), Effect.catchTag("ProjectionFault", (fault) => Effect.gen(function* () {
1705
+ stopped.set(id, runnerFailure(Cause.fail(fault), yield* Clock.currentTimeMillis));
1706
+ yield* changed(state);
1707
+ yield* Effect.logError(`Projection ${projection} trigger ${id} stopped`, fault);
1708
+ }))))).pipe(Effect.result);
1709
+ if (Result.isFailure(attempt) && first === void 0) first = attempt.failure;
1710
+ }
1711
+ remoteFailed = first !== void 0;
1712
+ if (first !== void 0) return yield* first;
1713
+ });
1714
+ const follow = (signal, policy) => Effect.forEach(remote, ([id, state]) => Effect.gen(function* () {
1715
+ const key = streams.get(id);
1716
+ let liveCursor;
1717
+ let step = yield* Schedule.toStep(policy);
1718
+ const backoff = Effect.gen(function* () {
1719
+ const now = yield* Clock.currentTimeMillis;
1720
+ const delay = yield* Effect.suspend(() => step(now, void 0)).pipe(Effect.map(([, duration]) => duration), Pull.catchDone(() => Effect.never), Effect.catchCause((cause) => Effect.logWarning(`Projection ${projection} trigger ${id} follower retry failed`, cause).pipe(Effect.andThen(Effect.never))));
1721
+ yield* Effect.sleep(delay);
1722
+ });
1723
+ while (true) {
1724
+ const snapshot = yield* permit.withPermit(Effect.gen(function* () {
1725
+ return {
1726
+ from: yield* cursor(key),
1727
+ changed: state.changed,
1728
+ stopped: stopped.has(id)
1729
+ };
1730
+ })).pipe(Effect.result);
1731
+ if (Result.isFailure(snapshot)) {
1732
+ yield* Effect.logWarning(`Projection ${projection} trigger ${id} follower cursor failed`, snapshot.failure);
1733
+ yield* backoff;
1734
+ continue;
1735
+ }
1736
+ const { from, changed: committed, stopped: isStopped } = snapshot.success;
1737
+ if (isStopped) {
1738
+ yield* Deferred.await(committed);
1739
+ continue;
1740
+ }
1741
+ const result = yield* state.wire.readNext(id, {
1742
+ offset: from,
1743
+ cursor: liveCursor
1744
+ }).pipe(Effect.result);
1745
+ if (Result.isFailure(result)) {
1746
+ yield* Effect.logWarning(`Projection ${projection} trigger ${id} follower read failed`, result.failure);
1747
+ yield* backoff;
1748
+ continue;
1749
+ }
1750
+ const page = result.success;
1751
+ liveCursor = page.cursor;
1752
+ step = yield* Schedule.toStep(policy);
1753
+ if (page.messages.length > 0 || page.nextOffset > from) {
1754
+ yield* permit.withPermit(Effect.gen(function* () {
1755
+ if (!stopped.has(id) && (yield* cursor(key)) === from) {
1756
+ state.ahead = true;
1757
+ yield* signal;
1758
+ }
1759
+ }));
1760
+ yield* Deferred.await(committed);
1761
+ } else if (page.closed) yield* Deferred.await(committed);
1762
+ }
1763
+ }).pipe(Effect.forkScoped), { discard: true });
1764
+ const rescan = (id) => permit.withPermit(Effect.gen(function* () {
1765
+ const key = streams.get(StreamId.make(id));
1766
+ if (key === void 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection ${projection} has no trigger ${id}`));
1767
+ yield* transaction.withTransaction(owner.write(key, ZERO_OFFSET)).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(storageFault("projection.triggers.rescan")(cause))), Effect.tap(() => Effect.sync(() => {
1768
+ cursors.set(key, Offset.make(ZERO_OFFSET));
1769
+ stopped.delete(id);
1770
+ const state = remote.get(StreamId.make(id));
1771
+ if (state !== void 0) state.ahead = true;
1772
+ })), Effect.tap(() => {
1773
+ const state = remote.get(StreamId.make(id));
1774
+ return state === void 0 ? Effect.void : changed(state);
1775
+ }), Effect.onError(() => Effect.sync(() => cursors.delete(key))));
1776
+ }));
1777
+ return {
1778
+ next,
1779
+ read,
1780
+ readRemote,
1781
+ retrying: () => remoteFailed,
1782
+ follow,
1783
+ rescan,
1784
+ retry: () => permit.withPermit(Effect.gen(function* () {
1785
+ stopped.clear();
1786
+ for (const state of remote.values()) {
1787
+ state.ahead = true;
1788
+ yield* changed(state);
1789
+ }
1790
+ })),
1791
+ status: () => Array.map([...streams.keys()], (stream) => ({
1792
+ stream,
1793
+ failure: Option.fromUndefinedOr(stopped.get(stream))
1794
+ }))
1795
+ };
1796
+ });
1797
+ // src/catch-up.ts
1798
+ const Tail = Schema.Struct({
1799
+ stream: StreamId,
1800
+ offset: Offset,
1801
+ closed: Schema.Boolean
1802
+ });
1803
+ /** A serializable vector of fixed source tails, keyed by input name. */
1804
+ const Tails = Schema.Record(Schema.String, Tail);
1805
+ const isOffset = Schema.is(Offset);
1806
+ const historyUnavailable = (input, message, cause) => new ProjectionFault({
1807
+ phase: "read",
1808
+ reason: "history-unavailable",
1809
+ input,
1810
+ message,
1811
+ cause
1812
+ });
1813
+ const head$1 = Effect.fn("Projection.catchUp.head")(function* (name, address) {
1814
+ const { wire } = yield* address.stream;
1815
+ const storageFailure = (cause) => new ProjectionFault({
1816
+ phase: "read",
1817
+ reason: "storage-failure",
1818
+ input: name,
1819
+ message: `Cannot read the head of ${address.id}`,
1820
+ cause
1821
+ });
1822
+ const result = yield* wire.head(address.id).pipe(Effect.catchTags({
1823
+ StreamNotFound: (cause) => historyUnavailable(name, `Input stream ${address.id} is missing`, cause),
1824
+ StreamGone: (cause) => historyUnavailable(name, `Input stream ${address.id} is gone`, cause),
1825
+ StorageFault: storageFailure,
1826
+ TransportFault: storageFailure
1827
+ }));
1828
+ if (!isOffset(result.nextOffset)) return yield* new ProjectionFault({
1829
+ phase: "read",
1830
+ reason: "invalid-source",
1831
+ input: name,
1832
+ message: `Head of ${address.id} has an invalid offset`
1833
+ });
1834
+ return {
1835
+ stream: address.id,
1836
+ offset: result.nextOffset,
1837
+ closed: result.closed
1838
+ };
1839
+ });
1840
+ /** Capture each resolved input head once. The vector can be reused while producers keep writing. */
1841
+ const tails = Effect.fn("Projection.tails")(function* (projection) {
1842
+ const entries = yield* Effect.forEach(inputEntries(projection.inputs), ([name, address]) => head$1(name, address).pipe(Effect.map((value) => [name, value])));
1843
+ return Record.fromEntries(entries);
1844
+ });
1845
+ const validateTails = Effect.fnUntraced(function* (projection, targets) {
1846
+ const decoded = yield* Schema.decodeEffect(Tails, {
1847
+ onExcessProperty: "error",
1848
+ reportInput: true
1849
+ })(targets).pipe(Effect.mapError((cause) => new ProjectionFault({
1850
+ phase: "load",
1851
+ reason: "invalid-options",
1852
+ message: `Invalid tails for ${projection.id}: ${cause.message}`,
1853
+ cause
1854
+ })));
1855
+ for (const [name, address] of inputEntries(projection.inputs)) if (decoded[name]?.stream !== address.id) return yield* new ProjectionFault({
1856
+ phase: "load",
1857
+ reason: "identity-mismatch",
1858
+ input: name,
1859
+ message: `Tail for ${name} must name stream ${address.id}`
1860
+ });
1861
+ if (Record.size(decoded) !== Record.size(projection.inputs)) return yield* new ProjectionFault({
1862
+ phase: "load",
1863
+ reason: "identity-mismatch",
1864
+ message: `Tail input names differ from the declaration of ${projection.id}`
1865
+ });
1866
+ return decoded;
1867
+ });
1868
+ const measure = Effect.fnUntraced(function* (projection, targets, verifyHeads) {
1869
+ const { record } = yield* restore(projection, projection.commit);
1870
+ if (record.ended) return yield* new ProjectionFault({
1871
+ phase: "load",
1872
+ reason: "history-unavailable",
1873
+ message: `Binding of ${projection.id} ended after an input was lost`
1874
+ });
1875
+ const entries = yield* Effect.forEach(inputEntries(projection.inputs), Effect.fnUntraced(function* ([name, address]) {
1876
+ const committed = record.inputs[name];
1877
+ const target = targets[name];
1878
+ if (!isOffset(committed)) return yield* new ProjectionFault({
1879
+ phase: "load",
1880
+ reason: "invalid-record",
1881
+ input: name,
1882
+ message: `Stored offset for ${name} is not a valid offset`
1883
+ });
1884
+ if (verifyHeads) {
1885
+ const current = yield* head$1(name, address);
1886
+ const order = compare(current.offset, target.offset);
1887
+ if (order < 0 || target.closed && (!current.closed || order !== 0)) return yield* historyUnavailable(name, `Head of ${address.id} no longer contains its tail`);
1888
+ }
1889
+ const behind = compare(committed, target.offset) < 0 || target.closed && record.closed?.[name] !== true || record.pending !== void 0 && Record.has(record.pending.ranges, name);
1890
+ return [name, {
1891
+ committed,
1892
+ target: target.offset,
1893
+ behind
1894
+ }];
1895
+ }));
1896
+ return {
1897
+ caughtUp: record.pending === void 0 && Array.every(entries, ([, input]) => !input.behind),
1898
+ inputs: Record.fromEntries(entries)
1899
+ };
1900
+ });
1901
+ /** Compare fixed source tails with one committed checkpoint, including processed closes. Checks source readiness only. */
1902
+ const lag = Effect.fn("Projection.lag")(function* (projection, targets) {
1903
+ const fixed = targets === void 0 ? yield* tails(projection) : yield* validateTails(projection, targets);
1904
+ return yield* measure(projection, fixed, targets !== void 0);
1905
+ });
1906
+ const pollInterval = "250 millis";
1907
+ /** Wait for one fixed vector of source tails. The caller controls the timeout. */
1908
+ const caughtUp = Effect.fn("Projection.caughtUp")(function* (projection, targets) {
1909
+ const fixed = targets === void 0 ? yield* tails(projection) : yield* validateTails(projection, targets);
1910
+ return yield* measure(projection, fixed, true).pipe(Effect.repeat({
1911
+ schedule: Schedule.spaced(pollInterval),
1912
+ while: (progress) => !progress.caughtUp
1913
+ }), Effect.asVoid);
1914
+ });
1915
+ // src/runner.ts
1916
+ /** Re-read wall time after a suspended host resumes, even for distant deadlines. */
1917
+ const MAX_DUE_WAIT_MS = 3e4;
1918
+ const SCHEDULE_CHUNK = 100;
1006
1919
  /**
1007
1920
  * The binding of a written stream id, if the projection reads that id.
1008
1921
  *
@@ -1058,6 +1971,26 @@ const bindingOf = (declaration, key) => Option.flatMap(Schema.decodeOption(Param
1058
1971
  return Option.none();
1059
1972
  }
1060
1973
  });
1974
+ const startupInventory = Effect.fn("Projection.startupInventory")(function* (declaration) {
1975
+ const store = yield* Effect.serviceOption(CheckpointStore);
1976
+ const list = Option.getOrUndefined(store)?.list;
1977
+ const id = declaration.id;
1978
+ return yield* Effect.gen(function* () {
1979
+ if (list === void 0) return [];
1980
+ const keys = /* @__PURE__ */ new Set();
1981
+ const current = /* @__PURE__ */ new Set();
1982
+ for (const { generation, params } of yield* list(id)) (generation === declaration.generation ? current : keys).add(canonicalParams(params));
1983
+ if (Record.isEmptyRecord(declaration.params)) keys.add(canonicalParams({}));
1984
+ for (const key of current) keys.delete(key);
1985
+ const candidates = [];
1986
+ for (const key of keys) {
1987
+ const bound = bindingOf(declaration, key);
1988
+ if (Option.isSome(bound)) candidates.push(bound.value);
1989
+ else yield* Effect.logWarning(`Projection ${id} skipped startup params ${key}: they no longer decode`);
1990
+ }
1991
+ return candidates;
1992
+ }).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([]))));
1993
+ });
1061
1994
  /**
1062
1995
  * A binding that faults with `history-unavailable` on an input whose head is
1063
1996
  * absent can never run: its source is gone, and an id never returns. With a
@@ -1104,132 +2037,308 @@ const durableMarks = (projection, match) => Effect.gen(function* () {
1104
2037
  * the commit's transaction. The in-memory set stays the fast path. A binding
1105
2038
  * that catches up clears its mark with a `seq` compare, so a write during the
1106
2039
  * run keeps it. After a restart, `next`, `wait` and `drain` find the marks in
1107
- * storage. A failed binding defers its own mark, and its neighbours run.
2040
+ * storage. Otherwise marks are private to this runner. In both modes a failed
2041
+ * binding backs off or stops its own mark, and its neighbours run. A start
2042
+ * makes stopped marks due once before answering next, wait or drain.
1108
2043
  */
1109
- const runnerOf = (declaration, options = {}) => {
2044
+ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "process") => {
2045
+ if ("retry" in options) throw new RangeError("Projection.attach retry was renamed to passRetry");
2046
+ const durable = options.durable ?? defaultDurable;
1110
2047
  const limit = options.limit ?? 100;
1111
2048
  const batch = options.batch ?? 25;
2049
+ const concurrency = options.concurrency ?? 1;
1112
2050
  if (!Number.isSafeInteger(limit) || limit <= 0) throw new RangeError("Projection.attach limit must be a positive safe integer");
1113
2051
  if (!Number.isSafeInteger(batch) || batch <= 0) throw new RangeError("Projection.attach batch must be a positive safe integer");
2052
+ if (!Number.isSafeInteger(concurrency) || concurrency <= 0) throw new RangeError("Projection.attach concurrency must be a positive safe integer");
1114
2053
  const match = matcher(declaration);
1115
2054
  return Effect.gen(function* () {
1116
- const committed = yield* (yield* Storage).committed;
2055
+ const storage = yield* Storage;
2056
+ const registry = yield* Effect.serviceOption(Registry);
2057
+ const publish = Option.isSome(registry) ? eventPublisher(registry.value) : void 0;
2058
+ const committed = yield* storage.committed;
1117
2059
  const pending = /* @__PURE__ */ new Map();
1118
- const marks = options.durable === true ? yield* durableMarks(declaration.id, match) : void 0;
1119
- const add = (ids) => {
2060
+ const working = /* @__PURE__ */ new Set();
2061
+ const wake = yield* Queue.sliding(1);
2062
+ const signal = Queue.offer(wake, void 0).pipe(Effect.asVoid);
2063
+ const interruptedDelay = Queue.peek(wake).pipe(Effect.asVoid);
2064
+ const requested = Queue.take(wake).pipe(Effect.as(true));
2065
+ let active = 0;
2066
+ const runActive = (binding, context) => Effect.acquireUseRelease(Effect.sync(() => {
2067
+ active += 1;
2068
+ }), () => {
2069
+ const running = catchUp(binding, { limit }, context).pipe(Effect.flatMap((cycle) => progressOf(binding, cycle)));
2070
+ return publish === void 0 ? running : running.pipe(Effect.tap((progress) => publish(RunnerEvent.Ran({
2071
+ projection: declaration.id,
2072
+ params: binding.params,
2073
+ status: progress.status,
2074
+ units: progress.units,
2075
+ offsets: progress.offsets,
2076
+ wakeAt: progress.wakeAt
2077
+ }))));
2078
+ }, () => Effect.sync(() => {
2079
+ active -= 1;
2080
+ }));
2081
+ const marks = durable ? yield* durableMarks(declaration.id, match) : memoryProjectionMarks();
2082
+ let failure = Option.none();
2083
+ let started = false;
2084
+ const startPermit = yield* Semaphore.make(1);
2085
+ const prepare = Effect.fnUntraced(function* (binding) {
2086
+ const loaded = yield* binding.commit.load(binding);
2087
+ if (Option.isSome(loaded.record)) return false;
2088
+ if ((binding[GenerationOutputs]?.size ?? 0) > 0) {
2089
+ yield* tails(binding);
2090
+ yield* createOutputs(binding);
2091
+ }
2092
+ return true;
2093
+ });
2094
+ const seed = Effect.gen(function* () {
2095
+ 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([]))));
2096
+ const byKey = new Map(Array.map(candidates, (binding) => [canonicalParams(binding.params), binding]));
2097
+ for (const chunk of Array.chunksOf([...byKey], SCHEDULE_CHUNK)) {
2098
+ const keys = [];
2099
+ 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);
2100
+ if (keys.length > 0) yield* marks.mark(declaration.id, keys).pipe(Effect.mapError(storageFault("marks.mark")));
2101
+ }
2102
+ }).pipe(Effect.mapError((cause) => new StorageFault({
2103
+ operation: "projection.startup",
2104
+ message: `Cannot queue startup replay for ${declaration.id}`,
2105
+ retryable: retryable(Cause.fail(cause)),
2106
+ cause
2107
+ })));
2108
+ const start = startPermit.withPermit(Effect.gen(function* () {
2109
+ if (started) return;
2110
+ yield* marks.resume(declaration.id);
2111
+ yield* seed;
2112
+ started = true;
2113
+ }));
2114
+ const observeFailure = (effect) => effect.pipe(Effect.catchCause((cause) => Effect.gen(function* () {
2115
+ failure = Option.some(runnerFailure(cause, yield* Clock.currentTimeMillis));
2116
+ return yield* Effect.failCause(cause);
2117
+ })));
2118
+ const triggers = options.triggers === void 0 || options.triggers.length === 0 ? void 0 : yield* triggersOf(declaration.id, declaration.generation, options.triggers, match, marks, host);
2119
+ const add = (ids) => Effect.gen(function* () {
2120
+ const bindings = /* @__PURE__ */ new Map();
1120
2121
  for (const id of ids) {
1121
2122
  const found = match(id);
1122
- if (Option.isSome(found)) pending.set(found.value[0], found.value[1]);
2123
+ if (Option.isSome(found)) bindings.set(...found.value);
1123
2124
  }
1124
- };
1125
- const absorb = Effect.map(PubSub.takeUpTo(committed, Number.POSITIVE_INFINITY), Array.forEach(add));
2125
+ if (!durable && bindings.size > 0) yield* marks.mark(declaration.id, [...bindings.keys()]).pipe(Effect.mapError(storageFault("marks.mark")));
2126
+ for (const [key, binding] of bindings) pending.set(key, binding);
2127
+ });
2128
+ const absorb = PubSub.takeUpTo(committed, Number.POSITIVE_INFINITY).pipe(Effect.flatMap((commits) => Effect.forEach(commits, add, { discard: true })));
1126
2129
  const next = Effect.gen(function* () {
2130
+ yield* start;
1127
2131
  yield* absorb;
1128
- if (pending.size > 0) return Option.some(yield* Clock.currentTimeMillis);
1129
- return marks === void 0 ? Option.none() : yield* marks.nextDue(declaration.id);
2132
+ if ((yield* Queue.size(wake)) > 0 || pending.size > 0 || triggers !== void 0 && (yield* triggers.next)) return Option.some(yield* Clock.currentTimeMillis);
2133
+ return yield* marks.nextDue(declaration.id);
1130
2134
  });
1131
- const take = Effect.map(PubSub.take(committed), add);
1132
- const waitDue = (store) => Effect.gen(function* () {
1133
- const due = yield* store.nextDue(declaration.id);
2135
+ const take = Effect.raceFirst(Effect.flatMap(PubSub.take(committed), add), interruptedDelay);
2136
+ const waitDue = Effect.gen(function* () {
2137
+ const due = yield* marks.nextDue(declaration.id);
1134
2138
  if (Option.isNone(due)) return yield* take;
1135
2139
  const delay = due.value - (yield* Clock.currentTimeMillis);
1136
2140
  return yield* delay <= 0 ? Effect.void : take.pipe(Effect.timeoutOrElse({
1137
- duration: delay,
2141
+ duration: Math.min(delay, MAX_DUE_WAIT_MS),
1138
2142
  orElse: () => Effect.void
1139
2143
  }));
1140
2144
  });
1141
- /** Wait for a commit, or in durable mode for the next due mark. */
2145
+ /** Wait for a commit or the next due mark. */
1142
2146
  const wait = Effect.gen(function* () {
2147
+ yield* start;
1143
2148
  yield* absorb;
1144
- if (pending.size > 0) return void 0;
1145
- return yield* marks === void 0 ? take : waitDue(marks);
1146
- });
1147
- const dropped = (key) => Effect.logWarning(`Projection ${declaration.id} dropped binding ${key}: its source was removed before its first run`);
1148
- /**
1149
- * Every binding runs once, even if a peer fails; failed or bounded work
1150
- * stays pending. A binding whose source went before its first run is
1151
- * dropped, because no later run can succeed.
1152
- */
1153
- const drainInMemory = Effect.gen(function* () {
1154
- let failure;
1155
- for (const [key, binding] of Array.fromIterable(pending)) {
1156
- pending.delete(key);
1157
- const exit = yield* Effect.exit(run(binding, { limit }));
1158
- if (Exit.isSuccess(exit) && exit.value.status !== "limit-reached") continue;
1159
- if (Exit.isFailure(exit) && (yield* sourceGone(binding.inputs, exit.cause))) {
1160
- yield* dropped(key);
1161
- continue;
1162
- }
1163
- pending.set(key, binding);
1164
- if (Exit.isFailure(exit)) failure ??= exit.cause;
1165
- }
1166
- yield* absorb;
1167
- if (failure !== void 0) return yield* Effect.failCause(failure);
1168
- return { more: pending.size > 0 };
2149
+ if (pending.size > 0 || triggers !== void 0 && (triggers.retrying() || (yield* triggers.next))) return void 0;
2150
+ return yield* waitDue;
1169
2151
  });
2152
+ 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({
2153
+ projection: declaration.id,
2154
+ params: binding.params
2155
+ }))));
1170
2156
  /**
1171
2157
  * The in-memory set plus up to `batch` due marks. A binding that catches up
1172
- * clears its mark by `seq`. A failed binding defers its own mark and does
1173
- * not fail the pass.
2158
+ * clears its mark by `seq`. A failed binding backs off or stops its own
2159
+ * mark without failing the pass.
1174
2160
  */
1175
- const drainDurable = (store) => Effect.gen(function* () {
2161
+ const drainMarks = Effect.gen(function* () {
1176
2162
  const id = declaration.id;
1177
2163
  const now = yield* Clock.currentTimeMillis;
1178
2164
  const work = new Map(pending);
1179
2165
  pending.clear();
1180
- for (const row of yield* store.due(id, now, batch)) {
2166
+ for (const row of yield* marks.due(id, now, batch)) {
1181
2167
  if (work.has(row.params)) continue;
1182
2168
  const binding = bindingOf(declaration, row.params);
1183
2169
  if (Option.isNone(binding)) {
1184
2170
  yield* Effect.logWarning(`Projection ${id} removed pending mark ${row.params}: its params no longer decode`);
1185
- yield* store.remove(id, row.params);
2171
+ yield* marks.remove(id, row.params);
1186
2172
  continue;
1187
2173
  }
1188
2174
  work.set(row.params, binding.value);
1189
2175
  }
1190
- const states = yield* store.read(id, [...work.keys()]);
1191
- for (const [key, binding] of work) {
1192
- const exit = yield* Effect.exit(run(binding, { limit }));
2176
+ for (const key of work.keys()) working.add(key);
2177
+ const states = yield* marks.read(id, [...work.keys()]);
2178
+ for (const [key, state] of states) if (state.stopped || state.dueAt > now) {
2179
+ work.delete(key);
2180
+ working.delete(key);
2181
+ }
2182
+ const runBinding = ([key, binding]) => Effect.gen(function* () {
2183
+ working.delete(key);
1193
2184
  const state = states.get(key);
2185
+ let unit;
2186
+ const exit = yield* Effect.exit(runActive(binding, {
2187
+ attempt: (state?.attempts ?? 0) + 1,
2188
+ unit: (formed) => {
2189
+ unit = formed;
2190
+ }
2191
+ }));
1194
2192
  if (Exit.isSuccess(exit)) {
1195
2193
  if (exit.value.status === "limit-reached") pending.set(key, binding);
1196
- else if (state !== void 0) yield* store.clear(id, key, state.seq);
1197
- continue;
2194
+ else if (Option.isSome(exit.value.wakeAt)) yield* marks.sleep(id, key, state?.seq ?? 0, exit.value.wakeAt.value);
2195
+ else if (state !== void 0) yield* marks.clear(id, key, state.seq);
2196
+ return;
1198
2197
  }
1199
2198
  if (yield* sourceGone(binding.inputs, exit.cause)) {
1200
- yield* dropped(key);
1201
- yield* store.remove(id, key);
1202
- continue;
2199
+ yield* dropped(key, binding);
2200
+ yield* marks.remove(id, key);
2201
+ return;
1203
2202
  }
1204
2203
  const attempts = (state?.attempts ?? 0) + 1;
1205
- const delay = deferDelay(attempts);
1206
- yield* store.defer(id, key, attempts, (yield* Clock.currentTimeMillis) + delay);
1207
- yield* Effect.logWarning(`Projection ${id} binding ${key} failed (attempt ${attempts}); it runs again in ${delay} ms`, exit.cause);
1208
- }
2204
+ const failed = runnerFailure(exit.cause, yield* Clock.currentTimeMillis);
2205
+ const budgetEnded = attempts >= (declaration.retry?.maxAttempts ?? Number.POSITIVE_INFINITY);
2206
+ const delay = !failed.retryable || budgetEnded ? Option.none() : yield* bindingDelay(declaration.retry?.schedule, attempts);
2207
+ if (failed.retryable && Option.isNone(delay) && declaration.retry?.onExhausted !== void 0) {
2208
+ const hook = declaration.retry.onExhausted;
2209
+ const failedUnit = unit;
2210
+ if (failedUnit === void 0) yield* Effect.logWarning(`Projection ${id} binding ${key} exhausted; skipped onExhausted because no unit formed`);
2211
+ else yield* Effect.suspend(() => {
2212
+ const decoded = Record.map(declaration.params, (codec, name) => Schema.decodeSync(codec)(binding.params[name]));
2213
+ return hook(withParams(failedUnit, decoded), failed);
2214
+ }).pipe(Effect.catchCause((cause) => Effect.logError(`Projection ${id} binding ${key} onExhausted failed`, cause)));
2215
+ }
2216
+ const dueAt = Option.map(delay, (ms) => failed.at + ms);
2217
+ const reason = hasNonRetryableHandler(exit.cause) ? Option.some(nonRetryableHandlerReason) : failed.reason;
2218
+ yield* marks.fail(id, key, {
2219
+ attempts,
2220
+ dueAt,
2221
+ failure: {
2222
+ ...failed,
2223
+ reason
2224
+ }
2225
+ });
2226
+ if (publish !== void 0) yield* publish(RunnerEvent.Failed({
2227
+ projection: id,
2228
+ params: binding.params,
2229
+ attempts,
2230
+ dueAt,
2231
+ failure: failed,
2232
+ stopped: Option.isNone(dueAt)
2233
+ }));
2234
+ yield* Effect.logWarning(`Projection ${id} binding ${key} failed (attempt ${attempts}); ${Option.isSome(delay) ? `it runs again in ${delay.value} ms` : "stopped until retry or restart"}`, exit.cause);
2235
+ });
2236
+ yield* Effect.forEach(work, runBinding, {
2237
+ concurrency,
2238
+ discard: true
2239
+ });
1209
2240
  yield* absorb;
1210
2241
  if (pending.size > 0) return { more: true };
1211
- const after = yield* store.nextDue(id);
2242
+ const after = yield* marks.nextDue(id);
1212
2243
  return { more: Option.isSome(after) && after.value <= (yield* Clock.currentTimeMillis) };
1213
2244
  });
2245
+ const drain = Effect.fn("Projection.drain")(function* () {
2246
+ yield* start;
2247
+ yield* Queue.clear(wake);
2248
+ yield* absorb;
2249
+ if (triggers !== void 0) yield* triggers.read;
2250
+ const result = yield* drainMarks;
2251
+ if (triggers !== void 0) yield* triggers.readRemote;
2252
+ failure = Option.none();
2253
+ return { more: result.more || triggers !== void 0 && (yield* triggers.next) };
2254
+ });
1214
2255
  return {
1215
- next,
1216
- wait,
1217
- drain: Effect.fn("Projection.drain")(function* () {
1218
- yield* absorb;
1219
- return yield* marks === void 0 ? drainInMemory : drainDurable(marks);
1220
- })(),
1221
- deferred: marks === void 0 ? Effect.succeed(0) : marks.deferred(declaration.id)
2256
+ follow: (policy) => triggers?.follow(signal, policy) ?? Effect.void,
2257
+ next: observeFailure(next),
2258
+ wait: observeFailure(wait),
2259
+ resume: requested,
2260
+ /** True when a consumed request permits a pass without another wait. */
2261
+ interruptDelay: (duration) => requested.pipe(Effect.timeoutOrElse({
2262
+ duration,
2263
+ orElse: () => Effect.succeed(false)
2264
+ })),
2265
+ schedule: (bindings) => Effect.gen(function* () {
2266
+ const validated = /* @__PURE__ */ new Map();
2267
+ for (const binding of bindings) {
2268
+ const key = canonicalParams(binding.params);
2269
+ const bound = bindingOf(declaration, key);
2270
+ if (Option.isNone(bound)) return yield* new InvalidBinding({
2271
+ projection: declaration.id,
2272
+ params: binding.params
2273
+ });
2274
+ validated.set(key, bound.value);
2275
+ }
2276
+ for (const keys of Array.chunksOf([...validated.keys()], SCHEDULE_CHUNK)) {
2277
+ yield* marks.mark(declaration.id, keys).pipe(Effect.mapError(storageFault("marks.mark")));
2278
+ for (const key of keys) yield* marks.retry(declaration.id, key);
2279
+ }
2280
+ for (const [key, bound] of validated) pending.set(key, bound);
2281
+ yield* signal;
2282
+ }).pipe(Effect.uninterruptible),
2283
+ rescan: (stream) => Effect.gen(function* () {
2284
+ if (triggers === void 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection ${declaration.id} has no trigger ${stream}`));
2285
+ yield* triggers.rescan(stream);
2286
+ yield* signal;
2287
+ }).pipe(Effect.uninterruptible),
2288
+ retry: (binding) => Effect.gen(function* () {
2289
+ const key = binding === void 0 ? void 0 : canonicalParams(binding.params);
2290
+ const count = yield* marks.retry(declaration.id, key);
2291
+ if (binding === void 0 && triggers !== void 0) yield* triggers.retry();
2292
+ yield* signal;
2293
+ return count;
2294
+ }).pipe(Effect.uninterruptible),
2295
+ failed: (failureLimit, binding) => Effect.gen(function* () {
2296
+ const rows = binding === void 0 ? yield* marks.failed(declaration.id, failureLimit) : Array.filter([...(yield* marks.read(declaration.id, [canonicalParams(binding.params)])).values()], (row) => row.attempts > 0);
2297
+ return yield* Effect.forEach(rows, (row) => Effect.gen(function* () {
2298
+ return {
2299
+ params: yield* Schema.decodeEffect(ParamsJson)(row.params).pipe(Effect.mapError((cause) => new StorageFault({
2300
+ operation: "marks.failed",
2301
+ retryable: false,
2302
+ message: "Invalid stored binding params",
2303
+ cause
2304
+ }))),
2305
+ attempts: row.attempts,
2306
+ dueAt: row.stopped ? Option.none() : Option.some(row.dueAt),
2307
+ stopped: row.stopped,
2308
+ 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))),
2309
+ failure: row.failure
2310
+ };
2311
+ }));
2312
+ }),
2313
+ drain: observeFailure(drain()).pipe(Effect.ensuring(Effect.sync(() => working.clear()))),
2314
+ status: Effect.gen(function* () {
2315
+ const summary = yield* marks.summary(declaration.id, yield* Clock.currentTimeMillis);
2316
+ return {
2317
+ active,
2318
+ queued: (/* @__PURE__ */ new Set([...pending.keys(), ...working])).size,
2319
+ marks: summary,
2320
+ failure,
2321
+ stopped: summary.stopped,
2322
+ triggers: triggers?.status() ?? []
2323
+ };
2324
+ }),
2325
+ deferred: Effect.gen(function* () {
2326
+ const summary = yield* marks.summary(declaration.id, yield* Clock.currentTimeMillis);
2327
+ return summary.retryDue + summary.backingOff + summary.stopped;
2328
+ })
1222
2329
  };
1223
2330
  });
1224
2331
  };
1225
2332
  // src/attach.ts
1226
- /** A defect of one drain pass, as a failure that the retry schedule sees. */
2333
+ /** A defect of one drain pass, captured for logging with typed failures. */
1227
2334
  var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Schema.Defect() }) {};
1228
2335
  /**
1229
2336
  * Run a projection whenever a local commit writes one of its inputs. The layer
1230
2337
  * subscribes to `Storage.committed` when it is built, so build it with the
1231
2338
  * storage layer and before the app writes. For each written id, the input's
1232
2339
  * `parse` gives the params, and the runner runs `projection.at(params)`.
2340
+ * The background runner also queues startup replays from the checkpoint
2341
+ * inventory or `options.bindings`.
1233
2342
  *
1234
2343
  * Use it on long-lived hosts (Bun, Node). On a Cloudflare object, use
1235
2344
  * `ProjectionWakeup.attach(projection)`.
@@ -1237,8 +2346,15 @@ var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Sche
1237
2346
  * By default the set of bindings with work lives in memory. A crash after a
1238
2347
  * commit and before the run leaves that binding late until its source gets its
1239
2348
  * next write. With `durable: true`, a pending mark in storage covers that
1240
- * window, and the layer runs due marks when it starts.
1241
- * Inputs on another owner never commit here, so they never trigger. Do not run
2349
+ * window, and the layer runs due marks when it starts. Recorded process timers
2350
+ * wake at their deadline; after host suspend, a capped wait rechecks within 30 s.
2351
+ * Return a time after unit.due to avoid repeatedly running a passed deadline.
2352
+ * Inputs on another owner can use local or remote wake streams in `triggers`.
2353
+ * A provided trigger service on another owner is read one page per pass outside
2354
+ * the local transaction; durable marks and the page cursor then commit together.
2355
+ * A scoped live-read follower signals new remote rows. Remote read failures use
2356
+ * passRetry after local bindings drain; local commits during that backoff wait
2357
+ * for it to end (up to 30 s with the default policy). Do not run
1242
2358
  * an attached binding under `Projection.follow` too: use one writer per key.
1243
2359
  *
1244
2360
  * ```ts
@@ -1248,15 +2364,67 @@ var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Sche
1248
2364
  * ```
1249
2365
  */
1250
2366
  const attach$1 = (projection, options = {}) => {
1251
- const runner = runnerOf(projection, {
1252
- limit: options.limit,
1253
- durable: options.durable ?? false,
1254
- batch: options.batch
1255
- });
2367
+ const runner = runnerOf(projection, options);
1256
2368
  return Layer.effectDiscard(Effect.gen(function* () {
1257
- const { wait, drain } = yield* runner;
1258
- const retry = options.retry ?? (yield* ProjectionRetry);
1259
- yield* wait.pipe(Effect.andThen(drain), Effect.catchDefect((defect) => Effect.fail(new PassDefect({ defect }))), Effect.tapError((error) => Effect.logError(`Projection.attach ${projection.id} failed`, error)), Effect.retry(retry), Effect.repeat(Schedule.forever), Effect.withSpan("Projection.attach"), Effect.forkScoped);
2369
+ const { wait, drain, status, schedule, rescan, retry, failed, interruptDelay, resume, follow } = yield* runner;
2370
+ const policy = options.passRetry ?? (yield* ProjectionRetry);
2371
+ const step = yield* Schedule.toStep(policy);
2372
+ yield* follow(policy);
2373
+ const current = {
2374
+ state: "running",
2375
+ failures: 0,
2376
+ retryAt: Option.none(),
2377
+ lastPassAt: Option.none(),
2378
+ step
2379
+ };
2380
+ const registry = yield* Effect.serviceOption(Registry);
2381
+ const changed = Option.isNone(registry) ? Effect.void : yield* registerRunner(registry.value, {
2382
+ id: projection.id,
2383
+ version: projection.version,
2384
+ generation: projection.generation,
2385
+ schedule,
2386
+ rescan,
2387
+ retry,
2388
+ failed,
2389
+ status: status.pipe(Effect.map((runnerStatus) => ({
2390
+ projection: projection.id,
2391
+ state: current.state,
2392
+ failures: current.failures,
2393
+ retryAt: current.retryAt,
2394
+ lastPassAt: current.lastPassAt,
2395
+ ...runnerStatus
2396
+ })))
2397
+ });
2398
+ yield* Effect.gen(function* () {
2399
+ let requested = false;
2400
+ while (true) {
2401
+ current.state = "running";
2402
+ current.retryAt = Option.none();
2403
+ const exit = yield* Effect.exit((requested ? Effect.void : wait).pipe(Effect.andThen(drain), Effect.catchDefect((defect) => Effect.fail(new PassDefect({ defect })))));
2404
+ requested = false;
2405
+ current.lastPassAt = Option.some(yield* Clock.currentTimeMillis);
2406
+ if (Exit.isSuccess(exit)) {
2407
+ current.failures = 0;
2408
+ current.step = yield* Schedule.toStep(policy);
2409
+ yield* changed;
2410
+ continue;
2411
+ }
2412
+ current.failures += 1;
2413
+ yield* Effect.logError(`Projection.attach ${projection.id} failed`, exit.cause);
2414
+ const now = yield* Clock.currentTimeMillis;
2415
+ const delay = yield* !retryable(exit.cause) ? Effect.succeedNone : Effect.suspend(() => current.step(now, void 0)).pipe(Effect.map(([, duration]) => Option.some(Duration.toMillis(duration))), Pull.catchDone(() => Effect.succeedNone), Effect.catchCause((cause) => Effect.logError(`Projection.attach ${projection.id} retry schedule failed`, cause).pipe(Effect.as(Option.none()))));
2416
+ if (Option.isSome(delay)) {
2417
+ current.state = "retrying";
2418
+ current.retryAt = Option.some((yield* Clock.currentTimeMillis) + delay.value);
2419
+ yield* changed;
2420
+ requested = yield* interruptDelay(delay.value);
2421
+ } else {
2422
+ current.state = "failed";
2423
+ yield* changed;
2424
+ requested = yield* resume;
2425
+ }
2426
+ }
2427
+ }).pipe(Effect.withSpan("Projection.attach"), Effect.forkScoped);
1260
2428
  }));
1261
2429
  };
1262
2430
  // src/current.ts
@@ -1274,7 +2442,7 @@ const current = Effect.fn("Projection.current")(function* (projection) {
1274
2442
  const page = yield* readInputs(projection.inputs, offsets);
1275
2443
  if (page.items === 0) return {
1276
2444
  state,
1277
- offsets: offsetsOf({ inputs: offsets })
2445
+ offsets: offsetsOf$1({ inputs: offsets })
1278
2446
  };
1279
2447
  const ranges = rangesOf(page.slices);
1280
2448
  const unit = unitOf(projection.id, projection.version, projection.generation, projection.params, ranges);
@@ -1284,6 +2452,35 @@ const current = Effect.fn("Projection.current")(function* (projection) {
1284
2452
  offsets = advance(offsets, ranges);
1285
2453
  }
1286
2454
  });
2455
+ // src/bindings.ts
2456
+ /**
2457
+ * Lists the decoded params of bindings with live checkpoints in the selected store.
2458
+ * By default it includes every generation of the declaration's id, across checkpoint
2459
+ * versions. A generation filter still includes every version at that generation.
2460
+ * Each binding appears once, in unspecified order.
2461
+ *
2462
+ * Fails with `InvalidBinding` if live params cannot round-trip through the current
2463
+ * codecs. MySQL owner stores fail because historical hashed keys cannot be decoded.
2464
+ */
2465
+ const bindings = Effect.fn("Projection.bindings")(function* (declaration, options) {
2466
+ const store = yield* CheckpointStore;
2467
+ if (store.list === void 0) return yield* unsupportedBindingList();
2468
+ const schema = Schema.Struct(declaration.params);
2469
+ const decode = Schema.decodeUnknownEffect(schema, { onExcessProperty: "error" });
2470
+ const encode = Schema.encodeEffect(schema);
2471
+ const stored = /* @__PURE__ */ new Map();
2472
+ for (const { generation, params } of yield* store.list(declaration.id)) if (options?.generation === void 0 || generation === options.generation) stored.set(canonicalParams(params), params);
2473
+ return yield* Effect.forEach(stored.values(), (params) => Effect.gen(function* () {
2474
+ const invalid = () => new InvalidBinding({
2475
+ projection: declaration.id,
2476
+ params
2477
+ });
2478
+ const decoded = yield* decode(params).pipe(Effect.mapError(invalid));
2479
+ const encoded = yield* encode(decoded).pipe(Effect.mapError(invalid));
2480
+ if (canonicalParams(encoded) !== canonicalParams(params)) return yield* invalid();
2481
+ return decoded;
2482
+ }));
2483
+ });
1287
2484
  // src/decide.ts
1288
2485
  /** Up to three retries after a lost race, so at most four appends per call. */
1289
2486
  const defaultDecideRetry = Schedule.recurs(3);
@@ -1335,6 +2532,106 @@ const retryLostRace = Effect.fnUntraced(function* (attempt, schedule) {
1335
2532
  return yield* Effect.fromResult(outcome);
1336
2533
  });
1337
2534
  const isOffsetMismatch = (error) => Predicate.isTagged(error, "OffsetMismatch");
2535
+ // src/retire.ts
2536
+ const cleanStream = (address, wire, mode) => {
2537
+ const { id, contentType } = address;
2538
+ return (mode === "remove" ? wire.remove(id).pipe(Effect.as("removed")) : wire.append(id, {
2539
+ close: true,
2540
+ data: /* @__PURE__ */ new Uint8Array(),
2541
+ contentType
2542
+ }).pipe(Effect.as("closed"), Effect.catchTag("StreamClosed", () => Effect.succeed("closed")))).pipe(Effect.catchTags({
2543
+ StreamNotFound: () => Effect.succeed("absent"),
2544
+ StreamGone: () => Effect.succeed("absent")
2545
+ }), Effect.mapError((cause) => new ProjectionFault({
2546
+ phase: "checkpoint",
2547
+ reason: Predicate.isTagged(cause, "StreamBusy") ? "output-busy" : isStreamsFault(cause) ? "storage-failure" : "invalid-output",
2548
+ message: `Cannot ${mode} output ${id}`,
2549
+ cause
2550
+ })));
2551
+ };
2552
+ /** Retire one binding and clean up its exclusively owned generation outputs. */
2553
+ const retire = (declaration, params, options) => {
2554
+ const bound = bindAtGeneration(declaration, params, options.generation);
2555
+ const mode = options.streams ?? "remove";
2556
+ return Effect.gen(function* () {
2557
+ if (bound?.commit.retire === void 0) return yield* new ProjectionFault({
2558
+ phase: "checkpoint",
2559
+ reason: "unsupported-composition",
2560
+ message: "Retirement requires a projection declaration with a Commit that supports it"
2561
+ });
2562
+ const outputs = [];
2563
+ const owned = [];
2564
+ const bindings = bound[GenerationOutputs];
2565
+ const routes = bound[RoutedOutputs];
2566
+ const routed = /* @__PURE__ */ new Map();
2567
+ const context = yield* Effect.context();
2568
+ if (routes !== void 0) for (const name of routes.keys()) routed.set(name, []);
2569
+ for (const [name, address] of Record.toEntries(boundOutputs(bound))) {
2570
+ const binding = bindings?.get(name);
2571
+ if (binding === void 0) continue;
2572
+ if (binding.shared) outputs.push([name, {
2573
+ id: address.id,
2574
+ result: "shared"
2575
+ }]);
2576
+ else owned.push({
2577
+ name,
2578
+ address,
2579
+ service: yield* address.stream
2580
+ });
2581
+ }
2582
+ const retired = {
2583
+ record: yield* bound.commit.retire({
2584
+ key: {
2585
+ id: bound.id,
2586
+ version: bound.version,
2587
+ generation: bound.generation,
2588
+ params: bound.params
2589
+ },
2590
+ cleanup: Effect.gen(function* () {
2591
+ const owner = yield* CurrentOwner;
2592
+ const clean = (address, service) => {
2593
+ if (owner !== void 0 && service.owner !== owner) return Effect.fail(new ProjectionFault({
2594
+ phase: "checkpoint",
2595
+ reason: "unsupported-composition",
2596
+ message: `Output ${address.id} does not share the transaction owner`
2597
+ }));
2598
+ return cleanStream(address, service.wire, mode).pipe(Effect.map((result) => ({
2599
+ id: address.id,
2600
+ result
2601
+ })));
2602
+ };
2603
+ for (const { name, address, service } of owned) outputs.push([name, yield* clean(address, service)]);
2604
+ if (routes !== void 0) {
2605
+ const records = yield* currentRouteRecords;
2606
+ for (const { output, streamId } of yield* records.list(bound)) {
2607
+ const definition = routes.get(output);
2608
+ const results = routed.get(output);
2609
+ const invalid = (cause) => new ProjectionFault({
2610
+ phase: "checkpoint",
2611
+ reason: "invalid-record",
2612
+ message: `Cannot restore routed output ${output} at ${streamId}`,
2613
+ cause
2614
+ });
2615
+ const address = yield* Effect.try({
2616
+ try: () => definition?.restore(streamId),
2617
+ catch: invalid
2618
+ });
2619
+ if (address === void 0 || results === void 0) return yield* invalid();
2620
+ results.push(yield* clean(address, Context.get(context, address.stream)));
2621
+ }
2622
+ if (mode === "remove") yield* records.clear(bound);
2623
+ }
2624
+ return yield* Effect.void;
2625
+ })
2626
+ }),
2627
+ outputs: Record.fromEntries(outputs)
2628
+ };
2629
+ return routes === void 0 ? retired : {
2630
+ ...retired,
2631
+ routed: Record.fromEntries(routed)
2632
+ };
2633
+ });
2634
+ };
1338
2635
  // src/wake.ts
1339
2636
  const row = (stream, offset, closed) => DurableState.upsert("stream", closed ? {
1340
2637
  stream,
@@ -1372,6 +2669,7 @@ function wake(definition) {
1372
2669
  commit: producer,
1373
2670
  inputs: { source: input },
1374
2671
  outputs: { wake: definition.output },
2672
+ accepted: definition.accepted,
1375
2673
  state: {
1376
2674
  schema: Schema.Null,
1377
2675
  initial: null
@@ -1385,7 +2683,13 @@ function wake(definition) {
1385
2683
  }
1386
2684
  // src/projection.ts
1387
2685
  var projection_exports = /* @__PURE__ */ __exportAll({
2686
+ Registry: () => Registry,
2687
+ RunnerEvent: () => RunnerEvent,
2688
+ Tails: () => Tails,
1388
2689
  attach: () => attach$1,
2690
+ bindings: () => bindings,
2691
+ caughtUp: () => caughtUp,
2692
+ createOutputs: () => createOutputs,
1389
2693
  current: () => current,
1390
2694
  decide: () => decide,
1391
2695
  each: () => each,
@@ -1393,15 +2697,22 @@ var projection_exports = /* @__PURE__ */ __exportAll({
1393
2697
  fold: () => fold,
1394
2698
  follow: () => follow,
1395
2699
  forget: () => forget,
2700
+ generationBinding: () => generationBinding,
2701
+ isPerGeneration: () => isPerGeneration,
1396
2702
  items: () => items,
1397
2703
  key: () => key,
2704
+ lag: () => lag,
1398
2705
  mapAccum: () => mapAccum,
1399
2706
  mapAccumBatch: () => mapAccumBatch,
1400
2707
  pass: () => pass,
2708
+ perGeneration: () => perGeneration,
1401
2709
  process: () => process$1,
1402
2710
  read: () => read,
2711
+ retire: () => retire,
1403
2712
  run: () => run,
1404
- wake: () => wake
2713
+ tails: () => tails,
2714
+ wake: () => wake,
2715
+ wakeAt: () => wakeAt
1405
2716
  });
1406
2717
  const key = (projection) => ({
1407
2718
  id: projection.id,
@@ -1476,6 +2787,7 @@ const storedValues = Effect.fn("StateTable.storedValues")(function* (sql, id, co
1476
2787
  });
1477
2788
  // src/state-table.ts
1478
2789
  var state_table_exports = /* @__PURE__ */ __exportAll({
2790
+ clear: () => clear,
1479
2791
  define: () => define,
1480
2792
  migrate: () => migrate,
1481
2793
  rebuild: () => rebuild,
@@ -1672,36 +2984,46 @@ const reads = (id, collections) => {
1672
2984
  };
1673
2985
  };
1674
2986
  /** A State stream's declaration, kept current by the ordinary projection runners. */
1675
- function define(state) {
1676
- return {
1677
- ...declare({
1678
- id: `state-table/${state.key}`,
1679
- params: state.paramCodecs,
1680
- inputs: {}
1681
- }, ({ decoded, ...key }) => {
1682
- const address = state.at(decoded);
1683
- const raw = Object.assign(StreamAddress.json(address.id, { schema: Schema.String }), {
1684
- stream: address.stream,
1685
- codec: Schema.String
1686
- });
1687
- return {
1688
- ...key,
1689
- inputs: { state: raw },
1690
- commit: transaction,
1691
- process: (batch) => applySlice(raw, batch.state),
1692
- ...reads(address.id, state.collections),
1693
- sync: () => synchronize(raw)
1694
- };
1695
- }),
2987
+ function define(state, options = {}) {
2988
+ validateAccepted(options.accepted, state.paramCodecs, [state.template], transaction);
2989
+ const declaration = declare({
2990
+ id: `state-table/${state.key}`,
2991
+ params: state.paramCodecs,
2992
+ inputs: {}
2993
+ }, ({ decoded, ...key }) => {
2994
+ const address = state.at(decoded);
2995
+ const raw = Object.assign(StreamAddress.json(address.id, { schema: Schema.String }), {
2996
+ stream: address.stream,
2997
+ codec: Schema.String
2998
+ });
2999
+ const accepted = options.accepted?.at(decoded);
3000
+ if (accepted?.id === address.id) throw new RangeError("An accepted stream may not name an input stream");
3001
+ return {
3002
+ ...key,
3003
+ accepted,
3004
+ inputs: { state: raw },
3005
+ commit: transaction,
3006
+ process: (batch) => applySlice(raw, batch.state),
3007
+ ...reads(address.id, state.collections),
3008
+ sync: () => synchronize(raw)
3009
+ };
3010
+ });
3011
+ return Object.assign(declaration, {
1696
3012
  inputs: { state },
1697
3013
  parse: state.parse
1698
- };
3014
+ });
1699
3015
  }
3016
+ const clearIndex = (sql, id) => clearRows(sql, id).pipe(Effect.andThen(sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`), Effect.catchTag("SqlError", sqlFault(id)), Effect.asVoid);
3017
+ /** Delete cached rows and their applied offset, even if the State stream has been removed. */
3018
+ const clear = Effect.fn("StateTable.clear")(function* (table) {
3019
+ const tx = yield* Transaction;
3020
+ yield* tx.withTransaction(clearIndex(tx.sql, table.inputs.state.id));
3021
+ });
1700
3022
  /** Discard the index and replay the State stream atomically, retaining the binding checkpoint. */
1701
3023
  const rebuild = Effect.fn("StateTable.rebuild")(function* (table) {
1702
3024
  const tx = yield* Transaction;
1703
3025
  const id = table.inputs.state.id;
1704
- yield* tx.withTransaction(clearRows(tx.sql, id).pipe(Effect.andThen(tx.sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`), Effect.catchTag("SqlError", sqlFault(id)), Effect.andThen(table.sync())));
3026
+ yield* tx.withTransaction(clearIndex(tx.sql, id).pipe(Effect.andThen(table.sync())));
1705
3027
  });
1706
3028
  /** Append a reset to the State stream. The next table run applies it. */
1707
3029
  const reset = Effect.fn("StateTable.reset")(function* (table) {
@@ -1727,15 +3049,16 @@ const fault = (reason, message) => (cause) => new ProjectionFault({
1727
3049
  message,
1728
3050
  cause
1729
3051
  });
1730
- const writeFault = (id) => (cause) => fault(isStreamsFault(cause) ? "storage-failure" : "invalid-output", `Cannot write output ${id}`)(cause);
3052
+ const writeFault = (id) => (cause) => fault(isStreamsFault(cause) ? "storage-failure" : Predicate.isTagged(cause, "StreamBusy") ? "output-busy" : "invalid-output", `Cannot write output ${id}`)(cause);
1731
3053
  const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function* () {
1732
3054
  const output = outputs[spec.output];
1733
3055
  const collection = output.collections[spec.collection];
1734
3056
  const params = table.parse(output.id);
1735
3057
  if (collection === void 0 || Option.isNone(params)) return yield* Effect.die(/* @__PURE__ */ new RangeError(`${table.id} does not index ${spec.collection} of ${output.id}`));
1736
3058
  const { wire } = yield* output.stream;
1737
- yield* wire.create(output.id, { contentType: output.contentType }).pipe(Effect.mapError(writeFault(output.id)));
1738
- yield* table.at(params.value).sync();
3059
+ const generationBound = (yield* TransactionGenerationOutputs)?.get(spec.output)?.address.id === output.id;
3060
+ if (!generationBound) yield* wire.create(output.id, { contentType: output.contentType }).pipe(Effect.mapError(writeFault(output.id)));
3061
+ 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));
1739
3062
  const groups = /* @__PURE__ */ new Map();
1740
3063
  for (const { item } of items(batch)) for (const record of spec.records(item, unit)) {
1741
3064
  const key = spec.key(record, unit);
@@ -1782,29 +3105,76 @@ function process(table, spec) {
1782
3105
  /**
1783
3106
  * Local commits choose bindings; each alarm drains the same runner used by
1784
3107
  * Projection.attach. Acquire it in the object layer's scope, before any
1785
- * request writes.
3108
+ * request writes. Triggers must belong to this storage owner. A provided trigger
3109
+ * service on another owner dies at attach with a RangeError naming its stream;
3110
+ * remote trigger followers require the process host, Projection.attach.
3111
+ * On acquire, startup replays from the checkpoint inventory or `options.bindings`
3112
+ * are queued for the alarm on this object.
1786
3113
  *
1787
3114
  * Durable by default: each commit writes a pending mark for its bindings in
1788
3115
  * the same transaction, so an eviction or a deploy between the commit and the
1789
3116
  * alarm loses no work. The host's acquire reconcile reads the marks and arms
1790
- * the alarm. Pass `durable: false` for the in-memory set only.
3117
+ * the alarm, including recorded process timer deadlines. A start makes stopped marks due once; a still-broken binding
3118
+ * stops again. Stopped marks alone arm no alarm. Pass `durable: false` for private memory marks and timers that reset on eviction until the binding's next input.
3119
+ * A wake during backoff waits; a stopped timer fires late after retry or restart.
3120
+ * Return a time after unit.due to avoid repeatedly running a passed deadline.
1791
3121
  */
1792
3122
  const attach = (projection, options = {}) => {
1793
- const runner = runnerOf(projection, {
1794
- limit: options.limit,
1795
- durable: options.durable ?? true,
1796
- batch: options.batch
1797
- });
3123
+ const runner = runnerOf(projection, options, true, "wakeup");
1798
3124
  return Effect.gen(function* () {
1799
- const { next, drain, deferred } = yield* runner;
3125
+ const { next, drain, deferred, status, schedule, rescan, retry, failed } = yield* runner;
3126
+ let host;
3127
+ let running = false;
3128
+ let lastPassAt = Option.none();
3129
+ const registry = yield* Effect.serviceOption(Registry);
3130
+ const changed = Option.isNone(registry) ? Effect.void : yield* registerRunner(registry.value, {
3131
+ id: projection.id,
3132
+ version: projection.version,
3133
+ generation: projection.generation,
3134
+ status: Effect.gen(function* () {
3135
+ const state = host === void 0 ? {
3136
+ failures: 0,
3137
+ retryAt: Option.none()
3138
+ } : yield* host.state;
3139
+ return {
3140
+ projection: projection.id,
3141
+ state: running ? "running" : Option.isSome(state.retryAt) ? "retrying" : state.failures > 0 ? "failed" : "running",
3142
+ failures: state.failures,
3143
+ retryAt: running ? Option.none() : state.retryAt,
3144
+ lastPassAt,
3145
+ ...yield* status
3146
+ };
3147
+ }),
3148
+ failed,
3149
+ schedule: (binding) => schedule(binding).pipe(Effect.andThen(request), Effect.uninterruptible),
3150
+ rescan: (stream) => rescan(stream).pipe(Effect.andThen(request), Effect.uninterruptible),
3151
+ retry: (binding) => retry(binding).pipe(Effect.tap(() => request), Effect.uninterruptible)
3152
+ });
3153
+ const request = Effect.gen(function* () {
3154
+ if (host === void 0) return;
3155
+ yield* host.retry;
3156
+ yield* host.reconcile;
3157
+ yield* changed;
3158
+ });
1800
3159
  return {
1801
3160
  name: `streamsy/projection/${encodeURIComponent(projection.id)}`,
1802
3161
  next,
1803
- run: drain,
1804
- retry: options.retry ?? (yield* ProjectionRetry),
3162
+ retryable,
3163
+ run: Effect.suspend(() => {
3164
+ running = true;
3165
+ return drain.pipe(Effect.ensuring(Clock.currentTimeMillis.pipe(Effect.map((at) => {
3166
+ running = false;
3167
+ lastPassAt = Option.some(at);
3168
+ }))));
3169
+ }),
3170
+ bind: (bound) => Effect.sync(() => {
3171
+ host = bound;
3172
+ }),
3173
+ changed,
3174
+ retry: options.passRetry ?? (yield* ProjectionRetry),
1805
3175
  deferred
1806
3176
  };
1807
3177
  });
1808
3178
  };
1809
3179
  const ProjectionWakeup = { attach };
1810
- export { CheckpointRecord, CheckpointStore, commit_exports as Commit, fold_by_key_exports as FoldByKey, FoldByKeyError, HandlerFailed, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, state_table_exports as StateTable, Transaction };
3180
+ 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 };