@streamsy/projection 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { a as rangesOf, c as canonicalParams, d as ProjectionFault, l as unitOf, n as CheckpointStore, r as advance, s as restore, t as CheckpointRecord, u as withParams } from "./checkpoint-store-CoDWYNbd.js";
3
- import { Array, Context, Data, Duration, Effect, Function, Layer, Option, Pipeable, Predicate, Record, Ref, Result, Schedule, Schema } from "effect";
4
- import { CommitBoundary, DurableState, Offset, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
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, StreamId, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
5
5
  import { Streams, StreamsWriter } from "@streamsy/core/protocol";
6
- import { CurrentOwner, isForeignOwner, ownerOf } from "@streamsy/core/internal";
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. */
@@ -72,6 +72,35 @@ const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, f
72
72
  closed: result.closed
73
73
  } };
74
74
  });
75
+ /**
76
+ * A lost history is terminal only when a known input's head confirms it is gone.
77
+ * A pinned unit is replayed with `reproduce` and never takes this path: a
78
+ * removal between a pin and its append is a `range-unreproducible` fault.
79
+ */
80
+ const readOrGone = Effect.fn("Projection.readOrGone")(function* (input, address, from, read, seen) {
81
+ return yield* read.pipe(Effect.catchTag("ProjectionFault", (fault) => {
82
+ if (!seen || fault.reason !== "history-unavailable") return Effect.fail(fault);
83
+ return Effect.gen(function* () {
84
+ const { wire } = yield* address.stream;
85
+ if (!(yield* wire.head(address.id).pipe(Effect.as(false), Effect.catchTags({
86
+ StreamNotFound: () => Effect.succeed(true),
87
+ StreamGone: () => Effect.succeed(true)
88
+ }), Effect.mapError((cause) => new ProjectionFault({
89
+ phase: "read",
90
+ reason: "storage-failure",
91
+ input,
92
+ message: `Cannot read the head of ${address.id}`,
93
+ cause
94
+ }))))) return yield* fault;
95
+ return { slice: {
96
+ ...emptySlice(from),
97
+ upToDate: true,
98
+ closed: true,
99
+ gone: true
100
+ } };
101
+ });
102
+ }));
103
+ });
75
104
  /** Decode failure is an input fault: the stored bytes do not match the declared codec. */
76
105
  const decodeMessages = (input, address, messages) => Effect.forEach(messages, (message, index) => Schema.decodeEffect(address.codec)(Predicate.isTagged(address, "Json") ? new TextDecoder().decode(message.data) : message.data).pipe(Effect.mapError(() => new ProjectionFault({
77
106
  phase: "read",
@@ -88,6 +117,16 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
88
117
  input,
89
118
  message: `Pinned range of ${address.id} after ${range.from} cannot be reproduced: ${detail}`
90
119
  });
120
+ if (range.count === 0) {
121
+ if (range.from !== range.nextOffset || !range.closed && !range.gone) return yield* unreproducible("an empty pin must describe a terminal outcome at the same offset");
122
+ return { slice: {
123
+ ...emptySlice(range.from),
124
+ nextOffset: range.nextOffset,
125
+ closed: range.closed === true,
126
+ upToDate: true,
127
+ ...terminalOf(range)
128
+ } };
129
+ }
91
130
  let messages = [];
92
131
  let cursor = range.from;
93
132
  let last;
@@ -134,16 +173,17 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
134
173
  from: range.from,
135
174
  items: yield* decodeMessages(input, address, messages),
136
175
  nextOffset: range.nextOffset,
137
- upToDate: last.upToDate && cursor === range.nextOffset,
138
- closed: last.closed && cursor === range.nextOffset
176
+ upToDate: range.upToDate ?? (last.upToDate && cursor === range.nextOffset),
177
+ closed: range.closed === true
139
178
  } };
140
179
  });
141
180
  /** Read one server page per input in declaration order. */
142
- const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets) {
181
+ const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets, seen = false) {
143
182
  const slices = {};
144
183
  let items = 0;
145
184
  for (const [name, address] of inputEntries(inputs)) {
146
- const read = yield* readSlice(name, address, offsets[name] ?? "");
185
+ const from = offsets[name] ?? "";
186
+ const read = yield* readOrGone(name, address, from, readSlice(name, address, from), seen);
147
187
  slices[name] = read.slice;
148
188
  items += read.slice.items.length;
149
189
  }
@@ -361,8 +401,23 @@ const transaction = withPrepare(make({
361
401
  })
362
402
  }));
363
403
  // src/commit/producer.ts
364
- /** The pinned tuple identity: the params join the id so two parameterisations never share a sequence. */
365
- const producerId = (id, version, params) => `${id}/v${version}${Record.keys(params).length === 0 ? "" : `/${canonicalParams(params)}`}`;
404
+ /**
405
+ * The pinned tuple identity: the params join the id so two parameterisations never share a sequence.
406
+ * An id within the storage limit is used as it is, because outputs already hold producer state under it.
407
+ * A longer id becomes `<id>/v<version>/#<sha256 of the full id>`. A long projection id is cut by
408
+ * code point so the result is at most the limit.
409
+ */
410
+ const producerId = (id, version, params) => fitKey(`${id}/v${version}${Record.keys(params).length === 0 ? "" : `/${canonicalParams(params)}`}`, MAX_PRODUCER_ID_LENGTH, `${id}/v${version}/`);
411
+ /** The head of one output. A missing output on the checkpoint's owner is created here. */
412
+ const prepareOutput = (output, store) => {
413
+ 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({
415
+ phase: "pin",
416
+ reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
417
+ message: `Cannot prepare output ${output.address.id}`,
418
+ cause
419
+ })));
420
+ };
366
421
  /** The pin write is the last save before the append, so its conflict is a pin failure. */
367
422
  const asPin = (fault) => fault.phase === "checkpoint" && fault.reason === "token-conflict" ? new ProjectionFault({
368
423
  phase: "pin",
@@ -398,7 +453,6 @@ const producer = pin(make({
398
453
  };
399
454
  const { identity, adapters } = before.record;
400
455
  const streams = detailsOf(request).outputs;
401
- const ranges = request.unit.ranges;
402
456
  const positions = { ...adapters.outputs };
403
457
  for (const [name, position] of Record.toEntries(positions)) if (position.epoch !== projection.generation) return yield* new ProjectionFault({
404
458
  phase: "load",
@@ -425,13 +479,7 @@ const producer = pin(make({
425
479
  if (pending === void 0 && Record.keys(seqs).length > 0) {
426
480
  for (const [name, output] of Record.toEntries(streams)) {
427
481
  if (seqs[name] === void 0) continue;
428
- const { wire, owner: outputOwner } = output.service;
429
- if ((yield* wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== ownerOf(owner.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({
430
- phase: "pin",
431
- reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
432
- message: `Cannot prepare output ${output.address.id}`,
433
- cause
434
- })))).closed) return yield* new ProjectionFault({
482
+ if ((yield* prepareOutput(output, owner)).closed) return yield* new ProjectionFault({
435
483
  phase: "pin",
436
484
  reason: "invalid-output",
437
485
  message: `Output ${output.address.id} is closed`
@@ -447,22 +495,20 @@ const producer = pin(make({
447
495
  adapters: { outputs: { ...positions } },
448
496
  pending: {
449
497
  seqs,
450
- ranges: Record.fromEntries(Array.map(Record.toEntries(ranges), ([name, range]) => [name, {
451
- from: range.from,
452
- nextOffset: range.nextOffset,
453
- count: detailsOf(request).ranges[name]?.count ?? 0
454
- }]))
498
+ ranges: detailsOf(request).ranges
455
499
  }
456
500
  };
501
+ if (before.record.closed !== void 0) Object.assign(pinned, { closed: before.record.closed });
457
502
  if (before.record.state !== void 0) Object.assign(pinned, { state: before.record.state });
458
503
  token = yield* owner.compareAndSet(projection, before.token, pinned).pipe(Effect.mapError(asPin));
459
504
  }
505
+ const appendAs = yield* producerId(projection.id, projection.version, projection.params);
460
506
  for (const [name, output] of Record.toEntries(streams)) {
461
507
  const seq = seqs[name];
462
508
  const items = processed.items[name] ?? [];
463
509
  if (seq === void 0 || !Array.isReadonlyArrayNonEmpty(items)) continue;
464
510
  yield* appendPinned(output.address, output.service.wire, items, {
465
- producerId: producerId(projection.id, projection.version, projection.params),
511
+ producerId: appendAs,
466
512
  producerEpoch: projection.generation,
467
513
  producerSeq: seq
468
514
  });
@@ -607,6 +653,7 @@ const declare = (definition, bind) => {
607
653
  version,
608
654
  generation,
609
655
  params: definition.params,
656
+ inputs: definition.inputs,
610
657
  at: (params) => bind({
611
658
  id: definition.id,
612
659
  version,
@@ -661,28 +708,61 @@ function mapAccum(definition) {
661
708
  function mapAccumBatch(definition) {
662
709
  return build("mapAccumBatch", definition);
663
710
  }
711
+ // src/forget.ts
712
+ /**
713
+ * Deletes the record. Stop the follower first, or use a new generation.
714
+ * Delete stream outputs first, because forgetting restarts their producer sequences.
715
+ */
716
+ const forget = (projection) => Effect.gen(function* () {
717
+ if (projection.commit.remove === void 0) return yield* new ProjectionFault({
718
+ phase: "checkpoint",
719
+ reason: "unsupported-composition",
720
+ message: "This Commit does not support forgetting"
721
+ });
722
+ yield* projection.commit.remove(projection);
723
+ return yield* Effect.void;
724
+ });
664
725
  // src/snapshot.ts
665
726
  /** Internal: the offsets of a record, typed by the declared inputs. */
666
727
  const offsetsOf = (record) => record.inputs;
667
728
  /**
729
+ * Internal: decodes one encoded state field. The result is the declared initial value
730
+ * when no state is stored, and `undefined` when the declaration has no `state:`.
731
+ */
732
+ const stateOf = Effect.fnUntraced(function* (projection, encoded) {
733
+ const declared = projection.state;
734
+ const stored = declared === void 0 ? Option.none() : yield* decodeState(projection, declared.schema, Option.fromUndefinedOr(encoded));
735
+ return declared === void 0 ? void 0 : Option.getOrElse(stored, declared.initial);
736
+ });
737
+ /**
668
738
  * Reads the state and offsets from one checkpoint record, so the state
669
739
  * always matches the offsets. Before the first unit, the state is the declared initial
670
740
  * value and every offset is the start of its input.
671
741
  */
672
742
  const read = Effect.fn("Projection.read")(function* (projection) {
673
- const declared = projection.state;
674
743
  const restored = yield* restore(projection, projection.commit);
675
- const encoded = Option.fromUndefinedOr(restored.record.state);
676
- const stored = declared === void 0 ? Option.none() : yield* decodeState(projection, declared.schema, encoded);
677
744
  return {
678
- state: declared === void 0 ? void 0 : Option.getOrElse(stored, declared.initial),
745
+ state: yield* stateOf(projection, restored.record.state),
679
746
  offsets: offsetsOf(restored.record)
680
747
  };
681
748
  });
682
749
  // src/run.ts
683
- /** Restore and adapt one input unit; the Commit owns every write. */
684
- const pass = Effect.fn("Projection.pass")(function* (projection) {
750
+ /**
751
+ * Internal: one pass that also returns the encoded state it committed, or the stored
752
+ * state when it found no input.
753
+ */
754
+ const step = Effect.fn("Projection.pass")(function* (projection) {
685
755
  const before = yield* restore(projection, projection.commit);
756
+ if (before.record.ended) {
757
+ yield* forget(projection);
758
+ return {
759
+ status: "source-closed",
760
+ units: 0,
761
+ items: 0,
762
+ offsets: offsetsOf(before.record),
763
+ encoded: before.record.state
764
+ };
765
+ }
686
766
  const pending = before.record.pending;
687
767
  if (pending !== void 0 && !isPinned(projection.commit)) return yield* new ProjectionFault({
688
768
  phase: "load",
@@ -704,30 +784,40 @@ const pass = Effect.fn("Projection.pass")(function* (projection) {
704
784
  }
705
785
  batch = slices;
706
786
  } else {
707
- const read = yield* readInputs(projection.inputs, before.record.inputs);
787
+ const read = yield* readInputs(projection.inputs, before.record.inputs, Option.isSome(before.loaded.record));
708
788
  batch = read.slices;
709
789
  count = read.items;
710
- if (count === 0) return {
790
+ const terminal = Array.some(Record.toEntries(batch), ([name, slice]) => slice.gone === true || slice.closed && slice.upToDate && !before.record.closed?.[name]);
791
+ if (count === 0 && !terminal) return {
711
792
  status: Array.every(Record.values(batch), (slice) => slice.closed) ? "source-closed" : "caught-up",
712
793
  units: 0,
713
794
  items: 0,
714
- offsets: offsetsOf(before.record)
795
+ offsets: offsetsOf(before.record),
796
+ encoded: before.record.state
715
797
  };
716
798
  }
799
+ const gone = Array.some(Record.values(batch), (slice) => slice.gone === true);
717
800
  const ranges = pending?.ranges ?? rangesOf(batch);
718
801
  const unit = unitOf(projection.id, projection.version, projection.generation, projection.params, ranges);
719
802
  const { pending: _pending, ...record } = before.record;
803
+ const closed = { ...record.closed };
804
+ for (const [name, slice] of Record.toEntries(batch)) if (slice.closed && slice.upToDate) closed[name] = true;
720
805
  const next = {
721
806
  ...record,
722
- inputs: advance(record.inputs, ranges)
807
+ inputs: advance(record.inputs, ranges),
808
+ closed
723
809
  };
810
+ if (gone) Object.assign(next, { ended: true });
724
811
  const outputs = {};
725
812
  for (const [name, address] of Record.toEntries(projection.streams ?? {})) outputs[name] = {
726
813
  address,
727
814
  service: yield* address.stream
728
815
  };
729
816
  let prepared;
730
- const run = Effect.suspend(() => projection.process(batch, unit, before.record.state, prepared)).pipe(Effect.mapError((error) => new HandlerFailed({ error })));
817
+ let result;
818
+ const run = Effect.suspend(() => projection.process(batch, unit, before.record.state, prepared)).pipe(Effect.tap((value) => Effect.sync(() => {
819
+ result = value;
820
+ })), Effect.mapError((error) => new HandlerFailed({ error })));
731
821
  const prepare = projection.prepare === void 0 ? void 0 : Effect.suspend(() => projection.prepare(batch, unit)).pipe(Effect.tap((value) => Effect.sync(() => {
732
822
  prepared = value;
733
823
  })), Effect.asVoid, Effect.mapError((error) => new HandlerFailed({ error })));
@@ -741,46 +831,71 @@ const pass = Effect.fn("Projection.pass")(function* (projection) {
741
831
  outputs,
742
832
  prepare,
743
833
  ranges: Record.fromEntries(Array.map(Record.toEntries(ranges), ([name, range]) => [name, {
744
- from: range.from,
745
- nextOffset: range.nextOffset,
746
- count: batch[name]?.items.length ?? 0
834
+ ...range,
835
+ count: batch[name]?.items.length ?? 0,
836
+ closed: batch[name]?.closed ?? false,
837
+ upToDate: batch[name]?.upToDate ?? false
747
838
  }]))
748
839
  });
749
840
  yield* projection.commit.apply(request).pipe(Effect.catchTag("HandlerFailed", (failure) => Effect.fail(failure.error)));
841
+ const stored = withState(next, result);
842
+ if (gone) yield* forget(projection);
750
843
  return {
751
- status: "progress",
844
+ status: gone ? "source-closed" : "progress",
752
845
  units: 1,
753
846
  items: count,
754
- offsets: offsetsOf(next)
847
+ offsets: offsetsOf(next),
848
+ encoded: stored.state
755
849
  };
756
850
  });
757
- /** Repeats pass until caught up, closed, or limited. Use one writer per key. */
758
- const run = Effect.fn("Projection.run")(function* (projection, options = {}) {
759
- yield* validateOptions(options);
851
+ /** Restore and adapt one input unit; the Commit owns every write. */
852
+ const pass = (projection) => Effect.map(step(projection), ({ encoded: _encoded, ...result }) => result);
853
+ /** Internal: repeats pass until caught up, closed, or limited. The caller validates options. */
854
+ const catchUp = Effect.fnUntraced(function* (projection, options) {
760
855
  const cap = options.limit ?? Number.POSITIVE_INFINITY;
761
856
  let units = 0;
762
857
  let items = 0;
763
- let result;
858
+ let offsets;
859
+ let encoded;
764
860
  do {
765
- result = yield* pass(projection);
861
+ const result = yield* step(projection);
766
862
  units += result.units;
767
863
  items += result.items;
864
+ offsets = result.offsets;
865
+ encoded = result.encoded;
768
866
  if (result.status !== "progress") return {
769
- ...result,
867
+ status: result.status,
770
868
  units,
771
- items
869
+ items,
870
+ offsets,
871
+ encoded
772
872
  };
773
873
  } while (units < cap);
774
874
  return {
775
- ...result,
776
875
  status: "limit-reached",
777
876
  units,
778
- items
877
+ items,
878
+ offsets,
879
+ encoded
779
880
  };
780
881
  });
882
+ /** Internal: a cycle with its state decoded once. It reads no checkpoint. */
883
+ const progressOf = (projection, { encoded, ...cycle }) => Effect.map(stateOf(projection, encoded), (state) => ({
884
+ ...cycle,
885
+ state
886
+ }));
887
+ /**
888
+ * Repeats pass until caught up, closed, or limited, then decodes the state of the last
889
+ * pass once. After a gone input, the result holds the state that the final unit
890
+ * committed, although the kernel then deletes the record. Use one writer per key.
891
+ */
892
+ const run = Effect.fn("Projection.run")(function* (projection, options = {}) {
893
+ yield* validateOptions(options);
894
+ return yield* progressOf(projection, yield* catchUp(projection, options));
895
+ });
781
896
  // src/retry.ts
782
897
  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))))));
783
- /** Default storage-failure retry for follow; an explicit options.retry takes precedence. */
898
+ /** Default retry for following and attached runners; an explicit options.retry takes precedence. */
784
899
  const ProjectionRetry = Context.Reference("@streamsy/projection/ProjectionRetry", { defaultValue: () => defaultRetry });
785
900
  // src/follow.ts
786
901
  /**
@@ -788,17 +903,12 @@ const ProjectionRetry = Context.Reference("@streamsy/projection/ProjectionRetry"
788
903
  * authoritative. Only the response cursor is kept, so the next hint on that
789
904
  * input echoes it. A closed input answers `readNext` at once, so a closed and
790
905
  * drained input parks for the interval instead of waking every cycle; the
791
- * open inputs, and the interval itself, decide when the next run happens.
906
+ * open inputs, and the interval itself, decide when the next run happens. A
907
+ * gone input wakes the next run so it can end the binding.
792
908
  */
793
- const hint = Effect.fn("Projection.wake")(function* (input, address, offset, interval, cursors) {
909
+ const hint = Effect.fn("Projection.hint")(function* (input, address, offset, interval, cursors) {
794
910
  const cursor = (yield* Ref.get(cursors))[input];
795
911
  const { wire: reader } = yield* address.stream;
796
- const historyUnavailable = () => new ProjectionFault({
797
- phase: "read",
798
- reason: "history-unavailable",
799
- input,
800
- message: `Required history of ${address.id} after ${offset} is unavailable`
801
- });
802
912
  const storageFailure = (cause) => new ProjectionFault({
803
913
  phase: "read",
804
914
  reason: "storage-failure",
@@ -820,8 +930,8 @@ const hint = Effect.fn("Projection.wake")(function* (input, address, offset, int
820
930
  message: cause.message,
821
931
  cause
822
932
  }),
823
- StreamNotFound: () => historyUnavailable(),
824
- StreamGone: () => historyUnavailable(),
933
+ StreamNotFound: () => Effect.void,
934
+ StreamGone: () => Effect.void,
825
935
  NotSupported: (error) => new ProjectionFault({
826
936
  phase: "read",
827
937
  reason: "unsupported-composition",
@@ -833,12 +943,21 @@ const hint = Effect.fn("Projection.wake")(function* (input, address, offset, int
833
943
  }), Effect.timeoutOption(interval), Effect.asVoid);
834
944
  });
835
945
  /**
836
- * Runs to caught-up, then waits for the first input to hint at a change and runs
837
- * again. The caller's scope owns the fiber and every parked wait; joining exposes
838
- * the terminal close or a typed failure. On HTTP backends a parked hint is cancelled
839
- * and replaced once per `repairIntervalMs` until an input changes.
946
+ * Follows a projection as a pull stream. Each element is one committed cycle: the
947
+ * state and offsets that the last pass left, plus the units and items of the cycle.
948
+ *
949
+ * To run the stream is to be the writer, so run one `follow` stream per key. The next
950
+ * cycle runs only when the consumer pulls, so a slow consumer gets one element that
951
+ * covers all the input that arrived meanwhile. The stream emits after the first cycle,
952
+ * after each cycle that commits a unit or reaches `limit`, and after the last cycle
953
+ * when every input is closed or an input is gone; then it ends. After a gone input, the
954
+ * last element holds the state that the final unit committed, and the kernel then
955
+ * deletes the record. A wake that finds no input emits nothing.
956
+ * Options are checked at the first pull. On HTTP backends a parked hint is cancelled
957
+ * and replaced once per `repairIntervalMs` until an input changes. One
958
+ * `Projection.follow` span covers the whole stream.
840
959
  */
841
- const follow = Effect.fn("Projection.follow")(function* (projection, options = {}) {
960
+ const follow = (projection, options = {}) => Stream.unwrap(Effect.gen(function* () {
842
961
  yield* validateOptions(options);
843
962
  const interval = options.repairIntervalMs ?? 3e4;
844
963
  if (!Number.isSafeInteger(interval) || interval <= 0) return yield* new ProjectionFault({
@@ -847,12 +966,294 @@ const follow = Effect.fn("Projection.follow")(function* (projection, options = {
847
966
  message: "repairIntervalMs must be a positive safe integer"
848
967
  });
849
968
  const cursors = yield* Ref.make({});
850
- const wake = (result) => Effect.raceAllFirst(Array.map(inputEntries(projection.inputs), ([name, address]) => hint(name, address, result.offsets[name] ?? ZERO_OFFSET, interval, cursors)));
851
- return yield* run(projection, options).pipe(Effect.tap((result) => result.status === "caught-up" ? wake(result) : Effect.yieldNow)).pipe(Effect.retry({
969
+ const schedule = (options.retry ?? (yield* ProjectionRetry)).pipe(Schedule.tap(({ input }) => Schema.is(ProjectionFault)(input) && input.retryable ? Effect.logWarning("Projection.follow retry", input) : Effect.void));
970
+ const retrying = (effect) => Effect.retry(effect, {
852
971
  while: (fault) => Schema.is(ProjectionFault)(fault) && fault.retryable,
853
- schedule: (options.retry ?? (yield* ProjectionRetry)).pipe(Schedule.tap(({ input }) => Schema.is(ProjectionFault)(input) && input.retryable ? Effect.logWarning("Projection.follow retry", input) : Effect.void))
854
- }), Effect.repeat({ while: (result) => result.status !== "source-closed" }), Effect.forkScoped);
972
+ schedule
973
+ });
974
+ const wake = (offsets) => Effect.raceAllFirst(Array.map(inputEntries(projection.inputs), ([name, address]) => hint(name, address, offsets[name] ?? ZERO_OFFSET, interval, cursors)));
975
+ /**
976
+ * One cycle, retried on a retryable fault. When it follows a caught-up cycle it
977
+ * first waits for a hint; a retry after a failed wait runs at once.
978
+ */
979
+ const cycle = (previous) => {
980
+ let waiting = previous?.status === "caught-up";
981
+ return retrying(Effect.suspend(() => {
982
+ const parked = waiting && previous !== void 0;
983
+ waiting = false;
984
+ return parked ? wake(previous.offsets).pipe(Effect.andThen(catchUp(projection, options))) : catchUp(projection, options);
985
+ }));
986
+ };
987
+ /** Runs cycles until one must be emitted: the first, a commit, a limit, or the close. */
988
+ const next = Effect.fnUntraced(function* (previous) {
989
+ let result = yield* cycle(previous);
990
+ if (previous === void 0) return result;
991
+ while (result.status === "caught-up" && result.units === 0) result = yield* cycle(result);
992
+ return result;
993
+ });
994
+ return Stream.unfold(void 0, (previous) => Effect.gen(function* () {
995
+ if (previous?.status === "source-closed") return void 0;
996
+ const result = yield* next(previous);
997
+ return [yield* progressOf(projection, result), result];
998
+ }));
999
+ })).pipe(Stream.withSpan("Projection.follow"));
1000
+ const MAX_DEFER_MS = 36e5;
1001
+ /** The wait before a failed binding runs again: 1 s, doubling, at most 1 hour. */
1002
+ const deferDelay = (attempts) => Math.min(1e3 * 2 ** Math.max(0, attempts - 1), MAX_DEFER_MS);
1003
+ /**
1004
+ * The binding of a written stream id, if the projection reads that id.
1005
+ *
1006
+ * The rule: each input must give every projection param, so that one id picks
1007
+ * one binding. A declaration input with a template is checked here and throws a
1008
+ * RangeError. A custom route has no template, so an id whose parse misses a
1009
+ * param is skipped. A fixed address triggers only a projection with no params.
1010
+ */
1011
+ const matcher = (declaration) => {
1012
+ const names = Record.keys(declaration.params);
1013
+ const inputs = Record.toEntries(declaration.inputs);
1014
+ for (const [name, input] of inputs) {
1015
+ const given = isDeclaration(input) ? input.template.length === 0 ? names : compileSegments(input.template).names : [];
1016
+ const missing = Array.filter(names, (param) => !given.includes(param));
1017
+ if (missing.length > 0) throw new RangeError(`Projection ${declaration.id} cannot attach: input ${name} does not give param ${Array.join(missing, ", ")}`);
1018
+ }
1019
+ const bound = (params) => {
1020
+ const binding = declaration.at(params);
1021
+ return Option.some([canonicalParams(binding.params), binding]);
1022
+ };
1023
+ return (id) => {
1024
+ for (const [, input] of inputs) {
1025
+ if (!isDeclaration(input)) {
1026
+ if (input.id === id) return bound({});
1027
+ continue;
1028
+ }
1029
+ const parsed = input.parse(id);
1030
+ if (Option.isNone(parsed)) continue;
1031
+ const params = parsed.value;
1032
+ if (Array.every(names, (name) => name in params)) return bound(params);
1033
+ }
1034
+ return Option.none();
1035
+ };
1036
+ };
1037
+ const ParamsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String));
1038
+ /**
1039
+ * The binding of a pending mark's params, if they still decode with the
1040
+ * projection's param codecs and encode back to the same key.
1041
+ */
1042
+ const bindingOf = (declaration, key) => Option.flatMap(Schema.decodeOption(ParamsJson)(key), (encoded) => {
1043
+ const decoded = {};
1044
+ for (const [name, codec] of Record.toEntries(declaration.params)) {
1045
+ const value = encoded[name];
1046
+ if (value === void 0) return Option.none();
1047
+ const result = Schema.decodeOption(codec)(value);
1048
+ if (Option.isNone(result)) return Option.none();
1049
+ decoded[name] = result.value;
1050
+ }
1051
+ try {
1052
+ const binding = declaration.at(decoded);
1053
+ return canonicalParams(binding.params) === key ? Option.some(binding) : Option.none();
1054
+ } catch {
1055
+ return Option.none();
1056
+ }
855
1057
  });
1058
+ /**
1059
+ * A binding that faults with `history-unavailable` on an input whose head is
1060
+ * absent can never run: its source is gone, and an id never returns. With a
1061
+ * checkpoint, `readOrGone` turns this into a `gone` unit, so only a binding
1062
+ * with no checkpoint reaches here. Any other head answer keeps the fault.
1063
+ */
1064
+ const sourceGone = (inputs, cause) => Effect.gen(function* () {
1065
+ const fault = Cause.findErrorOption(cause).pipe(Option.filter((error) => Schema.is(ProjectionFault)(error) && error.reason === "history-unavailable"));
1066
+ if (Option.isNone(fault) || fault.value.input === void 0) return false;
1067
+ const input = fault.value.input;
1068
+ const address = Array.findFirst(inputEntries(inputs), ([name]) => name === input);
1069
+ if (Option.isNone(address)) return false;
1070
+ const { wire } = yield* address.value[1].stream;
1071
+ return yield* wire.head(address.value[1].id).pipe(Effect.as(false), Effect.catchTags({
1072
+ StreamNotFound: () => Effect.succeed(true),
1073
+ StreamGone: () => Effect.succeed(true)
1074
+ }), Effect.orElseSucceed(() => false));
1075
+ });
1076
+ /**
1077
+ * Register the commit hook that marks each binding a transaction writes, in
1078
+ * that transaction. Dies when the storage layer has no marks, for example
1079
+ * over remote storage.
1080
+ */
1081
+ const durableMarks = (projection, match) => Effect.gen(function* () {
1082
+ const hooks = yield* Effect.serviceOption(CommitHooks);
1083
+ const marks = yield* Effect.serviceOption(ProjectionMarks);
1084
+ if (Option.isNone(hooks) || Option.isNone(marks)) return yield* Effect.die(/* @__PURE__ */ new Error(`Projection ${projection} cannot attach durably: the storage layer keeps no projection marks. Use a local memory or SQL storage layer, or pass durable: false.`));
1085
+ yield* hooks.value.beforeCommit((ids) => {
1086
+ const keys = /* @__PURE__ */ new Set();
1087
+ for (const id of ids) {
1088
+ const found = match(id);
1089
+ if (Option.isSome(found)) keys.add(found.value[0]);
1090
+ }
1091
+ return keys.size === 0 ? Effect.void : marks.value.mark(projection, [...keys]);
1092
+ });
1093
+ return marks.value;
1094
+ });
1095
+ /**
1096
+ * One scoped commit subscription and pending set, shared by the two host
1097
+ * adapters. The subscription exists when this effect returns, so a commit
1098
+ * after that point always marks its binding.
1099
+ *
1100
+ * With `durable`, a commit hook also writes a pending mark for each binding in
1101
+ * the commit's transaction. The in-memory set stays the fast path. A binding
1102
+ * that catches up clears its mark with a `seq` compare, so a write during the
1103
+ * run keeps it. After a restart, `next`, `wait` and `drain` find the marks in
1104
+ * storage. A failed binding defers its own mark, and its neighbours run.
1105
+ */
1106
+ const runnerOf = (declaration, options = {}) => {
1107
+ const limit = options.limit ?? 100;
1108
+ const batch = options.batch ?? 25;
1109
+ if (!Number.isSafeInteger(limit) || limit <= 0) throw new RangeError("Projection.attach limit must be a positive safe integer");
1110
+ if (!Number.isSafeInteger(batch) || batch <= 0) throw new RangeError("Projection.attach batch must be a positive safe integer");
1111
+ const match = matcher(declaration);
1112
+ return Effect.gen(function* () {
1113
+ const committed = yield* (yield* Storage).committed;
1114
+ const pending = /* @__PURE__ */ new Map();
1115
+ const marks = options.durable === true ? yield* durableMarks(declaration.id, match) : void 0;
1116
+ const add = (ids) => {
1117
+ for (const id of ids) {
1118
+ const found = match(id);
1119
+ if (Option.isSome(found)) pending.set(found.value[0], found.value[1]);
1120
+ }
1121
+ };
1122
+ const absorb = Effect.map(PubSub.takeUpTo(committed, Number.POSITIVE_INFINITY), Array.forEach(add));
1123
+ const next = Effect.gen(function* () {
1124
+ yield* absorb;
1125
+ if (pending.size > 0) return Option.some(yield* Clock.currentTimeMillis);
1126
+ return marks === void 0 ? Option.none() : yield* marks.nextDue(declaration.id);
1127
+ });
1128
+ const take = Effect.map(PubSub.take(committed), add);
1129
+ const waitDue = (store) => Effect.gen(function* () {
1130
+ const due = yield* store.nextDue(declaration.id);
1131
+ if (Option.isNone(due)) return yield* take;
1132
+ const delay = due.value - (yield* Clock.currentTimeMillis);
1133
+ return yield* delay <= 0 ? Effect.void : take.pipe(Effect.timeoutOrElse({
1134
+ duration: delay,
1135
+ orElse: () => Effect.void
1136
+ }));
1137
+ });
1138
+ /** Wait for a commit, or in durable mode for the next due mark. */
1139
+ const wait = Effect.gen(function* () {
1140
+ yield* absorb;
1141
+ if (pending.size > 0) return void 0;
1142
+ return yield* marks === void 0 ? take : waitDue(marks);
1143
+ });
1144
+ const dropped = (key) => Effect.logWarning(`Projection ${declaration.id} dropped binding ${key}: its source was removed before its first run`);
1145
+ /**
1146
+ * Every binding runs once, even if a peer fails; failed or bounded work
1147
+ * stays pending. A binding whose source went before its first run is
1148
+ * dropped, because no later run can succeed.
1149
+ */
1150
+ const drainInMemory = Effect.gen(function* () {
1151
+ let failure;
1152
+ for (const [key, binding] of Array.fromIterable(pending)) {
1153
+ pending.delete(key);
1154
+ const exit = yield* Effect.exit(run(binding, { limit }));
1155
+ if (Exit.isSuccess(exit) && exit.value.status !== "limit-reached") continue;
1156
+ if (Exit.isFailure(exit) && (yield* sourceGone(binding.inputs, exit.cause))) {
1157
+ yield* dropped(key);
1158
+ continue;
1159
+ }
1160
+ pending.set(key, binding);
1161
+ if (Exit.isFailure(exit)) failure ??= exit.cause;
1162
+ }
1163
+ yield* absorb;
1164
+ if (failure !== void 0) return yield* Effect.failCause(failure);
1165
+ return { more: pending.size > 0 };
1166
+ });
1167
+ /**
1168
+ * The in-memory set plus up to `batch` due marks. A binding that catches up
1169
+ * clears its mark by `seq`. A failed binding defers its own mark and does
1170
+ * not fail the pass.
1171
+ */
1172
+ const drainDurable = (store) => Effect.gen(function* () {
1173
+ const id = declaration.id;
1174
+ const now = yield* Clock.currentTimeMillis;
1175
+ const work = new Map(pending);
1176
+ pending.clear();
1177
+ for (const row of yield* store.due(id, now, batch)) {
1178
+ if (work.has(row.params)) continue;
1179
+ const binding = bindingOf(declaration, row.params);
1180
+ if (Option.isNone(binding)) {
1181
+ yield* Effect.logWarning(`Projection ${id} removed pending mark ${row.params}: its params no longer decode`);
1182
+ yield* store.remove(id, row.params);
1183
+ continue;
1184
+ }
1185
+ work.set(row.params, binding.value);
1186
+ }
1187
+ const states = yield* store.read(id, [...work.keys()]);
1188
+ for (const [key, binding] of work) {
1189
+ const exit = yield* Effect.exit(run(binding, { limit }));
1190
+ const state = states.get(key);
1191
+ if (Exit.isSuccess(exit)) {
1192
+ if (exit.value.status === "limit-reached") pending.set(key, binding);
1193
+ else if (state !== void 0) yield* store.clear(id, key, state.seq);
1194
+ continue;
1195
+ }
1196
+ if (yield* sourceGone(binding.inputs, exit.cause)) {
1197
+ yield* dropped(key);
1198
+ yield* store.remove(id, key);
1199
+ continue;
1200
+ }
1201
+ const attempts = (state?.attempts ?? 0) + 1;
1202
+ const delay = deferDelay(attempts);
1203
+ yield* store.defer(id, key, attempts, (yield* Clock.currentTimeMillis) + delay);
1204
+ yield* Effect.logWarning(`Projection ${id} binding ${key} failed (attempt ${attempts}); it runs again in ${delay} ms`, exit.cause);
1205
+ }
1206
+ yield* absorb;
1207
+ if (pending.size > 0) return { more: true };
1208
+ const after = yield* store.nextDue(id);
1209
+ return { more: Option.isSome(after) && after.value <= (yield* Clock.currentTimeMillis) };
1210
+ });
1211
+ return {
1212
+ next,
1213
+ wait,
1214
+ drain: Effect.fn("Projection.drain")(function* () {
1215
+ yield* absorb;
1216
+ return yield* marks === void 0 ? drainInMemory : drainDurable(marks);
1217
+ })(),
1218
+ deferred: marks === void 0 ? Effect.succeed(0) : marks.deferred(declaration.id)
1219
+ };
1220
+ });
1221
+ };
1222
+ // src/attach.ts
1223
+ /**
1224
+ * Run a projection whenever a local commit writes one of its inputs. The layer
1225
+ * subscribes to `Storage.committed` when it is built, so build it with the
1226
+ * storage layer and before the app writes. For each written id, the input's
1227
+ * `parse` gives the params, and the runner runs `projection.at(params)`.
1228
+ *
1229
+ * Use it on long-lived hosts (Bun, Node). On a Cloudflare object, use
1230
+ * `ProjectionWakeup.attach(projection)`.
1231
+ *
1232
+ * By default the set of bindings with work lives in memory. A crash after a
1233
+ * commit and before the run leaves that binding late until its source gets its
1234
+ * next write. With `durable: true`, a pending mark in storage covers that
1235
+ * window, and the layer runs due marks when it starts.
1236
+ * Inputs on another owner never commit here, so they never trigger. Do not run
1237
+ * an attached binding under `Projection.follow` too: use one writer per key.
1238
+ *
1239
+ * ```ts
1240
+ * const app = Layer.mergeAll(Api, Projection.attach(filesWake)).pipe(
1241
+ * Layer.provideMerge(BunStorage.layer(streams, { path })),
1242
+ * );
1243
+ * ```
1244
+ */
1245
+ const attach$1 = (projection, options = {}) => {
1246
+ const runner = runnerOf(projection, {
1247
+ limit: options.limit,
1248
+ durable: options.durable ?? false,
1249
+ batch: options.batch
1250
+ });
1251
+ return Layer.effectDiscard(Effect.gen(function* () {
1252
+ const { wait, drain } = yield* runner;
1253
+ const retry = options.retry ?? (yield* ProjectionRetry);
1254
+ yield* wait.pipe(Effect.andThen(drain), Effect.tapError((error) => Effect.logError(`Projection.attach ${projection.id} failed`, error)), Effect.retry(retry), Effect.repeat(Schedule.forever), Effect.withSpan("Projection.attach"), Effect.forkScoped);
1255
+ }));
1256
+ };
856
1257
  // src/current.ts
857
1258
  /**
858
1259
  * Folds the checkpoint and input tail in memory, without locks or writes.
@@ -929,22 +1330,57 @@ const retryLostRace = Effect.fnUntraced(function* (attempt, schedule) {
929
1330
  return yield* Effect.fromResult(outcome);
930
1331
  });
931
1332
  const isOffsetMismatch = (error) => Predicate.isTagged(error, "OffsetMismatch");
932
- // src/forget.ts
1333
+ // src/wake.ts
1334
+ const row = (stream, offset, closed) => DurableState.upsert("stream", closed ? {
1335
+ stream,
1336
+ offset: Offset.make(offset),
1337
+ closed: true
1338
+ } : {
1339
+ stream,
1340
+ offset: Offset.make(offset)
1341
+ });
933
1342
  /**
934
- * Deletes the record. Stop the follower first, or use a new generation.
935
- * Delete stream outputs first, because forgetting restarts their producer sequences.
1343
+ * A wake projection: one source stream gives one keyed row in one wake stream.
1344
+ * Each unit appends one upsert `{ stream, offset, closed? }` with
1345
+ * `Commit.producer`, so several source writes in one unit fold into one row,
1346
+ * and a retry answers `Duplicate`. The producer creates a missing wake stream
1347
+ * on its own owner. A wake stream on another owner must exist before the first
1348
+ * append: its owner creates it at start. When the source is removed or
1349
+ * expires, the binding appends a State delete for its row and forgets itself.
1350
+ *
1351
+ * ```ts
1352
+ * const filesWake = Projection.wake({
1353
+ * id: "files-wake",
1354
+ * params: { user: UserKey, folderId: FolderKey },
1355
+ * input: Files,
1356
+ * output: UserWake,
1357
+ * });
1358
+ * ```
936
1359
  */
937
- const forget = (projection) => Effect.gen(function* () {
938
- if (projection.commit.remove === void 0) return yield* new ProjectionFault({
939
- phase: "checkpoint",
940
- reason: "unsupported-composition",
941
- message: "This Commit does not support forgetting"
1360
+ function wake(definition) {
1361
+ const input = definition.input;
1362
+ return build("mapAccumBatch", {
1363
+ id: definition.id,
1364
+ version: definition.version,
1365
+ generation: definition.generation,
1366
+ params: definition.params,
1367
+ commit: producer,
1368
+ inputs: { source: input },
1369
+ outputs: { wake: definition.output },
1370
+ state: {
1371
+ schema: Schema.Null,
1372
+ initial: null
1373
+ },
1374
+ mapAccumBatch: (_state, batch, unit) => {
1375
+ const source = isDeclaration(input) ? input.at(unit.params) : input;
1376
+ const slice = batch.source;
1377
+ return [null, { wake: [slice.gone ? DurableState.remove("stream", StreamId.make(source.id)) : row(StreamId.make(source.id), slice.nextOffset, slice.closed)] }];
1378
+ }
942
1379
  });
943
- yield* projection.commit.remove(projection);
944
- return yield* Effect.void;
945
- });
1380
+ }
946
1381
  // src/projection.ts
947
1382
  var projection_exports = /* @__PURE__ */ __exportAll({
1383
+ attach: () => attach$1,
948
1384
  current: () => current,
949
1385
  decide: () => decide,
950
1386
  each: () => each,
@@ -959,7 +1395,8 @@ var projection_exports = /* @__PURE__ */ __exportAll({
959
1395
  pass: () => pass,
960
1396
  process: () => process,
961
1397
  read: () => read,
962
- run: () => run
1398
+ run: () => run,
1399
+ wake: () => wake
963
1400
  });
964
1401
  const key = (projection) => ({
965
1402
  id: projection.id,
@@ -969,4 +1406,33 @@ const key = (projection) => ({
969
1406
  });
970
1407
  /** Runs each tagged entry in order and discards its success value. */
971
1408
  const each = (handle) => (batch, unit) => Effect.forEach(items(batch), (entry) => handle(entry, unit), { discard: true });
972
- export { CheckpointRecord, CheckpointStore, commit_exports as Commit, HandlerFailed, projection_exports as Projection, ProjectionFault, ProjectionRetry, Transaction };
1409
+ // src/wakeup.ts
1410
+ /**
1411
+ * Local commits choose bindings; each alarm drains the same runner used by
1412
+ * Projection.attach. Acquire it in the object layer's scope, before any
1413
+ * request writes.
1414
+ *
1415
+ * Durable by default: each commit writes a pending mark for its bindings in
1416
+ * the same transaction, so an eviction or a deploy between the commit and the
1417
+ * alarm loses no work. The host's acquire reconcile reads the marks and arms
1418
+ * the alarm. Pass `durable: false` for the in-memory set only.
1419
+ */
1420
+ const attach = (projection, options = {}) => {
1421
+ const runner = runnerOf(projection, {
1422
+ limit: options.limit,
1423
+ durable: options.durable ?? true,
1424
+ batch: options.batch
1425
+ });
1426
+ return Effect.gen(function* () {
1427
+ const { next, drain, deferred } = yield* runner;
1428
+ return {
1429
+ name: `streamsy/projection/${encodeURIComponent(projection.id)}`,
1430
+ next,
1431
+ run: drain,
1432
+ retry: options.retry ?? (yield* ProjectionRetry),
1433
+ deferred
1434
+ };
1435
+ });
1436
+ };
1437
+ const ProjectionWakeup = { attach };
1438
+ export { CheckpointRecord, CheckpointStore, commit_exports as Commit, HandlerFailed, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, Transaction };