@streamsy/projection 0.14.0 → 0.16.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,8 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { _ as NonRetryable, c as recordKey, d as canonicalParams, f as encodeKey, g as InvalidBinding, h as withParams, i as assertCheckpointKeyVersion, l as restore, m as unitOf, n as CheckpointStore, o as loadLatest, p as terminalOf, r as advance, s as rangesOf, t as CheckpointRecord, u as unsupportedBindingList, v as NotAttached, y as ProjectionFault } from "./checkpoint-store-BE0zelau.js";
2
+ import { _ as NonRetryable, c as recordKey, d as canonicalParams, f as encodeKey, g as InvalidBinding, h as withParams, i as assertCheckpointKeyVersion, l as restore, m as unitOf, n as CheckpointStore, o as loadLatest, p as terminalOf, r as advance, s as rangesOf, t as CheckpointRecord, u as unsupportedBindingList, v as NotAttached, y as ProjectionFault } from "./checkpoint-store-9roy8DEy.js";
3
3
  import { Array, Cause, Clock, Context, Data, DateTime, Deferred, Duration, Effect, Exit, Function, Layer, Option, Order, Pipeable, Predicate, PubSub, Pull, Queue, Record, Ref, Result, Schedule, Schema, Semaphore, Stream } from "effect";
4
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
+ import { CommitHooks, CurrentOwner, MAX_PRODUCER_ID_LENGTH, OwnerRecords, ProjectionMarks, compileSegments, decodeMessage, decodeStateWire, enlist, fitKey, isForeignOwner, memoryProjectionMarks, offsetsOf, ownerOf } from "@streamsy/core/internal";
6
6
  import { Streams, StreamsWriter } from "@streamsy/core/protocol";
7
7
  import { SqlClient } from "effect/sql";
8
8
  // src/batch.ts
@@ -65,19 +65,16 @@ const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, f
65
65
  input,
66
66
  message: `Read of ${address.id} did not advance past ${from}`
67
67
  });
68
- const items = yield* decodeMessages(input, address, result.messages);
69
- const offsets = pageOffsets(result);
70
- const slice = {
71
- from,
72
- items,
73
- nextOffset: result.nextOffset,
74
- upToDate: result.upToDate,
75
- closed: result.closed
68
+ return {
69
+ slice: {
70
+ from,
71
+ ...yield* decodeMessages(input, address, result.messages, pageOffsets(result)),
72
+ nextOffset: result.nextOffset,
73
+ upToDate: result.upToDate,
74
+ closed: result.closed
75
+ },
76
+ count: result.messages.length
76
77
  };
77
- return { slice: offsets === void 0 ? slice : {
78
- ...slice,
79
- offsets
80
- } };
81
78
  });
82
79
  /** Empty reads know all their offsets; malformed metadata is treated as unavailable. */
83
80
  const pageOffsets = (result) => {
@@ -105,22 +102,40 @@ const readOrGone = Effect.fn("Projection.readOrGone")(function* (input, address,
105
102
  message: `Cannot read the head of ${address.id}`,
106
103
  cause
107
104
  }))))) return yield* fault;
108
- return { slice: {
109
- ...emptySlice(from),
110
- upToDate: true,
111
- closed: true,
112
- gone: true
113
- } };
105
+ return {
106
+ slice: {
107
+ ...emptySlice(from),
108
+ upToDate: true,
109
+ closed: true,
110
+ gone: true
111
+ },
112
+ count: 0
113
+ };
114
114
  });
115
115
  }));
116
116
  });
117
117
  /** Decode failure is an input fault: the stored bytes do not match the declared codec. */
118
- const decodeMessages = (input, address, messages) => Effect.forEach(messages, (message, index) => Schema.decodeEffect(address.codec)(Predicate.isTagged(address, "Json") ? new TextDecoder().decode(message.data) : message.data).pipe(Effect.mapError(() => new ProjectionFault({
119
- phase: "read",
120
- reason: "invalid-source",
121
- input,
122
- message: `Cannot decode ${address.id} at read message ${index}`
123
- }))));
118
+ const decodeMessages = (input, address, messages, offsets) => Effect.gen(function* () {
119
+ const items = [];
120
+ const keptOffsets = [];
121
+ for (const [index, message] of messages.entries()) {
122
+ const decoded = yield* decodeMessage(address, message, index).pipe(Effect.mapError((cause) => new ProjectionFault({
123
+ phase: "read",
124
+ reason: "invalid-source",
125
+ input,
126
+ message: cause.message,
127
+ cause
128
+ })));
129
+ if (Option.isNone(decoded)) continue;
130
+ items.push(decoded.value);
131
+ const offset = offsets?.[index];
132
+ if (offset !== void 0) keptOffsets.push(offset);
133
+ }
134
+ return offsets === void 0 ? { items } : {
135
+ items,
136
+ offsets: keptOffsets
137
+ };
138
+ });
124
139
  /** Re-read server pages, retaining the pinned count and checking the boundary where available. */
125
140
  const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, range) {
126
141
  const { wire: reader } = yield* address.stream;
@@ -132,13 +147,16 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
132
147
  });
133
148
  if (range.count === 0) {
134
149
  if (range.from !== range.nextOffset || !range.closed && !range.gone) return yield* unreproducible("an empty pin must describe a terminal outcome at the same offset");
135
- return { slice: {
136
- ...emptySlice(range.from),
137
- nextOffset: range.nextOffset,
138
- closed: range.closed === true,
139
- upToDate: true,
140
- ...terminalOf(range)
141
- } };
150
+ return {
151
+ slice: {
152
+ ...emptySlice(range.from),
153
+ nextOffset: range.nextOffset,
154
+ closed: range.closed === true,
155
+ upToDate: true,
156
+ ...terminalOf(range)
157
+ },
158
+ count: 0
159
+ };
142
160
  }
143
161
  let messages = [];
144
162
  let offsets = [];
@@ -187,31 +205,33 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
187
205
  offsets = offsets?.slice(0, range.count);
188
206
  if (compare(cursor, range.nextOffset) < 0) return yield* unreproducible("the input is shorter than the pin");
189
207
  }
190
- const slice = {
191
- from: range.from,
192
- items: yield* decodeMessages(input, address, messages),
193
- nextOffset: range.nextOffset,
194
- upToDate: range.upToDate ?? (last.upToDate && cursor === range.nextOffset),
195
- closed: range.closed === true
208
+ return {
209
+ slice: {
210
+ from: range.from,
211
+ ...yield* decodeMessages(input, address, messages, offsets),
212
+ nextOffset: range.nextOffset,
213
+ upToDate: range.upToDate ?? (last.upToDate && cursor === range.nextOffset),
214
+ closed: range.closed === true
215
+ },
216
+ count: messages.length
196
217
  };
197
- return { slice: offsets === void 0 ? slice : {
198
- ...slice,
199
- offsets
200
- } };
201
218
  });
202
219
  /** Read one server page per input in declaration order. */
203
220
  const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets, seen = false) {
204
221
  const slices = {};
222
+ const counts = {};
205
223
  let items = 0;
206
224
  for (const [name, address] of inputEntries(inputs)) {
207
225
  const from = offsets[name] ?? "";
208
226
  const read = yield* readOrGone(name, address, from, readSlice(name, address, from), seen);
209
227
  slices[name] = read.slice;
210
228
  items += read.slice.items.length;
229
+ if (read.count > 0) counts[name] = read.count;
211
230
  }
212
231
  return {
213
232
  slices,
214
- items
233
+ items,
234
+ counts
215
235
  };
216
236
  });
217
237
  /** Tagged items in declaration order, then stream order within each input. */
@@ -244,15 +264,16 @@ const pin$1 = (commit) => Object.defineProperty(commit, RangeKey, {
244
264
  const isPinned = (commit) => RangeKey in commit && commit[RangeKey] === "pin";
245
265
  const inherit = (source, target) => {
246
266
  if (supportsPrepare(source)) withPrepare(target);
247
- if (supportsAccepted(source)) withAccepted(target);
267
+ if (supportsFrontier(source)) withFrontier(target);
248
268
  return isPinned(source) ? pin$1(target) : extend(target);
249
269
  };
250
270
  const PrepareKey = Symbol.for("@streamsy/projection/internal/Prepare");
251
271
  const withPrepare = (commit) => Object.defineProperty(commit, PrepareKey, { value: true });
252
272
  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;
273
+ /** Marks a Commit that writes output batches, which both frontier destinations need. */
274
+ const FrontierKey = Symbol.for("@streamsy/projection/internal/Frontier");
275
+ const withFrontier = (commit) => Object.defineProperty(commit, FrontierKey, { value: true });
276
+ const supportsFrontier = (commit) => FrontierKey in commit && commit[FrontierKey] === true;
256
277
  // src/commit/model.ts
257
278
  const TypeId$1 = "~@streamsy/projection/Commit";
258
279
  /** Opaque to Commit authors; the kernel restores the original typed handler error. */
@@ -550,7 +571,7 @@ const transaction = Object.assign(withPrepare(make$1({
550
571
  }));
551
572
  return yield* Effect.void;
552
573
  })
553
- })).pipe(withAccepted), { [TransactionCommitTypeId]: true });
574
+ })).pipe(withFrontier), { [TransactionCommitTypeId]: true });
554
575
  /**
555
576
  * Clean up binding state in the owner's transaction on forget and retire.
556
577
  * The boundary follows the same nesting rules as {@link transaction}.
@@ -707,7 +728,7 @@ const producer = pin$1(make$1({
707
728
  }, result));
708
729
  return yield* Effect.void;
709
730
  })
710
- })).pipe(withAccepted);
731
+ })).pipe(withFrontier);
711
732
  // src/commit/at-least-once.ts
712
733
  const atLeastOnce = pin$1(make$1({
713
734
  name: "atLeastOnce",
@@ -760,56 +781,172 @@ var commit_exports = /* @__PURE__ */ __exportAll({
760
781
  transactionWithCleanup: () => transactionWithCleanup,
761
782
  withCompensation: () => withCompensation
762
783
  });
763
- // src/accepted.ts
764
- /** Private output name, stable across producer retries. */
784
+ // src/frontier.ts
785
+ /**
786
+ * The `frontier` option: one row builder, two destinations.
787
+ *
788
+ * Each unit publishes one `Streamsy.Frontier` row for each input that moved or
789
+ * closed, plus the frontier rows its State inputs carry. `frontier: true` appends
790
+ * the rows to each fixed State output that declares a frontier collection.
791
+ * `frontier: X` writes them to the frontier stream `X` as part of the unit.
792
+ */
793
+ /** Private output name of a frontier stream. Stable across producer retries, so keep the old name. */
765
794
  const acceptedKey = "@streamsy/accepted";
766
- const validateAccepted = (output, params, inputTemplates, commit, outputNames = []) => {
767
- if (output === void 0) return;
768
- if (!supportsAccepted(commit)) throw new RangeError("accepted requires Commit.transaction or Commit.producer");
795
+ const FrontierOutputs = Symbol.for("@streamsy/projection/internal/FrontierOutputs");
796
+ const frontierOutputs = (binding) => binding[FrontierOutputs];
797
+ /**
798
+ * Collections of an input that is read as raw JSON text, such as the State stream of a
799
+ * `StateTable`. Its frontier rows are forwarded like those of a decoded State input.
800
+ */
801
+ const RawCollections = Symbol.for("@streamsy/projection/internal/RawCollections");
802
+ /** @internal Shared with View.circuit. */
803
+ const isFrontierCollection = (collection) => Predicate.hasProperty(collection, "schema") && collection.schema === Streamsy.Frontier && Predicate.hasProperty(collection, "key") && collection.key === "stream";
804
+ const namesOf = (collections) => Predicate.isObject(collections) ? Array.filter(Record.keys(collections), (name) => isFrontierCollection(collections[name])) : [];
805
+ const frontierCollections = (value) => Predicate.hasProperty(value, "collections") ? namesOf(value.collections) : [];
806
+ const rawCollections = (value) => Predicate.hasProperty(value, RawCollections) ? namesOf(value[RawCollections]) : [];
807
+ const validateCollections = (outputs) => {
808
+ const collections = /* @__PURE__ */ new Map();
809
+ for (const [name, output] of Record.toEntries(outputs)) {
810
+ const generation = isPerGeneration(output) ? generationBinding(output) : void 0;
811
+ if (generation?.routeBy !== void 0) throw new RangeError("frontier does not support routed outputs");
812
+ const [collection, duplicate] = frontierCollections(generation?.route ?? output);
813
+ if (duplicate !== void 0) throw new RangeError(`frontier output ${name} declares more than one frontier collection`);
814
+ if (collection !== void 0) collections.set(name, collection);
815
+ }
816
+ if (collections.size === 0) throw new RangeError("frontier requires a fixed State output with a frontier collection");
817
+ return collections;
818
+ };
819
+ const validateStream = (output, params, inputTemplates, outputNames) => {
769
820
  validateGenerationParam(output, params);
770
- const { route: accepted, param, routeBy } = isPerGeneration(output) ? generationBinding(output) : {
821
+ const { route: stream, param, routeBy } = isPerGeneration(output) ? generationBinding(output) : {
771
822
  route: output,
772
823
  param: void 0,
773
824
  routeBy: void 0
774
825
  };
775
- if (routeBy !== void 0) throw new RangeError("accepted does not support routed outputs");
776
- if (accepted.collections !== Streamsy.wakeCollections) {
777
- if (accepted.collections.stream?.schema !== Streamsy.WakeRow || accepted.collections.stream.key !== "stream") throw new RangeError("accepted requires a wake stream declaration");
778
- }
779
- for (const name of Record.keys(accepted.paramCodecs)) if (name !== param && !Record.has(params, name)) throw new RangeError(`accepted parameter ${name} must be a projection parameter`);
780
- for (const template of inputTemplates) if (template === accepted.template) throw new RangeError("An accepted stream may not name an input stream");
781
- if (Array.contains(outputNames, "@streamsy/accepted")) throw new RangeError(`Output name ${acceptedKey} is reserved for accepted`);
826
+ if (routeBy !== void 0) throw new RangeError("frontier does not support routed outputs");
827
+ if (!isFrontierCollection(stream.collections.stream)) throw new RangeError("frontier requires a frontier stream declaration");
828
+ for (const name of Record.keys(stream.paramCodecs)) if (name !== param && !Record.has(params, name)) throw new RangeError(`frontier parameter ${name} must be a projection parameter`);
829
+ for (const template of inputTemplates) if (template === stream.template) throw new RangeError("A frontier stream may not name an input stream");
830
+ if (Array.contains(outputNames, "@streamsy/accepted")) throw new RangeError(`Output name ${acceptedKey} is reserved for the frontier stream`);
782
831
  };
783
- /** Only moved inputs contribute a row; terminal closes retain their final offset. */
784
- const acceptedOutput = (address, inputs, unit, closed = {}) => {
785
- const items = [];
832
+ /**
833
+ * Check the `frontier` option of a declaration. For `true`, answer the frontier collection
834
+ * of each output that gets the rows. A frontier stream answers `undefined`.
835
+ *
836
+ * @internal Shared with View.circuit.
837
+ */
838
+ const validateFrontier = (frontier, context) => {
839
+ if (frontier === void 0) return void 0;
840
+ if (!supportsFrontier(context.commit)) throw new RangeError("frontier requires Commit.transaction or Commit.producer");
841
+ const outputs = context.outputs ?? {};
842
+ if (frontier === true) return validateCollections(outputs);
843
+ validateStream(frontier, context.params, context.inputTemplates ?? [], Record.keys(outputs));
844
+ };
845
+ /** @internal Reject the removed `accepted` option, passed from JavaScript or unchecked TypeScript. */
846
+ const rejectAccepted = (id, definition) => {
847
+ if ("accepted" in definition && definition.accepted !== void 0) throw new RangeError(`Projection ${id}: accepted was removed. Use frontier: in its place.`);
848
+ };
849
+ /**
850
+ * The row of one input range, or undefined. An input that did not move gives no row,
851
+ * except once at its terminal close. A gone input gives no row.
852
+ */
853
+ const inputFrontier = (stream, range, closedBefore) => {
854
+ if (range.gone === true) return void 0;
855
+ const closed = range.closed === true;
856
+ if (compare(range.nextOffset, range.from) <= 0 && (!closed || closedBefore)) return void 0;
857
+ return closed ? {
858
+ stream,
859
+ offset: range.nextOffset,
860
+ closed: true
861
+ } : {
862
+ stream,
863
+ offset: range.nextOffset
864
+ };
865
+ };
866
+ /** An upsert of a frontier row, in any collection. The caller checks the collection name. */
867
+ const FrontierUpsert = Schema.Struct({
868
+ type: Schema.String,
869
+ value: Streamsy.Frontier,
870
+ headers: Schema.Struct({ operation: Schema.Literal("upsert") })
871
+ });
872
+ const isFrontierUpsert = Schema.is(FrontierUpsert);
873
+ const decodeRawUpsert = Schema.decodeUnknownOption(Schema.fromJsonString(FrontierUpsert));
874
+ /** The frontier upsert in one input item, decoded or stored JSON text. */
875
+ const frontierUpsert = (item, raw) => {
876
+ if (!raw) return isFrontierUpsert(item) ? item : void 0;
877
+ return Predicate.isString(item) ? Option.getOrUndefined(decodeRawUpsert(item)) : void 0;
878
+ };
879
+ /**
880
+ * The frontier rows of one unit, for either destination: the rows its State inputs carry,
881
+ * then one row for each input that moved or closed. `closed` holds the inputs whose close an
882
+ * earlier unit recorded.
883
+ *
884
+ * @internal Shared with View.circuit.
885
+ */
886
+ const unitFrontiers = (inputs, unit, batch, closed = {}) => {
887
+ const rows = /* @__PURE__ */ new Map();
888
+ for (const [name, slice] of Record.toEntries(batch)) {
889
+ const input = inputs[name];
890
+ if (input === void 0) continue;
891
+ const decoded = frontierCollections(input);
892
+ const raw = decoded.length === 0 ? rawCollections(input) : [];
893
+ const types = decoded.length === 0 ? raw : decoded;
894
+ if (types.length === 0) continue;
895
+ for (const value of slice.items) {
896
+ const item = frontierUpsert(value, raw.length > 0);
897
+ if (item === void 0 || !Array.contains(types, item.type)) continue;
898
+ const row = item.value;
899
+ const previous = rows.get(row.stream);
900
+ if (previous === void 0 || compare(row.offset, previous.offset) > 0) rows.set(row.stream, row);
901
+ }
902
+ }
786
903
  for (const [name, range] of Record.toEntries(unit.ranges)) {
787
904
  const input = inputs[name];
788
- if (input === void 0 || range.gone || compare(range.nextOffset, range.from) <= 0 && (!range.closed || closed[name])) continue;
789
- const stream = StreamId.make(input.id);
790
- const offset = Offset.make(range.nextOffset);
791
- const value = range.closed ? {
792
- stream,
793
- offset,
794
- closed: true
795
- } : {
796
- stream,
797
- offset
798
- };
799
- items.push({
800
- type: "stream",
801
- key: stream,
905
+ if (input === void 0) continue;
906
+ const row = inputFrontier(input.id, range, closed[name] === true);
907
+ if (row === void 0) continue;
908
+ const previous = rows.get(row.stream);
909
+ rows.delete(row.stream);
910
+ rows.set(row.stream, previous !== void 0 && compare(previous.offset, row.offset) > 0 ? previous : row);
911
+ }
912
+ return Array.fromIterable(rows.values());
913
+ };
914
+ /** `frontier: true`: append the rows to the buffers before the Commit writes any output. */
915
+ const frontierResult = (result, collections, rows) => {
916
+ if (result === void 0 || !("outputs" in result)) return result;
917
+ if (rows.length === 0) return result;
918
+ const outputs = { ...result.outputs };
919
+ for (const [name, type] of collections) {
920
+ const output = outputs[name];
921
+ if (output === void 0) continue;
922
+ const items = Array.map(rows, (value) => ({
923
+ type,
924
+ key: value.stream,
802
925
  value,
803
926
  headers: { operation: "upsert" }
804
- });
927
+ }));
928
+ outputs[name] = {
929
+ address: output.address,
930
+ items: [...output.items, ...items]
931
+ };
805
932
  }
806
- return {
933
+ return "encoded" in result ? Accumulated({
934
+ value: result.value,
935
+ encoded: result.encoded,
936
+ outputs
937
+ }) : Emitted({ outputs });
938
+ };
939
+ /** `frontier: X`: one more output batch for the frontier stream, added to every handler kind. */
940
+ const frontierStreamResult = (result, address, rows) => {
941
+ const output = {
807
942
  address,
808
- items
943
+ items: Array.map(rows, (value) => ({
944
+ type: "stream",
945
+ key: value.stream,
946
+ value,
947
+ headers: { operation: "upsert" }
948
+ }))
809
949
  };
810
- };
811
- /** Adapt every handler kind to the existing output-writing Commit result. */
812
- const acceptedResult = (result, output) => {
813
950
  const outputs = result !== void 0 && "outputs" in result ? {
814
951
  ...result.outputs,
815
952
  [acceptedKey]: output
@@ -826,7 +963,7 @@ const acceptedResult = (result, output) => {
826
963
  } : emitted;
827
964
  };
828
965
  // src/outputs.ts
829
- const resolveOutputs = (outputs, acceptedOutput, params, key, inputs) => {
966
+ const resolveOutputs = (outputs, frontierStream, params, key, inputs) => {
830
967
  const generationOutputs = /* @__PURE__ */ new Map();
831
968
  const resolve = (name, output) => {
832
969
  if (isPerGeneration(output)) {
@@ -847,7 +984,7 @@ const resolveOutputs = (outputs, acceptedOutput, params, key, inputs) => {
847
984
  }
848
985
  return [[name, resolve(name, output)]];
849
986
  }));
850
- const accepted = acceptedOutput === void 0 ? void 0 : resolve(acceptedKey, acceptedOutput);
987
+ const accepted = frontierStream === void 0 ? void 0 : resolve(acceptedKey, frontierStream);
851
988
  const addresses = accepted === void 0 ? Record.values(streams) : [...Record.values(streams), accepted];
852
989
  const ids = Array.map(addresses, (address) => address.id);
853
990
  if (new Set(ids).size !== ids.length) throw new RangeError("Two outputs may not name the same stream");
@@ -1063,8 +1200,17 @@ const rejectProjectionVersion = (id, definition) => {
1063
1200
  };
1064
1201
  const build = (kind, definition) => {
1065
1202
  rejectProjectionVersion(definition.id, definition);
1203
+ rejectAccepted(definition.id, definition);
1066
1204
  const commit = definition.commit ?? checkpoint;
1067
1205
  const outputs = definition.outputs ?? {};
1206
+ const stream = definition.frontier === true ? void 0 : definition.frontier;
1207
+ const frontier = validateFrontier(definition.frontier, {
1208
+ commit,
1209
+ params: definition.params,
1210
+ outputs,
1211
+ inputTemplates: Array.map(Array.filter(Record.values(definition.inputs), isDeclaration), (input) => input.template)
1212
+ });
1213
+ if (frontier !== void 0 && (kind === "fold" || kind === "process")) throw new RangeError("frontier requires Projection.emit, Projection.mapAccum or Projection.mapAccumBatch");
1068
1214
  for (const output of Record.values(outputs)) {
1069
1215
  validateGenerationParam(output, definition.params);
1070
1216
  if (isPerGeneration(output) && generationBinding(output).routeBy !== void 0) {
@@ -1072,12 +1218,11 @@ const build = (kind, definition) => {
1072
1218
  if (!supportsPrepare(commit)) throw new RangeError("Routed outputs require Commit.transaction");
1073
1219
  }
1074
1220
  }
1075
- validateAccepted(definition.accepted, definition.params, Array.map(Array.filter(Record.values(definition.inputs), isDeclaration), (input) => input.template), commit, Record.keys(outputs));
1076
1221
  if (definition.prepare !== void 0 && !supportsPrepare(commit)) throw new RangeError("prepare requires Commit.transaction");
1077
1222
  return declare(definition, ({ decoded, ...key }) => {
1078
1223
  const state = definition.state === void 0 ? void 0 : bindState(definition.state, decoded);
1079
1224
  const inputs = addressesOf(definition.inputs, decoded);
1080
- const { streams, accepted, generationOutputs, routed, handlerOutputs } = resolveOutputs(outputs, definition.accepted, decoded, key, inputs);
1225
+ const { streams, accepted, generationOutputs, routed, handlerOutputs } = resolveOutputs(outputs, stream, decoded, key, inputs);
1081
1226
  const bound = {
1082
1227
  ...key,
1083
1228
  inputs,
@@ -1090,6 +1235,7 @@ const build = (kind, definition) => {
1090
1235
  };
1091
1236
  if (generationOutputs.size > 0) Object.assign(bound, { [GenerationOutputs]: generationOutputs });
1092
1237
  if (routed.size > 0) Object.assign(bound, { [RoutedOutputs]: routed });
1238
+ if (frontier !== void 0) Object.assign(bound, { [FrontierOutputs]: frontier });
1093
1239
  return bound;
1094
1240
  });
1095
1241
  };
@@ -1181,6 +1327,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1181
1327
  message: `Commit ${projection.commit.name} cannot resume a pinned unit`
1182
1328
  });
1183
1329
  let batch;
1330
+ let counts;
1184
1331
  let count = 0;
1185
1332
  let due = pending?.due;
1186
1333
  let dueOnly = pending !== void 0 && due !== void 0 && Record.isEmptyRecord(pending.ranges);
@@ -1189,6 +1336,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1189
1336
  if (before.record.wakeAt <= now) due = before.record.wakeAt;
1190
1337
  }
1191
1338
  if (pending !== void 0) {
1339
+ counts = Record.map(pending.ranges, (range) => range.count);
1192
1340
  const slices = {};
1193
1341
  for (const [name, address] of inputEntries(projection.inputs)) {
1194
1342
  const range = pending.ranges[name];
@@ -1204,8 +1352,10 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1204
1352
  const read = yield* readInputs(projection.inputs, before.record.inputs, Option.isSome(before.loaded.record));
1205
1353
  batch = read.slices;
1206
1354
  count = read.items;
1355
+ counts = read.counts;
1207
1356
  const terminal = Array.some(Record.toEntries(batch), ([name, slice]) => slice.gone === true || slice.closed && slice.upToDate && !before.record.closed?.[name]);
1208
- if (count === 0 && !terminal && (due === void 0 || !allowEmptyDue)) return {
1357
+ const empty = Record.isEmptyRecord(counts);
1358
+ if (empty && !terminal && (due === void 0 || !allowEmptyDue)) return {
1209
1359
  status: Array.every(Record.values(batch), (slice) => slice.closed) ? "source-closed" : "caught-up",
1210
1360
  units: 0,
1211
1361
  items: 0,
@@ -1213,7 +1363,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1213
1363
  encoded: before.record.state,
1214
1364
  wakeAt: Option.fromUndefinedOr(before.record.wakeAt)
1215
1365
  };
1216
- dueOnly = count === 0 && !terminal;
1366
+ dueOnly = empty && !terminal;
1217
1367
  if (dueOnly) batch = Record.map(batch, (_slice, name) => emptySlice(before.record.inputs[name] ?? ""));
1218
1368
  }
1219
1369
  const gone = Array.some(Record.values(batch), (slice) => slice.gone === true);
@@ -1245,10 +1395,12 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1245
1395
  let prepared;
1246
1396
  let result;
1247
1397
  const run = Effect.suspend(() => projection.process(batch, unit, before.record.state, prepared, context?.attempt ?? 1)).pipe(Effect.map((value) => {
1248
- if (projection.accepted === void 0) return value;
1398
+ const frontier = frontierOutputs(projection);
1399
+ if (projection.accepted === void 0 && frontier === void 0) return value;
1249
1400
  const handled = value;
1250
- const output = acceptedOutput(projection.accepted, projection.inputs, unit, before.record.closed);
1251
- return acceptedResult(handled, output);
1401
+ const rows = unitFrontiers(projection.inputs, unit, batch, before.record.closed);
1402
+ const withFrontier = frontier === void 0 ? handled : frontierResult(handled, frontier, rows);
1403
+ return projection.accepted === void 0 ? withFrontier : frontierStreamResult(withFrontier, projection.accepted, rows);
1252
1404
  }), Effect.tap((value) => Effect.sync(() => {
1253
1405
  result = value;
1254
1406
  })), Effect.mapError((error) => new HandlerFailed({ error })));
@@ -1266,7 +1418,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
1266
1418
  prepare,
1267
1419
  ranges: Record.fromEntries(Array.map(Record.toEntries(ranges), ([name, range]) => [name, {
1268
1420
  ...range,
1269
- count: batch[name]?.items.length ?? 0,
1421
+ count: counts[name] ?? 0,
1270
1422
  closed: batch[name]?.closed ?? false,
1271
1423
  upToDate: batch[name]?.upToDate ?? false
1272
1424
  }]))
@@ -1575,7 +1727,7 @@ const storageFault = (operation) => (cause) => new StorageFault({
1575
1727
  });
1576
1728
  // src/triggers.ts
1577
1729
  const DEFAULT_LIMIT$1 = 1e3;
1578
- const decodeWakeMessage = Schema.decodeEffect(Schema.fromJsonString(Streamsy.WakeMessage));
1730
+ const decodeFrontierMessage = Schema.decodeEffect(Schema.fromJsonString(Streamsy.FrontierMessage));
1579
1731
  const decoder = new TextDecoder();
1580
1732
  const invalid = (id, message, cause) => new ProjectionFault({
1581
1733
  phase: "read",
@@ -1662,14 +1814,14 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
1662
1814
  limit: DEFAULT_LIMIT$1
1663
1815
  });
1664
1816
  for (const message of messages) {
1665
- const event = yield* decodeWakeMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => new ProjectionFault({
1817
+ const event = yield* decodeFrontierMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => new ProjectionFault({
1666
1818
  phase: "read",
1667
1819
  reason: "invalid-source",
1668
1820
  message: `Cannot decode trigger ${id} at offset ${message.offset}`,
1669
1821
  cause
1670
1822
  })));
1671
1823
  if (!StreamAddress.isChange(event)) continue;
1672
- const binding = match(StreamAddress.isUpsert(event) ? event.value.stream : StreamId.make(event.key));
1824
+ const binding = match(StreamId.make(StreamAddress.isUpsert(event) ? event.value.stream : event.key));
1673
1825
  if (Option.isSome(binding)) found.add(binding.value[0]);
1674
1826
  else yield* Effect.logWarning(`Projection ${projection} skipped unmatched trigger source ${event.key} from ${id}`);
1675
1827
  }
@@ -1719,9 +1871,9 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
1719
1871
  const offset = yield* Schema.decodeEffect(Offset)(result.nextOffset).pipe(Effect.mapError((cause) => invalid(id, "Invalid trigger page cursor", cause)));
1720
1872
  const found = /* @__PURE__ */ new Set();
1721
1873
  for (const message of result.messages) {
1722
- const event = yield* decodeWakeMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => invalid(id, `Cannot decode trigger page after ${from}`, cause)));
1874
+ const event = yield* decodeFrontierMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => invalid(id, `Cannot decode trigger page after ${from}`, cause)));
1723
1875
  if (!StreamAddress.isChange(event)) continue;
1724
- const binding = match(StreamAddress.isUpsert(event) ? event.value.stream : StreamId.make(event.key));
1876
+ const binding = match(StreamId.make(StreamAddress.isUpsert(event) ? event.value.stream : event.key));
1725
1877
  if (Option.isSome(binding)) found.add(binding.value[0]);
1726
1878
  else yield* Effect.logWarning(`Projection ${projection} skipped unmatched trigger source ${event.key} from ${id}`);
1727
1879
  }
@@ -1844,7 +1996,7 @@ const historyUnavailable = (input, message, cause) => new ProjectionFault({
1844
1996
  message,
1845
1997
  cause
1846
1998
  });
1847
- const head$1 = Effect.fn("Projection.catchUp.head")(function* (name, address) {
1999
+ const head = Effect.fn("Projection.catchUp.head")(function* (name, address) {
1848
2000
  const { wire } = yield* address.stream;
1849
2001
  const storageFailure = (cause) => new ProjectionFault({
1850
2002
  phase: "read",
@@ -1873,7 +2025,7 @@ const head$1 = Effect.fn("Projection.catchUp.head")(function* (name, address) {
1873
2025
  });
1874
2026
  /** Capture each resolved input head once. The vector can be reused while producers keep writing. */
1875
2027
  const tails = Effect.fn("Projection.tails")(function* (projection) {
1876
- const entries = yield* Effect.forEach(inputEntries(projection.inputs), ([name, address]) => head$1(name, address).pipe(Effect.map((value) => [name, value])));
2028
+ const entries = yield* Effect.forEach(inputEntries(projection.inputs), ([name, address]) => head(name, address).pipe(Effect.map((value) => [name, value])));
1877
2029
  return Record.fromEntries(entries);
1878
2030
  });
1879
2031
  const validateTails = Effect.fnUntraced(function* (projection, targets) {
@@ -1916,7 +2068,7 @@ const measure = Effect.fnUntraced(function* (projection, targets, verifyHeads) {
1916
2068
  message: `Stored offset for ${name} is not a valid offset`
1917
2069
  });
1918
2070
  if (verifyHeads) {
1919
- const current = yield* head$1(name, address);
2071
+ const current = yield* head(name, address);
1920
2072
  const order = compare(current.offset, target.offset);
1921
2073
  if (order < 0 || target.closed && (!current.closed || order !== 0)) return yield* historyUnavailable(name, `Head of ${address.id} no longer contains its tail`);
1922
2074
  }
@@ -2389,7 +2541,7 @@ var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Sche
2389
2541
  * window, and the layer runs due marks when it starts. Recorded process timers
2390
2542
  * wake at their deadline; after host suspend, a capped wait rechecks within 30 s.
2391
2543
  * Return a time after unit.due to avoid repeatedly running a passed deadline.
2392
- * Inputs on another owner can use local or remote wake streams in `triggers`.
2544
+ * Inputs on another owner can use local or remote frontier streams in `triggers`.
2393
2545
  * A provided trigger service on another owner is read one page per pass outside
2394
2546
  * the local transaction; durable marks and the page cursor then commit together.
2395
2547
  * A scoped live-read follower signals new remote rows. Remote read failures use
@@ -2398,7 +2550,7 @@ var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Sche
2398
2550
  * an attached binding under `Projection.follow` too: use one writer per key.
2399
2551
  *
2400
2552
  * ```ts
2401
- * const app = Layer.mergeAll(Api, Projection.attach(filesWake)).pipe(
2553
+ * const app = Layer.mergeAll(Api, Projection.attach(filesFrontier)).pipe(
2402
2554
  * Layer.provideMerge(BunStorage.layer(streams, { path })),
2403
2555
  * );
2404
2556
  * ```
@@ -2479,7 +2631,7 @@ const current = Effect.fn("Projection.current")(function* (projection) {
2479
2631
  let state = yield* currentState(projection, projection.state, encoded);
2480
2632
  while (true) {
2481
2633
  const page = yield* readInputs(projection.inputs, offsets);
2482
- if (page.items === 0) return {
2634
+ if (Record.isEmptyRecord(page.counts)) return {
2483
2635
  state,
2484
2636
  offsets: offsetsOf$1({ inputs: offsets })
2485
2637
  };
@@ -2674,35 +2826,32 @@ const retire = (declaration, params, options) => {
2674
2826
  };
2675
2827
  });
2676
2828
  };
2677
- // src/wake.ts
2678
- const row = (stream, offset, closed) => DurableState.upsert("stream", closed ? {
2679
- stream,
2680
- offset: Offset.make(offset),
2681
- closed: true
2682
- } : {
2683
- stream,
2684
- offset: Offset.make(offset)
2685
- });
2829
+ // src/frontier-projection.ts
2686
2830
  /**
2687
- * A wake projection: one source stream gives one keyed row in one wake stream.
2831
+ * A frontier projection: one source stream gives one keyed row in one frontier stream.
2688
2832
  * Each unit appends one upsert `{ stream, offset, closed? }` with
2689
2833
  * `Commit.producer`, so several source writes in one unit fold into one row,
2690
- * and a retry answers `Duplicate`. The producer creates a missing wake stream
2691
- * on its own owner. A wake stream on another owner must exist before the first
2834
+ * and a retry answers `Duplicate`. The producer creates a missing frontier stream
2835
+ * on its own owner. A frontier stream on another owner must exist before the first
2692
2836
  * append: its owner creates it at start. When the source is removed or
2693
2837
  * expires, the binding appends a State delete for its row and forgets itself.
2694
2838
  *
2839
+ * The row is the one that `frontier: output` would publish for the source, except that a
2840
+ * gone source deletes its row, so that triggers clear their outputs. Rows that a State
2841
+ * source carries are not forwarded.
2842
+ *
2695
2843
  * ```ts
2696
- * const filesWake = Projection.wake({
2844
+ * const filesFrontier = Projection.frontier({
2697
2845
  * id: "files-wake",
2698
2846
  * params: { user: UserKey, folderId: FolderKey },
2699
2847
  * input: Files,
2700
- * output: UserWake,
2848
+ * output: UserFrontier,
2701
2849
  * });
2702
2850
  * ```
2703
2851
  */
2704
- function wake(definition) {
2852
+ function frontier(definition) {
2705
2853
  rejectProjectionVersion(definition.id, definition);
2854
+ rejectAccepted(definition.id, definition);
2706
2855
  const input = definition.input;
2707
2856
  return build("mapAccumBatch", {
2708
2857
  id: definition.id,
@@ -2711,15 +2860,17 @@ function wake(definition) {
2711
2860
  commit: producer,
2712
2861
  inputs: { source: input },
2713
2862
  outputs: { wake: definition.output },
2714
- accepted: definition.accepted,
2715
2863
  state: {
2716
2864
  schema: Schema.Null,
2717
2865
  initial: null
2718
2866
  },
2719
2867
  mapAccumBatch: (_state, batch, unit) => {
2720
2868
  const source = isDeclaration(input) ? input.at(unit.params) : input;
2721
- const slice = batch.source;
2722
- return [null, { wake: [slice.gone ? DurableState.remove("stream", StreamId.make(source.id)) : row(StreamId.make(source.id), slice.nextOffset, slice.closed)] }];
2869
+ const stream = StreamId.make(source.id);
2870
+ if (batch.source.gone === true) return [null, { wake: [DurableState.remove("stream", stream)] }];
2871
+ const range = unit.ranges.source;
2872
+ const value = range === void 0 ? void 0 : inputFrontier(stream, range, false);
2873
+ return [null, { wake: value === void 0 ? [] : [DurableState.upsert("stream", value)] }];
2723
2874
  }
2724
2875
  });
2725
2876
  }
@@ -2739,6 +2890,7 @@ var projection_exports = /* @__PURE__ */ __exportAll({
2739
2890
  fold: () => fold,
2740
2891
  follow: () => follow,
2741
2892
  forget: () => forget,
2893
+ frontier: () => frontier,
2742
2894
  generationBinding: () => generationBinding,
2743
2895
  isPerGeneration: () => isPerGeneration,
2744
2896
  items: () => items,
@@ -2753,7 +2905,6 @@ var projection_exports = /* @__PURE__ */ __exportAll({
2753
2905
  retire: () => retire,
2754
2906
  run: () => run,
2755
2907
  tails: () => tails,
2756
- wake: () => wake,
2757
2908
  wakeAt: () => wakeAt
2758
2909
  });
2759
2910
  const key = (projection) => ({
@@ -2764,36 +2915,13 @@ const key = (projection) => ({
2764
2915
  /** Runs each tagged entry in order and discards its success value. */
2765
2916
  const each = (handle) => (batch, unit) => Effect.forEach(items(batch), (entry) => handle(entry, unit), { discard: true });
2766
2917
  // src/state-table-message.ts
2767
- const Message = Schema.Union([
2768
- Schema.Struct({ headers: Schema.Struct({ control: Schema.Literals([
2769
- "reset",
2770
- "snapshot-start",
2771
- "snapshot-end"
2772
- ]) }) }),
2773
- Schema.Struct({
2774
- type: Schema.String,
2775
- key: Schema.String,
2776
- headers: Schema.Struct({ operation: Schema.Literals([
2777
- "insert",
2778
- "update",
2779
- "upsert"
2780
- ]) }),
2781
- value: Schema.Unknown
2782
- }),
2783
- Schema.Struct({
2784
- type: Schema.String,
2785
- key: Schema.String,
2786
- headers: Schema.Struct({ operation: Schema.Literal("delete") })
2787
- })
2788
- ]);
2789
2918
  const Change = Data.taggedEnum();
2790
- const decode = Schema.decodeEffect(Schema.fromJsonString(Message));
2791
2919
  /**
2792
2920
  * Only the protocol envelope is decoded; collection values never pass through a codec.
2793
2921
  * `JSON.stringify` gives the bytes that storage holds, because core stores each JSON
2794
2922
  * message as `JSON.stringify` of the parsed item.
2795
2923
  */
2796
- const message = (json) => Effect.map(decode(json), (decoded) => {
2924
+ const message = (json) => Effect.map(decodeStateWire(json), (decoded) => {
2797
2925
  if (!("type" in decoded)) return Change.Control({ control: decoded.headers.control });
2798
2926
  return "value" in decoded ? Change.Upsert({
2799
2927
  collection: decoded.type,
@@ -2817,60 +2945,433 @@ const deleteJson = (collection, key) => JSON.stringify({
2817
2945
  const decodeRow = (schema, json) => Schema.decodeEffect(Schema.fromJsonString(Schema.toCodecJson(schema)))(json);
2818
2946
  /** Encode one row to the canonical JSON that the table stores for it. */
2819
2947
  const encodeRow = (schema, value) => Schema.encodeEffect(Schema.fromJsonString(Schema.toCodecJson(schema)))(value);
2820
- /** The stored JSON of each key that has a row. A missing key has no entry. */
2821
- const storedValues = Effect.fn("StateTable.storedValues")(function* (sql, id, collection, keys) {
2822
- const values = /* @__PURE__ */ new Map();
2823
- for (const chunk of Array.chunksOf(keys, 50)) {
2824
- const found = yield* sql`SELECT row_key, value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND ${sql.in("row_key", chunk)}`;
2825
- for (const row of found) values.set(row.row_key, row.value);
2948
+ /**
2949
+ * The stored JSON of each key that has a row. A missing key has no entry, and nor has a
2950
+ * key that the table cannot store.
2951
+ */
2952
+ const storedValues = (store, id, collection, keys) => store.values(id, collection, Array.filter(keys, (key) => Option.isNone(store.unstorable(collection, key))));
2953
+ // src/state-table-memory.ts
2954
+ const tombstone = Symbol("@streamsy/projection/StateTableMemory/tombstone");
2955
+ /** Private: the committed rows and head of one stream, for test dumps. */
2956
+ const MemoryRows = Symbol.for("@streamsy/projection/internal/StateTableMemoryRows");
2957
+ /**
2958
+ * Compare by code point, which is UTF-8 byte order and SQL's binary collations.
2959
+ * JavaScript's `<` compares UTF-16 code units, so it sorts U+1F600 before U+E000.
2960
+ */
2961
+ const compareCodePoints = (left, right) => {
2962
+ const length = Math.min(left.length, right.length);
2963
+ for (let index = 0; index < length; index++) {
2964
+ const a = left.charCodeAt(index);
2965
+ const b = right.charCodeAt(index);
2966
+ if (a !== b) return rank(a) - rank(b);
2967
+ }
2968
+ return left.length - right.length;
2969
+ };
2970
+ /** Code point order as an `Order`, for sorting keys. */
2971
+ const byCodePoint = (left, right) => {
2972
+ const order = compareCodePoints(left, right);
2973
+ return order < 0 ? -1 : order > 0 ? 1 : 0;
2974
+ };
2975
+ const rank = (unit) => unit >= 55296 && unit <= 57343 ? unit + 8192 : unit >= 57344 ? unit - 2048 : unit;
2976
+ /** The first index of `keys` that sorts after `after`. */
2977
+ const upperBound = (keys, after) => {
2978
+ let first = 0;
2979
+ let end = keys.length;
2980
+ while (first < end) {
2981
+ const mid = Math.floor((first + end) / 2);
2982
+ if (compareCodePoints(keys[mid], after) <= 0) first = mid + 1;
2983
+ else end = mid;
2826
2984
  }
2827
- return values;
2985
+ return first;
2986
+ };
2987
+ const unwritable = (id) => new ProjectionFault({
2988
+ phase: "process",
2989
+ reason: "unsupported-composition",
2990
+ message: `The rows of ${id} have no open memory owner transaction on this fiber. Write them inside the storage owner's transaction.`
2991
+ });
2992
+ const page = (keys, rows, options) => {
2993
+ const first = options.after === void 0 ? 0 : upperBound(keys, options.after);
2994
+ const selected = keys.slice(first, options.limit === void 0 ? void 0 : first + options.limit);
2995
+ return Array.map(selected, (row_key) => ({
2996
+ row_key,
2997
+ value: rows.get(row_key).value
2998
+ }));
2999
+ };
3000
+ /**
3001
+ * Rows in the heap of one memory owner. A unit writes to a private write set that
3002
+ * commits with the owner's transaction and is dropped on rollback, so a read outside
3003
+ * the unit sees committed rows only. A read inside the transaction but on a forked
3004
+ * fiber cannot enlist either, so it also sees committed rows only.
3005
+ */
3006
+ const makeStore = (owner) => {
3007
+ const committed = /* @__PURE__ */ new Map();
3008
+ /** Sorted keys of committed rows, by stream and collection, dropped when a commit changes them. */
3009
+ const sorted = /* @__PURE__ */ new Map();
3010
+ /** The open unit's writes. The owner runs one transaction at a time. */
3011
+ let written;
3012
+ /** True on the owner fiber inside its transaction, which then commits or drops `written`. */
3013
+ const inUnit = Effect.match(enlist(owner, {
3014
+ onCommit: () => {
3015
+ const writes = written;
3016
+ written = void 0;
3017
+ if (writes === void 0) return;
3018
+ for (const [id, write] of writes) {
3019
+ const base = committed.get(id) ?? {
3020
+ head: void 0,
3021
+ rows: /* @__PURE__ */ new Map()
3022
+ };
3023
+ const keys = sorted.get(id);
3024
+ if (write.cleared) {
3025
+ base.rows.clear();
3026
+ sorted.delete(id);
3027
+ }
3028
+ for (const [collection, pending] of write.rows) {
3029
+ let rows = base.rows.get(collection);
3030
+ for (const [key, row] of pending) if (row === tombstone) {
3031
+ if (rows?.delete(key) === true) keys?.delete(collection);
3032
+ } else {
3033
+ if (rows === void 0) {
3034
+ rows = /* @__PURE__ */ new Map();
3035
+ base.rows.set(collection, rows);
3036
+ }
3037
+ if (!rows.has(key)) keys?.delete(collection);
3038
+ rows.set(key, row);
3039
+ }
3040
+ if (rows?.size === 0) base.rows.delete(collection);
3041
+ }
3042
+ if (write.head === null) base.head = void 0;
3043
+ else if (write.head !== void 0) base.head = write.head;
3044
+ if (base.head === void 0 && base.rows.size === 0) {
3045
+ committed.delete(id);
3046
+ sorted.delete(id);
3047
+ } else committed.set(id, base);
3048
+ }
3049
+ },
3050
+ onRollback: () => {
3051
+ written = void 0;
3052
+ }
3053
+ }), {
3054
+ onFailure: () => false,
3055
+ onSuccess: () => true
3056
+ });
3057
+ const writeSet = (id) => Effect.flatMap(inUnit, (enlisted) => {
3058
+ if (!enlisted) return Effect.fail(unwritable(id));
3059
+ written ??= /* @__PURE__ */ new Map();
3060
+ let write = written.get(id);
3061
+ if (write === void 0) {
3062
+ write = {
3063
+ cleared: false,
3064
+ head: void 0,
3065
+ rows: /* @__PURE__ */ new Map()
3066
+ };
3067
+ written.set(id, write);
3068
+ }
3069
+ return Effect.succeed(write);
3070
+ });
3071
+ /** Run `body` on the stream's write set. A store write without a unit is a defect. */
3072
+ const write = (id, body) => Effect.asVoid(Effect.map(Effect.orDie(writeSet(id)), (state) => {
3073
+ body(state);
3074
+ }));
3075
+ const pendingRows = (state, collection) => {
3076
+ let rows = state.rows.get(collection);
3077
+ if (rows === void 0) {
3078
+ rows = /* @__PURE__ */ new Map();
3079
+ state.rows.set(collection, rows);
3080
+ }
3081
+ return rows;
3082
+ };
3083
+ /** The write set of `id` that this fiber sees, if any. */
3084
+ const visible = (id) => Effect.map(inUnit, (enlisted) => enlisted && written !== void 0 ? written.get(id) : void 0);
3085
+ const committedRow = (id, collection, key) => committed.get(id)?.rows.get(collection)?.get(key);
3086
+ const rowOf = (state, id, collection, key) => {
3087
+ const pending = state?.rows.get(collection)?.get(key);
3088
+ if (pending === tombstone) return void 0;
3089
+ if (pending !== void 0) return pending;
3090
+ if (state?.cleared === true) return void 0;
3091
+ return committedRow(id, collection, key);
3092
+ };
3093
+ /** Every row of `collection` that `state` leaves, by key. */
3094
+ const rowsOf = (state, id, collection) => {
3095
+ const rows = new Map(state?.cleared === true ? [] : committed.get(id)?.rows.get(collection) ?? []);
3096
+ for (const [key, row] of state?.rows.get(collection) ?? []) if (row === tombstone) rows.delete(key);
3097
+ else rows.set(key, row);
3098
+ return rows;
3099
+ };
3100
+ const committedKeys = (id, collection) => {
3101
+ let streams = sorted.get(id);
3102
+ const cached = streams?.get(collection);
3103
+ if (cached !== void 0) return cached;
3104
+ const keys = Array.sort(committed.get(id)?.rows.get(collection)?.keys() ?? [], byCodePoint);
3105
+ if (streams === void 0) {
3106
+ streams = /* @__PURE__ */ new Map();
3107
+ sorted.set(id, streams);
3108
+ }
3109
+ streams.set(collection, keys);
3110
+ return keys;
3111
+ };
3112
+ return {
3113
+ writer: (id) => Effect.asVoid(writeSet(id)),
3114
+ head: (id) => Effect.map(visible(id), (state) => {
3115
+ if (state?.head === null) return Option.none();
3116
+ if (state?.head !== void 0) return Option.some(state.head);
3117
+ return Option.fromUndefinedOr(committed.get(id)?.head);
3118
+ }),
3119
+ saveHead: (id, head) => write(id, (state) => {
3120
+ state.head = { ...head };
3121
+ }),
3122
+ deleteHead: (id) => write(id, (state) => {
3123
+ state.head = null;
3124
+ }),
3125
+ clearRows: (id) => write(id, (state) => {
3126
+ state.cleared = true;
3127
+ state.rows.clear();
3128
+ }),
3129
+ deleteBefore: (id, epoch) => write(id, (state) => {
3130
+ const collections = /* @__PURE__ */ new Set([...state.cleared ? [] : committed.get(id)?.rows.keys() ?? [], ...state.rows.keys()]);
3131
+ for (const collection of collections) {
3132
+ const pending = pendingRows(state, collection);
3133
+ for (const [key, row] of rowsOf(state, id, collection)) if (row.epoch < epoch) pending.set(key, tombstone);
3134
+ }
3135
+ }),
3136
+ upsertRow: (id, row, epoch) => write(id, (state) => {
3137
+ pendingRows(state, row.collection).set(row.key, {
3138
+ value: row.value,
3139
+ epoch
3140
+ });
3141
+ }),
3142
+ deleteRow: (id, collection, key) => write(id, (state) => {
3143
+ pendingRows(state, collection).set(key, tombstone);
3144
+ }),
3145
+ value: (id, collection, key) => Effect.map(visible(id), (state) => Option.map(Option.fromUndefinedOr(rowOf(state, id, collection, key)), (row) => row.value)),
3146
+ values: (id, collection, keys) => Effect.map(visible(id), (state) => {
3147
+ const values = /* @__PURE__ */ new Map();
3148
+ for (const key of keys) {
3149
+ const row = rowOf(state, id, collection, key);
3150
+ if (row !== void 0) values.set(key, row.value);
3151
+ }
3152
+ return values;
3153
+ }),
3154
+ list: (id, collection, options) => Effect.map(visible(id), (state) => {
3155
+ if (state === void 0 || !state.cleared && !state.rows.has(collection)) {
3156
+ const rows = committed.get(id)?.rows.get(collection);
3157
+ return rows === void 0 ? [] : page(committedKeys(id, collection), rows, options);
3158
+ }
3159
+ const rows = rowsOf(state, id, collection);
3160
+ return page(Array.sort(rows.keys(), byCodePoint), rows, options);
3161
+ }),
3162
+ unstorable: () => Option.none(),
3163
+ [MemoryRows]: (id) => ({
3164
+ head: committed.get(id)?.head,
3165
+ rows: Array.flatMap(Array.fromIterable(committed.get(id)?.rows ?? []), ([collection, rows]) => Array.map(Array.fromIterable(rows), ([key, row]) => ({
3166
+ collection,
3167
+ key,
3168
+ ...row
3169
+ })))
3170
+ })
3171
+ };
3172
+ };
3173
+ const stores = /* @__PURE__ */ new WeakMap();
3174
+ /** The one store of `owner`, so that every layer built over the owner shares its rows. */
3175
+ const memoryStore = (owner) => {
3176
+ let store = stores.get(owner);
3177
+ if (store === void 0) {
3178
+ store = makeStore(owner);
3179
+ stores.set(owner, store);
3180
+ }
3181
+ return store;
3182
+ };
3183
+ const MYSQL_TEXT_KEY = "CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin";
3184
+ const unsupported = () => Effect.fail(new ProjectionFault({
3185
+ phase: "load",
3186
+ reason: "unsupported-composition",
3187
+ message: "Unsupported SQL dialect; StateTable supports sqlite, pg and mysql"
3188
+ }));
3189
+ /** Create both tables. The SQLite DDL is unchanged since StateTable was added. */
3190
+ const createTables = (sql) => sql.onDialectOrElse({
3191
+ sqlite: () => Effect.gen(function* () {
3192
+ yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_heads (
3193
+ stream_id TEXT PRIMARY KEY,
3194
+ applied_offset TEXT NOT NULL,
3195
+ epoch INTEGER NOT NULL DEFAULT 0,
3196
+ snapshot_open INTEGER NOT NULL DEFAULT 0
3197
+ ) WITHOUT ROWID`;
3198
+ yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_rows (
3199
+ stream_id TEXT NOT NULL,
3200
+ collection TEXT NOT NULL,
3201
+ row_key TEXT NOT NULL,
3202
+ value TEXT NOT NULL,
3203
+ epoch INTEGER NOT NULL DEFAULT 0,
3204
+ PRIMARY KEY (stream_id, collection, row_key)
3205
+ ) WITHOUT ROWID`;
3206
+ }),
3207
+ pg: () => Effect.gen(function* () {
3208
+ yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_heads (
3209
+ stream_id TEXT COLLATE "C" PRIMARY KEY,
3210
+ applied_offset TEXT NOT NULL,
3211
+ epoch INTEGER NOT NULL DEFAULT 0,
3212
+ snapshot_open INTEGER NOT NULL DEFAULT 0
3213
+ )`;
3214
+ yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_rows (
3215
+ stream_id TEXT COLLATE "C" NOT NULL,
3216
+ collection TEXT COLLATE "C" NOT NULL,
3217
+ row_key TEXT COLLATE "C" NOT NULL,
3218
+ value TEXT NOT NULL,
3219
+ epoch INTEGER NOT NULL DEFAULT 0,
3220
+ PRIMARY KEY (stream_id, collection, row_key)
3221
+ )`;
3222
+ }),
3223
+ mysql: () => Effect.gen(function* () {
3224
+ yield* sql.unsafe(`CREATE TABLE IF NOT EXISTS streamsy_state_heads (
3225
+ stream_id VARCHAR(512) ${MYSQL_TEXT_KEY} PRIMARY KEY,
3226
+ applied_offset TEXT NOT NULL,
3227
+ epoch INT NOT NULL DEFAULT 0,
3228
+ snapshot_open INT NOT NULL DEFAULT 0
3229
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`);
3230
+ yield* sql.unsafe(`CREATE TABLE IF NOT EXISTS streamsy_state_rows (
3231
+ stream_id VARCHAR(512) ${MYSQL_TEXT_KEY} NOT NULL,
3232
+ collection VARCHAR(64) ${MYSQL_TEXT_KEY} NOT NULL,
3233
+ row_key VARCHAR(192) ${MYSQL_TEXT_KEY} NOT NULL,
3234
+ value LONGTEXT NOT NULL,
3235
+ epoch INT NOT NULL DEFAULT 0,
3236
+ PRIMARY KEY (stream_id, collection, row_key)
3237
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`);
3238
+ }),
3239
+ orElse: unsupported
2828
3240
  });
3241
+ /**
3242
+ * Lock the head row on server dialects, so that concurrent units apply one gap in turn
3243
+ * and the second sees the first's head. SQLite already has one writer.
3244
+ */
3245
+ const lockHead = (sql) => sql.onDialectOrElse({
3246
+ sqlite: () => sql``,
3247
+ orElse: () => sql`FOR UPDATE`
3248
+ });
3249
+ const saveHead = (sql, id, state) => {
3250
+ const values = sql`(stream_id, applied_offset, epoch, snapshot_open)
3251
+ VALUES (${id}, ${state.applied_offset}, ${state.epoch}, ${state.snapshot_open})`;
3252
+ return sql.onDialectOrElse({
3253
+ mysql: () => sql`INSERT INTO streamsy_state_heads ${values}
3254
+ ON DUPLICATE KEY UPDATE applied_offset = VALUES(applied_offset),
3255
+ epoch = VALUES(epoch), snapshot_open = VALUES(snapshot_open)`,
3256
+ orElse: () => sql`INSERT INTO streamsy_state_heads ${values}
3257
+ ON CONFLICT (stream_id) DO UPDATE SET applied_offset = excluded.applied_offset,
3258
+ epoch = excluded.epoch, snapshot_open = excluded.snapshot_open`
3259
+ });
3260
+ };
3261
+ const upsertRow = (sql, id, row, epoch) => {
3262
+ const values = sql`(stream_id, collection, row_key, value, epoch)
3263
+ VALUES (${id}, ${row.collection}, ${row.key}, ${row.value}, ${epoch})`;
3264
+ return sql.onDialectOrElse({
3265
+ mysql: () => sql`INSERT INTO streamsy_state_rows ${values}
3266
+ ON DUPLICATE KEY UPDATE value = VALUES(value), epoch = VALUES(epoch)`,
3267
+ orElse: () => sql`INSERT INTO streamsy_state_rows ${values}
3268
+ ON CONFLICT (stream_id, collection, row_key) DO UPDATE SET value = excluded.value, epoch = excluded.epoch`
3269
+ });
3270
+ };
3271
+ const tooLong = (column, value, limit) => {
3272
+ const length = [...value].length;
3273
+ return length > limit ? Option.some(`StateTable ${column} has ${length} characters; the MySQL limit is ${limit}`) : Option.none();
3274
+ };
3275
+ const hasNul = (column, value) => value.includes("\0") ? Option.some(`StateTable ${column} contains a NUL character, which Postgres text cannot store`) : Option.none();
3276
+ /**
3277
+ * Why the table cannot store a row of `collection` under `key`, if it cannot. MySQL
3278
+ * keys are bounded, and Postgres text rejects NUL. SQLite stores every string.
3279
+ */
3280
+ const unstorable = (sql, collection, key) => sql.onDialectOrElse({
3281
+ mysql: () => Option.orElse(tooLong("collection", collection, 64), () => tooLong("row_key", key, 192)),
3282
+ pg: () => Option.orElse(hasNul("collection", collection), () => hasNul("row_key", key)),
3283
+ orElse: () => Option.none()
3284
+ });
3285
+ /** The store over the storage owner's SQL client. Statements are unchanged per dialect. */
3286
+ const sqlStore = (sql) => ({
3287
+ writer: (id) => Effect.flatMap(Effect.serviceOption(sql.transactionService), (transaction) => Option.isSome(transaction) ? Effect.void : Effect.fail(new ProjectionFault({
3288
+ phase: "process",
3289
+ reason: "unsupported-composition",
3290
+ message: `The SqlClient for the rows of ${id} has no open transaction. Use the storage owner's client inside its transaction.`
3291
+ }))),
3292
+ head: (id, locked) => Effect.map(sql`SELECT applied_offset, epoch, snapshot_open FROM streamsy_state_heads WHERE stream_id = ${id} ${locked ? lockHead(sql) : sql``}`, Array.head),
3293
+ saveHead: (id, head) => Effect.asVoid(saveHead(sql, id, head)),
3294
+ deleteHead: (id) => Effect.asVoid(sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`),
3295
+ clearRows: (id) => Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}`),
3296
+ deleteBefore: (id, epoch) => Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id} AND epoch < ${epoch}`),
3297
+ upsertRow: (id, row, epoch) => Effect.asVoid(upsertRow(sql, id, row, epoch)),
3298
+ deleteRow: (id, collection, key) => Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}
3299
+ AND collection = ${collection} AND row_key = ${key}`),
3300
+ value: (id, collection, key) => Effect.map(sql`SELECT value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND row_key = ${key}`, (rows) => Option.map(Array.head(rows), (row) => row.value)),
3301
+ values: Effect.fn("StateTable.storedValues")(function* (id, collection, keys) {
3302
+ const values = /* @__PURE__ */ new Map();
3303
+ for (const chunk of Array.chunksOf(keys, 50)) {
3304
+ const found = yield* sql`SELECT row_key, value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND ${sql.in("row_key", chunk)}`;
3305
+ for (const row of found) values.set(row.row_key, row.value);
3306
+ }
3307
+ return values;
3308
+ }),
3309
+ list: (id, collection, options) => sql`SELECT row_key, value FROM streamsy_state_rows
3310
+ WHERE stream_id = ${id} AND collection = ${collection}
3311
+ ${options.after === void 0 ? sql`` : sql`AND row_key > ${options.after}`}
3312
+ ORDER BY row_key ${options.limit === void 0 ? sql`` : sql`LIMIT ${options.limit}`}`,
3313
+ unstorable: (collection, key) => unstorable(sql, collection, key)
3314
+ });
3315
+ // src/state-table-backend.ts
3316
+ const BackendTypeId = Symbol("@streamsy/projection/StateTableBackend");
3317
+ /** Private: tests read a memory store's committed rows through it. */
3318
+ const BackendStore = Symbol.for("@streamsy/projection/internal/StateTableStore");
3319
+ var BackendService = class {
3320
+ [BackendTypeId] = true;
3321
+ [BackendStore];
3322
+ constructor(store) {
3323
+ this[BackendStore] = store;
3324
+ }
3325
+ };
3326
+ /** Host-selected row storage for StateTable and FoldByKey. */
3327
+ var StateTableBackend = class extends Context.Service()("@streamsy/projection/StateTableBackend") {
3328
+ /** Keep rows in the host database. Run StateTable.migrate with the same client. */
3329
+ static layerSql = Layer.effect(this, Effect.map(SqlClient.SqlClient, (sql) => new BackendService(sqlStore(sql))));
3330
+ /**
3331
+ * Keep rows in the heap and join the memory owner's transaction. Every layer over one
3332
+ * owner shares its rows. A read outside a unit, or on a fiber that the unit forked,
3333
+ * sees committed rows only.
3334
+ */
3335
+ static layerMemory = Layer.effect(this, Effect.map(CommitBoundary, (boundary) => new BackendService(memoryStore(ownerOf(boundary)))));
3336
+ };
3337
+ /** The store of the host's backend. */
3338
+ const currentStore = Effect.flatMap(StateTableBackend, (service) => service instanceof BackendService ? Effect.succeed(service[BackendStore]) : Effect.die(/* @__PURE__ */ new TypeError("Expected a StateTable backend service")));
2829
3339
  // src/state-table.ts
2830
3340
  var state_table_exports = /* @__PURE__ */ __exportAll({
2831
3341
  clear: () => clear,
2832
3342
  define: () => define,
2833
3343
  migrate: () => migrate,
2834
3344
  rebuild: () => rebuild,
2835
- reset: () => reset
3345
+ reset: () => reset,
3346
+ unit: () => unit
2836
3347
  });
2837
3348
  const empty = {
2838
3349
  applied_offset: ZERO_OFFSET,
2839
3350
  epoch: 0,
2840
3351
  snapshot_open: 0
2841
3352
  };
2842
- const head = (sql, id) => Effect.map(sql`SELECT applied_offset, epoch, snapshot_open FROM streamsy_state_heads WHERE stream_id = ${id}`, Array.head);
2843
3353
  /** The offset that the rows reflect. A table with no head has no rows. */
2844
- const appliedOffset = (sql, id) => Effect.map(head(sql, id), (stored) => Option.getOrElse(stored, () => empty).applied_offset);
2845
- const clearRows = (sql, id) => sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}`;
2846
- const save = (sql, id, state) => sql`INSERT INTO streamsy_state_heads (stream_id, applied_offset, epoch, snapshot_open)
2847
- VALUES (${id}, ${state.applied_offset}, ${state.epoch}, ${state.snapshot_open})
2848
- ON CONFLICT (stream_id) DO UPDATE SET applied_offset = excluded.applied_offset,
2849
- epoch = excluded.epoch, snapshot_open = excluded.snapshot_open`;
3354
+ const appliedOffset = (store, id) => Effect.map(store.head(id, false), (stored) => Option.getOrElse(stored, () => empty).applied_offset);
2850
3355
  const sqlFault = (id) => (cause) => new ProjectionFault({
2851
3356
  phase: "process",
2852
3357
  reason: "storage-failure",
2853
3358
  message: `Cannot update the rows of ${id}`,
2854
3359
  cause
2855
3360
  });
2856
- /** Statements of a client without an open transaction would outlive a rolled-back unit. */
2857
- const transactionClient = (id) => Effect.gen(function* () {
2858
- const sql = yield* SqlClient.SqlClient;
2859
- if (Option.isNone(yield* Effect.serviceOption(sql.transactionService))) return yield* new ProjectionFault({
2860
- phase: "process",
2861
- reason: "unsupported-composition",
2862
- message: `The SqlClient for the rows of ${id} has no open transaction. Use the storage owner's client inside its transaction.`
2863
- });
2864
- return sql;
3361
+ /** Writes outside the storage owner's transaction would outlive a rolled-back unit. */
3362
+ const writer = (id) => Effect.gen(function* () {
3363
+ const store = yield* currentStore;
3364
+ yield* store.writer(id);
3365
+ return store;
2865
3366
  });
2866
- const apply = Effect.fn("StateTable.apply")(function* (sql, id, before, items) {
3367
+ const apply = Effect.fn("StateTable.apply")(function* (store, id, before, items) {
2867
3368
  let epoch = before.epoch;
2868
3369
  let open = before.snapshot_open;
2869
3370
  for (const item of items) yield* Change.$match(yield* message(item), {
2870
3371
  Control: ({ control }) => {
2871
3372
  if (control === "reset") {
2872
3373
  open = 0;
2873
- return Effect.asVoid(clearRows(sql, id));
3374
+ return store.clearRows(id);
2874
3375
  }
2875
3376
  if (control === "snapshot-start") {
2876
3377
  epoch += 1;
@@ -2879,51 +3380,37 @@ const apply = Effect.fn("StateTable.apply")(function* (sql, id, before, items) {
2879
3380
  }
2880
3381
  if (open === 0) return Effect.void;
2881
3382
  open = 0;
2882
- return Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id} AND epoch < ${epoch}`);
3383
+ return store.deleteBefore(id, epoch);
2883
3384
  },
2884
- Upsert: ({ collection, key, value }) => Effect.asVoid(sql`INSERT INTO streamsy_state_rows (stream_id, collection, row_key, value, epoch)
2885
- VALUES (${id}, ${collection}, ${key}, ${value}, ${epoch})
2886
- ON CONFLICT (stream_id, collection, row_key) DO UPDATE SET value = excluded.value, epoch = excluded.epoch`),
2887
- Delete: ({ collection, key }) => Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}
2888
- AND collection = ${collection} AND row_key = ${key}`)
3385
+ Upsert: (row) => Option.match(store.unstorable(row.collection, row.key), {
3386
+ onNone: () => store.upsertRow(id, row, epoch),
3387
+ onSome: (reason) => Effect.fail(new ProjectionFault({
3388
+ phase: "process",
3389
+ reason: "invalid-record",
3390
+ message: `A stored message of ${id} has a row that the table cannot store. ${reason}`
3391
+ }))
3392
+ }),
3393
+ Delete: ({ collection, key }) => Option.isSome(store.unstorable(collection, key)) ? Effect.void : store.deleteRow(id, collection, key)
2889
3394
  });
2890
3395
  return {
2891
3396
  epoch,
2892
3397
  snapshot_open: open
2893
3398
  };
2894
- }, (effect, _sql, id) => Effect.catchTag(effect, "SchemaError", (cause) => new ProjectionFault({
3399
+ }, (effect, _store, id) => Effect.catchTag(effect, "SchemaError", (cause) => new ProjectionFault({
2895
3400
  phase: "process",
2896
3401
  reason: "invalid-record",
2897
3402
  message: `A stored message of ${id} is not a State message`,
2898
3403
  cause
2899
3404
  })));
2900
- /** Create the SQLite row index at host startup, outside storage migrations. */
3405
+ /**
3406
+ * Create the row index on SQLite, Postgres or MySQL at host startup, outside storage
3407
+ * migrations. A host with `StateTableBackend.layerSql` runs it with the same client.
3408
+ */
2901
3409
  const migrate = Effect.fn("StateTable.migrate")(function* (sql) {
2902
- yield* sql.onDialectOrElse({
2903
- sqlite: () => Effect.void,
2904
- orElse: () => Effect.fail(new ProjectionFault({
2905
- phase: "load",
2906
- reason: "unsupported-composition",
2907
- message: "StateTable requires SQLite"
2908
- }))
2909
- });
2910
- yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_heads (
2911
- stream_id TEXT PRIMARY KEY,
2912
- applied_offset TEXT NOT NULL,
2913
- epoch INTEGER NOT NULL DEFAULT 0,
2914
- snapshot_open INTEGER NOT NULL DEFAULT 0
2915
- ) WITHOUT ROWID`;
2916
- yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_rows (
2917
- stream_id TEXT NOT NULL,
2918
- collection TEXT NOT NULL,
2919
- row_key TEXT NOT NULL,
2920
- value TEXT NOT NULL,
2921
- epoch INTEGER NOT NULL DEFAULT 0,
2922
- PRIMARY KEY (stream_id, collection, row_key)
2923
- ) WITHOUT ROWID`;
3410
+ yield* createTables(sql);
2924
3411
  });
2925
3412
  const synchronize = (address) => Effect.gen(function* () {
2926
- const sql = yield* transactionClient(address.id);
3413
+ const store = yield* writer(address.id);
2927
3414
  const { wire } = yield* address.stream;
2928
3415
  const unavailable = () => new ProjectionFault({
2929
3416
  phase: "read",
@@ -2936,7 +3423,7 @@ const synchronize = (address) => Effect.gen(function* () {
2936
3423
  message: `Cannot read ${address.id}`,
2937
3424
  cause
2938
3425
  });
2939
- const stored = yield* head(sql, address.id);
3426
+ const stored = yield* store.head(address.id, true);
2940
3427
  const tail = yield* wire.head(address.id).pipe(Effect.catchTags({
2941
3428
  StreamNotFound: unavailable,
2942
3429
  StreamGone: unavailable,
@@ -2945,7 +3432,7 @@ const synchronize = (address) => Effect.gen(function* () {
2945
3432
  }));
2946
3433
  let state = Option.getOrElse(stored, () => empty);
2947
3434
  if (Option.isNone(stored) || compare(state.applied_offset, tail.nextOffset) > 0) {
2948
- yield* clearRows(sql, address.id);
3435
+ yield* store.clearRows(address.id);
2949
3436
  state = empty;
2950
3437
  }
2951
3438
  while (compare(state.applied_offset, tail.nextOffset) < 0) {
@@ -2963,19 +3450,19 @@ const synchronize = (address) => Effect.gen(function* () {
2963
3450
  }));
2964
3451
  if (compare(page.nextOffset, state.applied_offset) <= 0) return yield* unavailable();
2965
3452
  state = {
2966
- ...yield* apply(sql, address.id, state, Array.map(page.messages, (item) => new TextDecoder().decode(item.data))),
3453
+ ...yield* apply(store, address.id, state, Array.map(page.messages, (item) => new TextDecoder().decode(item.data))),
2967
3454
  applied_offset: page.nextOffset
2968
3455
  };
2969
3456
  }
2970
- return yield* save(sql, address.id, state);
3457
+ return yield* store.saveHead(address.id, state);
2971
3458
  }).pipe(Effect.catchTag("SqlError", sqlFault(address.id)), Effect.asVoid, Effect.withSpan("StateTable.sync"));
2972
3459
  const applySlice = (address, slice) => Effect.gen(function* () {
2973
- const sql = yield* transactionClient(address.id);
2974
- const stored = yield* head(sql, address.id);
3460
+ const store = yield* writer(address.id);
3461
+ const stored = yield* store.head(address.id, true);
2975
3462
  if (Option.isSome(stored) && stored.value.applied_offset === slice.from || Option.isNone(stored) && slice.from === ZERO_OFFSET) {
2976
- if (Option.isNone(stored)) yield* clearRows(sql, address.id);
2977
- const next = yield* apply(sql, address.id, Option.getOrElse(stored, () => empty), slice.items);
2978
- yield* save(sql, address.id, {
3463
+ if (Option.isNone(stored)) yield* store.clearRows(address.id);
3464
+ const next = yield* apply(store, address.id, Option.getOrElse(stored, () => empty), slice.items);
3465
+ yield* store.saveHead(address.id, {
2979
3466
  ...next,
2980
3467
  applied_offset: slice.nextOffset
2981
3468
  });
@@ -2989,22 +3476,22 @@ const reads = (id, collections) => {
2989
3476
  };
2990
3477
  return {
2991
3478
  offset: Effect.fn("StateTable.offset")(function* () {
2992
- return yield* appliedOffset(yield* SqlClient.SqlClient, id);
3479
+ return yield* appliedOffset(yield* currentStore, id);
2993
3480
  }),
2994
3481
  get: Effect.fn("StateTable.get")(function* (collection, key) {
2995
- const sql = yield* SqlClient.SqlClient;
2996
- const offset = yield* appliedOffset(sql, id);
2997
- const row = (yield* sql`SELECT value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND row_key = ${key}`)[0];
3482
+ const store = yield* currentStore;
3483
+ const offset = yield* appliedOffset(store, id);
3484
+ const row = Option.isSome(store.unstorable(collection, key)) ? Option.none() : yield* store.value(id, collection, key);
2998
3485
  return {
2999
3486
  offset,
3000
- value: row === void 0 ? void 0 : yield* readValue(collection, row.value)
3487
+ value: Option.isNone(row) ? void 0 : yield* readValue(collection, row.value)
3001
3488
  };
3002
3489
  }),
3003
3490
  getMany: Effect.fn("StateTable.getMany")(function* (collection, keys) {
3004
- const sql = yield* SqlClient.SqlClient;
3005
- const offset = yield* appliedOffset(sql, id);
3491
+ const store = yield* currentStore;
3492
+ const offset = yield* appliedOffset(store, id);
3006
3493
  const rows = /* @__PURE__ */ new Map();
3007
- for (const [key, value] of yield* storedValues(sql, id, collection, keys)) rows.set(key, yield* readValue(collection, value));
3494
+ for (const [key, value] of yield* storedValues(store, id, collection, keys)) rows.set(key, yield* readValue(collection, value));
3008
3495
  return {
3009
3496
  offset,
3010
3497
  rows
@@ -3016,12 +3503,9 @@ const reads = (id, collections) => {
3016
3503
  reason: "invalid-options",
3017
3504
  message: "StateTable list limit must be a positive safe integer"
3018
3505
  });
3019
- const sql = yield* SqlClient.SqlClient;
3020
- const offset = yield* appliedOffset(sql, id);
3021
- const found = yield* sql`SELECT row_key, value FROM streamsy_state_rows
3022
- WHERE stream_id = ${id} AND collection = ${collection}
3023
- ${options.after === void 0 ? sql`` : sql`AND row_key > ${options.after}`}
3024
- ORDER BY row_key ${options.limit === void 0 ? sql`` : sql`LIMIT ${options.limit}`}`;
3506
+ const store = yield* currentStore;
3507
+ const offset = yield* appliedOffset(store, id);
3508
+ const found = yield* store.list(id, collection, options);
3025
3509
  const rows = yield* Effect.forEach(found, (row) => Effect.map(readValue(collection, row.value), (value) => ({
3026
3510
  key: row.row_key,
3027
3511
  value
@@ -3034,11 +3518,18 @@ const reads = (id, collections) => {
3034
3518
  })
3035
3519
  };
3036
3520
  };
3521
+ /** The collections of a bound table, for `unit`. */
3522
+ const TableCollections = Symbol.for("@streamsy/projection/internal/StateTableCollections");
3037
3523
  /** A State stream's declaration, kept current by the ordinary projection runners. */
3038
3524
  function define(state, options = {}) {
3039
3525
  const id = `state-table/${state.key}`;
3040
3526
  rejectProjectionVersion(id, options);
3041
- validateAccepted(options.accepted, state.paramCodecs, [state.template], transaction);
3527
+ rejectAccepted(id, options);
3528
+ validateFrontier(options.frontier, {
3529
+ commit: transaction,
3530
+ params: state.paramCodecs,
3531
+ inputTemplates: [state.template]
3532
+ });
3042
3533
  const declaration = declare({
3043
3534
  id,
3044
3535
  params: state.paramCodecs,
@@ -3049,9 +3540,10 @@ function define(state, options = {}) {
3049
3540
  stream: address.stream,
3050
3541
  codec: Schema.String
3051
3542
  });
3052
- const accepted = options.accepted?.at(decoded);
3053
- if (accepted?.id === address.id) throw new RangeError("An accepted stream may not name an input stream");
3054
- return {
3543
+ Object.defineProperty(raw, RawCollections, { value: state.collections });
3544
+ const accepted = options.frontier?.at(decoded);
3545
+ if (accepted?.id === address.id) throw new RangeError("A frontier stream may not name an input stream");
3546
+ const bound = {
3055
3547
  ...key,
3056
3548
  accepted,
3057
3549
  inputs: { state: raw },
@@ -3060,6 +3552,7 @@ function define(state, options = {}) {
3060
3552
  ...reads(address.id, state.collections),
3061
3553
  sync: () => synchronize(raw)
3062
3554
  };
3555
+ return Object.defineProperty(bound, TableCollections, { value: state.collections });
3063
3556
  });
3064
3557
  return Object.assign(declaration, {
3065
3558
  inputs: { state },
@@ -3067,9 +3560,9 @@ function define(state, options = {}) {
3067
3560
  });
3068
3561
  }
3069
3562
  const clearIndex = (id) => Effect.gen(function* () {
3070
- const sql = yield* transactionClient(id);
3071
- yield* clearRows(sql, id);
3072
- yield* sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`;
3563
+ const store = yield* writer(id);
3564
+ yield* store.clearRows(id);
3565
+ yield* store.deleteHead(id);
3073
3566
  }).pipe(Effect.catchTag("SqlError", sqlFault(id)));
3074
3567
  /** Delete cached rows and their applied offset, even if the State stream has been removed. */
3075
3568
  const clear = Effect.fn("StateTable.clear")(function* (table) {
@@ -3086,6 +3579,82 @@ const reset = Effect.fn("StateTable.reset")(function* (table) {
3086
3579
  const state = StreamAddress.state(address.id, { collections: {} });
3087
3580
  return yield* Streams.append(state, [StreamAddress.reset()]).pipe(Effect.provideService(StreamsWriter, wire));
3088
3581
  });
3582
+ const unitFault = (reason, text) => (cause) => new ProjectionFault({
3583
+ phase: "process",
3584
+ reason,
3585
+ message: text,
3586
+ cause
3587
+ });
3588
+ /** The unit's map key for one row. */
3589
+ const rowId = (collection, key) => `${collection}\u0000${key}`;
3590
+ const isBoundTable = (table) => Predicate.hasProperty(table, TableCollections);
3591
+ /**
3592
+ * Create a missing unwrapped output, call `sync`, and open the unit's rows. Call it once
3593
+ * for each unit, inside a `Commit.transaction` handler, and return `changes()`.
3594
+ */
3595
+ const unit = Effect.fn("StateTable.unit")(function* (table) {
3596
+ if (!isBoundTable(table)) return yield* Effect.die(/* @__PURE__ */ new RangeError("StateTable.unit requires a table from define"));
3597
+ const collections = table[TableCollections];
3598
+ const address = table.inputs.state;
3599
+ const id = address.id;
3600
+ const store = yield* writer(id);
3601
+ const { wire } = yield* address.stream;
3602
+ const managed = yield* TransactionGenerationOutputs;
3603
+ const generationBound = managed !== void 0 && Array.some([...managed.values()], (output) => output.address.id === id);
3604
+ if (!generationBound) yield* wire.create(id, { contentType: address.contentType }).pipe(Effect.mapError((cause) => unitFault(isStreamsFault(cause) ? "storage-failure" : Predicate.isTagged(cause, "StreamBusy") ? "output-busy" : "invalid-output", `Cannot write output ${id}`)(cause)));
3605
+ yield* table.sync().pipe(Effect.mapError((cause) => generationBound && cause.reason === "history-unavailable" ? unitFault("invalid-output", `Cannot write output ${id}`)(cause) : cause));
3606
+ const known = /* @__PURE__ */ new Map();
3607
+ const entries = [];
3608
+ const collectionOf = (collection) => {
3609
+ const entry = collections[collection];
3610
+ if (entry === void 0) throw new RangeError(`Unknown State collection ${collection}`);
3611
+ return entry;
3612
+ };
3613
+ const read = (collection, keys) => storedValues(store, id, collection, keys).pipe(Effect.mapError(unitFault("storage-failure", `Cannot read the rows of ${id}`)), Effect.map((found) => {
3614
+ for (const key of keys) known.set(rowId(collection, key), { json: found.get(key) });
3615
+ }));
3616
+ const current = (collection, key) => Effect.gen(function* () {
3617
+ const found = known.get(rowId(collection, key));
3618
+ if (found !== void 0) return found;
3619
+ yield* read(collection, [key]);
3620
+ return known.get(rowId(collection, key)) ?? { json: void 0 };
3621
+ });
3622
+ return {
3623
+ load: (collection, keys) => Effect.suspend(() => {
3624
+ const missing = Array.filter([...new Set(keys)], (key) => !known.has(rowId(collection, key)));
3625
+ return missing.length === 0 ? Effect.void : read(collection, missing);
3626
+ }),
3627
+ get: (collection, key) => Effect.gen(function* () {
3628
+ const schema = collectionOf(collection).schema;
3629
+ const found = yield* current(collection, key);
3630
+ if (found.json === void 0) return void 0;
3631
+ if (!("value" in found)) found.value = yield* decodeRow(schema, found.json).pipe(Effect.mapError(unitFault("invalid-record", `Row ${key} of ${id} does not decode`)));
3632
+ return found.value;
3633
+ }),
3634
+ upsert: (collection, row, options = {}) => Effect.gen(function* () {
3635
+ const entry = collectionOf(collection);
3636
+ const schema = entry.schema;
3637
+ const field = entry.key;
3638
+ const key = Predicate.hasProperty(row, field) ? String(row[field]) : "undefined";
3639
+ const before = yield* current(collection, key);
3640
+ const after = yield* encodeRow(schema, row).pipe(Effect.mapError(unitFault("invalid-output", `Cannot encode row ${key} of ${id}`)));
3641
+ if (after === before.json) return false;
3642
+ known.set(rowId(collection, key), {
3643
+ json: after,
3644
+ value: row
3645
+ });
3646
+ entries.push(DurableState.upsert(collection, row, options));
3647
+ return true;
3648
+ }),
3649
+ remove: (collection, key, options = {}) => Effect.gen(function* () {
3650
+ if ((yield* current(collection, key)).json === void 0) return false;
3651
+ known.set(rowId(collection, key), { json: void 0 });
3652
+ entries.push(DurableState.remove(collection, key, options));
3653
+ return true;
3654
+ }),
3655
+ changes: () => [...entries]
3656
+ };
3657
+ });
3089
3658
  // src/fold-by-key-error.ts
3090
3659
  /** A folded row disagreed with the key that was used to load its previous row. */
3091
3660
  var FoldByKeyError = class extends Schema.TaggedError()("FoldByKeyError", { message: Schema.String }) {};
@@ -3121,7 +3690,8 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
3121
3690
  if (group === void 0) groups.set(key, [record]);
3122
3691
  else group.push(record);
3123
3692
  }
3124
- const stored = yield* storedValues(yield* SqlClient.SqlClient, output.id, spec.collection, [...groups.keys()]).pipe(Effect.mapError(fault("storage-failure", `Cannot read the rows of ${output.id}`)));
3693
+ const store = yield* currentStore;
3694
+ const stored = yield* storedValues(store, output.id, spec.collection, [...groups.keys()]).pipe(Effect.mapError(fault("storage-failure", `Cannot read the rows of ${output.id}`)));
3125
3695
  const schema = collection.schema;
3126
3696
  const changes = [];
3127
3697
  for (const [key, records] of groups) {
@@ -3139,6 +3709,12 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
3139
3709
  const field = collection.key;
3140
3710
  const actual = Predicate.hasProperty(value, field) ? String(value[field]) : "undefined";
3141
3711
  if (actual !== key) return yield* new FoldByKeyError({ message: `FoldByKey key "${key}" differs from folded row key "${actual}"` });
3712
+ const rejected = store.unstorable(spec.collection, key);
3713
+ if (Option.isSome(rejected)) return yield* new ProjectionFault({
3714
+ phase: "process",
3715
+ reason: "invalid-output",
3716
+ message: `Cannot write a row of ${output.id}. ${rejected.value}`
3717
+ });
3142
3718
  const after = yield* encodeRow(schema, value).pipe(Effect.mapError(fault("invalid-output", `Cannot encode row ${key} of ${output.id}`)));
3143
3719
  if (after !== before) changes.push(upsertJson(spec.collection, key, after));
3144
3720
  }
@@ -3230,4 +3806,4 @@ const attach = (projection, options = {}) => {
3230
3806
  });
3231
3807
  };
3232
3808
  const ProjectionWakeup = { attach };
3233
- export { CheckpointRecord, CheckpointStore, commit_exports as Commit, fold_by_key_exports as FoldByKey, FoldByKeyError, HandlerFailed, InvalidBinding, NonRetryable, NotAttached, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, RunnerEvent, state_table_exports as StateTable, Transaction };
3809
+ 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, StateTableBackend, Transaction, isFrontierCollection, unitFrontiers, validateFrontier };