@streamsy/projection 0.12.0 → 0.14.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/README.md CHANGED
@@ -60,16 +60,17 @@ await Effect.runPromise(program.pipe(Effect.provide(host)));
60
60
 
61
61
  ## Commits
62
62
 
63
- | Commit | Fits | Guarantee | Services |
64
- | ------------- | ----------------------------------- | -------------------------------- | -------------------------------- |
65
- | `checkpoint` | `fold` | Exactly once for the saved value | `CheckpointStore` |
66
- | `transaction` | All constructors | Exactly once within SQL | `CheckpointStore`, `Transaction` |
67
- | `producer` | `emit`, `mapAccum`, `mapAccumBatch` | Effectively once for outputs | `CheckpointStore`, output routes |
68
- | `atLeastOnce` | `process` | At least once | `CheckpointStore` |
69
-
70
- `Commit.transaction` provides `SqlClient`. Its SQL, same-owner stream appends,
71
- and checkpoint commit together. External calls are at least once. Memory hosts
72
- provide no `Transaction`.
63
+ | Commit | Fits | Guarantee | Services |
64
+ | ------------- | ----------------------------------- | ----------------------------------------- | -------------------------------- |
65
+ | `checkpoint` | `fold` | Exactly once for the saved value | `CheckpointStore` |
66
+ | `transaction` | All constructors | Exactly once within the owner transaction | `CheckpointStore`, `Transaction` |
67
+ | `producer` | `emit`, `mapAccum`, `mapAccumBatch` | Effectively once for outputs | `CheckpointStore`, output routes |
68
+ | `atLeastOnce` | `process` | At least once | `CheckpointStore` |
69
+
70
+ `Commit.transaction` commits the unit and checkpoint together on a memory or
71
+ SQL storage host. Checkpoints and stream writes must share the transaction owner.
72
+ A SQL handler reads the storage owner’s `SqlClient` from context to join the
73
+ transaction. External calls are at least once.
73
74
 
74
75
  `Commit.producer` pins ranges and producer sequences. Retries append with the
75
76
  same positions; handlers must be deterministic. A missing output on the
@@ -78,10 +79,18 @@ must already exist: its owner creates it at start. There is no atomicity
78
79
  across producer outputs. Chain projections for sinks with different guarantees.
79
80
 
80
81
  `Commit.atLeastOnce` pins before processing, so retries keep `unit.key`.
81
- `Projection.process` with `Commit.transaction` can use `prepare(batch, unit)`
82
- outside the transaction. It runs at least once and passes its result to
82
+ `Projection.process` with `Commit.transaction` can
83
+ use `prepare(batch, unit)` outside the transaction. It runs at least once and passes its result to
83
84
  `process`. A retry can read new input and change `unit.key`.
84
85
 
86
+ `Commit.transactionWithCleanup((key) => cleanup)` passes the binding’s
87
+ checkpoint key to the cleanup Effect. The Effect reads its services from context.
88
+ `Projection.forget` runs cleanup after removing the checkpoint and marking any
89
+ route records forgotten. Pass the bound declaration for a routed binding.
90
+ `Projection.retire` runs it after the tombstone write and owned output cleanup.
91
+ The callback also runs on a repeated retirement. A cleanup failure rolls back
92
+ changes in the same transaction, including SQL run with the storage owner’s client.
93
+
85
94
  `Commit.withCompensation(f)` calls `f(result, cause, unit)` after successful
86
95
  processing if the commit fails. It is also available as a `.pipe` combinator.
87
96
  For external delivery, use `Commit.atLeastOnce` with `unit.key` as the idempotency key,
@@ -89,6 +98,11 @@ the declaration's [binding retry policy](https://streamsy.dev/docs/reference/pro
89
98
  for a retry budget and `onExhausted`, and [`Projection.wakeAt`](https://streamsy.dev/docs/projections/process#timers)
90
99
  for a deferred retry or a snooze. See the [effects guide](https://streamsy.dev/docs/projections/effects) for the complete pattern.
91
100
 
101
+ To stop a binding on a permanent typed handler error, add
102
+ `readonly [NonRetryable] = true` using `NonRetryable` from `@streamsy/projection`.
103
+ Attached runners report the failure without stepping the retry schedule or
104
+ calling `onExhausted`.
105
+
92
106
  `Commit.make` defines `load`, `apply`, and optional `remove`. Custom Commits
93
107
  extend ranges on retry. Never save after a failed handler; compare-and-set on
94
108
  `loaded.token`; report `checkpoint / token-conflict` for a moved token; return
@@ -129,12 +143,13 @@ collection. Two outputs cannot name the same stream or an input.
129
143
  a declaration and a bound table are `StateTable.Declaration` and
130
144
  `StateTable.Bound`.
131
145
 
132
- `FoldByKey.process(table, spec)` builds a `Projection.process` handler, under
133
- `Commit.transaction` with the State stream in `outputs`, that folds records into
134
- one collection. It reads each key's previous row from the table. `sync` and the
135
- fold handler fail with `ProjectionFault` for every wire, SQL and schema failure,
136
- and the handler adds `FoldByKeyError` for a row with the wrong key. A fold's `id`,
137
- `version` and `generation` are its identity, so a rename is a fold fix. See
146
+ `FoldByKey.process(table, spec)` builds a `Projection.process` handler on a SQL
147
+ host. Put the State stream in `outputs` to fold records into one collection. Use
148
+ `Commit.transaction` and provide the storage owner’s `SqlClient` to the runner.
149
+ The fold reads each key’s previous row from the table. `sync` and the fold handler
150
+ fail with `ProjectionFault` for every wire, SQL and schema failure,
151
+ and the handler adds `FoldByKeyError` for a row with the wrong key. A fold's
152
+ identity includes its `id`, `generation` and binding params. See
138
153
  [State tables](https://streamsy.dev/docs/projections/state-table).
139
154
 
140
155
  ## Wake streams
@@ -194,21 +209,21 @@ available to the normal retry policy.
194
209
  A pending unit replays its pinned input ranges. If the input is removed
195
210
  between the pin and the settle, the replay fails with `range-unreproducible`
196
211
  and the pin stays. The final gone unit does not run for that binding. Keep
197
- source history until pending units settle, or call `Projection.forget` on the
198
- binding after you clean up its outputs.
212
+ source history until pending units settle, or call `Projection.forget(bound)`
213
+ to discard its progress.
199
214
 
200
215
  ## Hosts
201
216
 
202
217
  | Layer | Provides | Requires |
203
218
  | ----------------------------- | ---------------------------- | ------------------------------- |
204
219
  | `CheckpointStore.layer` | `CheckpointStore` | `CommitBoundary`, owner records |
205
- | `Transaction.layer` | `Transaction` | `CommitBoundary`, `SqlClient` |
220
+ | `Transaction.layer` | `Transaction` | `CommitBoundary` |
206
221
  | `CheckpointStore.layerMemory` | Standalone `CheckpointStore` | Nothing |
207
222
 
208
223
  `CheckpointStore.layer` keeps checkpoints on the owner of the streams. It works
209
224
  over every Streamsy storage host: `MemoryStorage.layer`, `BunStorage.layer`, and
210
- `DurableObjectStorage.layer`. Add `Transaction.layer` on a SQL host for
211
- `Commit.transaction`. Compose the projection Layers over storage with
225
+ `DurableObjectStorage.layer`. Add `Transaction.layer` over the same storage host for `Commit.transaction`.
226
+ Compose the projection Layers over storage with
212
227
  `Layer.provideMerge` and retain one Layer graph for the host lifetime:
213
228
 
214
229
  ```ts
@@ -308,8 +323,8 @@ units within that binding run in order.
308
323
 
309
324
  Keep `concurrency` below the pool size: each `Commit.transaction` unit holds one
310
325
  pooled connection for its whole handler. Both server drivers default to 10 connections;
311
- leave a connection for reads, appends and runner storage operations. Inside the handler, run all SQL on the
312
- provided `SqlClient` in the handler's fiber. `sql.reserve` or a fiber without the
326
+ leave a connection for reads, appends and runner storage operations. Inside the handler, run all SQL on the storage
327
+ owner’s `SqlClient` in the handler's fiber. `sql.reserve` or a fiber without the
313
328
  handler's transaction context waits forever on SQLite, and on a pool once every
314
329
  connection holds a transaction. Appending to a shared output last keeps its row
315
330
  lock short: units serialize from that append until commit. Units that lock streams
@@ -351,7 +366,7 @@ processing finishes. `registry.retry(target)` makes failed work due now.
351
366
 
352
367
  After a fold fix, `registry.rescan(projectionOrId, WakeClassOrStreamId)` resets one
353
368
  trigger cursor to `ZERO_OFFSET`, clears its stop and wakes the runner. It does not
354
- reset binding checkpoints; use the appropriate version or generation for the fix.
369
+ reset binding checkpoints. Raise `generation` to replay those bindings.
355
370
  A row that still fails to decode stops that stream again. The cursor is stored in
356
371
  both durability modes and survives restart; ingested marks survive only in durable
357
372
  mode. An unknown projection fails with `NotAttached`; an unknown trigger dies with
@@ -429,11 +444,31 @@ projections are follow-only; wait on their output to see a command.
429
444
  backoff from 200 ms, capped at 30 s. `run` does not retry. Handler errors retain
430
445
  their types; `ProjectionFault` carries `phase`, `reason`, and `cause`.
431
446
 
432
- Records are keyed by `id`, `version`, `generation`, and canonical parameters.
433
- Use a new generation for changed input identity or state schema. Retain input
434
- history after the checkpoint, including pinned ranges. Stop the follower first, or use a new generation before
435
- `Projection.forget(bound)`, which calls the Commit's `remove`. For producer
436
- outputs, delete output streams first or use a new generation.
447
+ Records are keyed by `id`, `generation` and canonical parameters.
448
+ Raise `generation` to start over, including after a change to input identity or
449
+ state schema. A new generation replays into fresh `perGeneration` streams.
450
+ Unwrapped outputs with `Commit.producer` or `Commit.transaction` receive the
451
+ replay after their existing items. To start with an empty output, choose a fresh
452
+ address or remove the stream before you start the upgraded process. Attach can
453
+ start replay at startup. [Checkpoints and generations](https://streamsy.dev/docs/projections/checkpoints#generations)
454
+
455
+ Delete an explicit `version: 1`. If a binding used a different `version`, stop
456
+ the old runners and keep the full input history for the new generation. The
457
+ migration guide covers reader cutover and retirement. [Migrate a declaration that set `version`](https://streamsy.dev/docs/projections/checkpoints#migrate-a-declaration-that-set-version)
458
+
459
+ Stop and drain the binding's runners before calling `Projection.forget(bound)`
460
+ to discard progress. Forget keeps the streams. For a routed binding, pass the
461
+ value returned by `declaration.at(params)` so `forget` marks its route records.
462
+ Passing a bare key leaves them live and allows a replay to append to old data.
463
+ Use a store that supports owner-record listing for routed forget on an existing
464
+ checkpoint, including automatic forget after a gone input.
465
+ With a transaction Commit, forgetting an absent checkpoint fails with a retryable
466
+ `token-conflict` if another host commits the binding's first unit meanwhile.
467
+
468
+ `Projection.retire` writes a tombstone even if the checkpoint cannot be decoded.
469
+ It can remove or close owned streams after a forget when you pass the declaration
470
+ with the original routed outputs. The result has `record` and a flat `streams`
471
+ array. [Retire a generation](https://streamsy.dev/docs/projections/checkpoints#retire-a-generation)
437
472
 
438
473
  Without a follower, each `current` replays from the last checkpoint or from
439
474
  the start. A continuously growing input can delay it. Fold handlers must be
@@ -0,0 +1,459 @@
1
+ import { Array, Context, Effect, Layer, Option, Order, Record, Schema, Semaphore } from "effect";
2
+ import { CommitBoundary, ZERO_OFFSET, isStreamsFault } from "@streamsy/core";
3
+ import { OWNER_RECORDS_LIST_UNSUPPORTED, OwnerRecords, attachOwner, ownerOf } from "@streamsy/core/internal";
4
+ // src/fault.ts
5
+ /** A typed handler failure bearing this marker stops its binding without retry. */
6
+ const NonRetryable = Symbol.for("@streamsy/projection/NonRetryable");
7
+ /** No live runner for this declaration exists in the selected registry. */
8
+ var NotAttached = class extends Schema.TaggedError()("NotAttached", { projection: Schema.String }) {};
9
+ /** Encoded params do not round-trip through the attached declaration's codecs. */
10
+ var InvalidBinding = class extends Schema.TaggedError()("InvalidBinding", {
11
+ projection: Schema.String,
12
+ params: Schema.Record(Schema.String, Schema.String)
13
+ }) {};
14
+ /** Phase says where the run stopped; a `checkpoint` failure means processing already completed. */
15
+ var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
16
+ phase: Schema.Literals([
17
+ "load",
18
+ "read",
19
+ "pin",
20
+ "process",
21
+ "checkpoint"
22
+ ]),
23
+ reason: Schema.Literals([
24
+ "history-unavailable",
25
+ "identity-mismatch",
26
+ "invalid-record",
27
+ "invalid-source",
28
+ "invalid-options",
29
+ "invalid-output",
30
+ "token-conflict",
31
+ "output-busy",
32
+ "range-unreproducible",
33
+ "stale-epoch",
34
+ "retired-generation",
35
+ "storage-failure",
36
+ "unsupported-composition"
37
+ ]),
38
+ input: Schema.optionalKey(Schema.String),
39
+ message: Schema.String,
40
+ cause: Schema.optionalKey(Schema.Defect())
41
+ }) {
42
+ get retryable() {
43
+ switch (this.reason) {
44
+ case "storage-failure": return !isStreamsFault(this.cause) || this.cause.retryable;
45
+ case "token-conflict":
46
+ case "output-busy": return true;
47
+ case "history-unavailable":
48
+ case "identity-mismatch":
49
+ case "invalid-record":
50
+ case "invalid-source":
51
+ case "invalid-options":
52
+ case "invalid-output":
53
+ case "range-unreproducible":
54
+ case "stale-epoch":
55
+ case "retired-generation":
56
+ case "unsupported-composition": return false;
57
+ }
58
+ return false;
59
+ }
60
+ };
61
+ // src/unit.ts
62
+ /** Length-safe encoding of inert string components; no persistence decoding here. */
63
+ const encodeKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
64
+ const Counter = Schema.Finite.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0));
65
+ const terminal = {
66
+ closed: Schema.optionalKey(Schema.Boolean),
67
+ gone: Schema.optionalKey(Schema.Literal(true))
68
+ };
69
+ Schema.Struct({
70
+ from: Schema.String,
71
+ nextOffset: Schema.String,
72
+ ...terminal
73
+ });
74
+ /** A range with the item count a retry must reproduce exactly. */
75
+ const PinnedRange = Schema.Struct({
76
+ from: Schema.String,
77
+ nextOffset: Schema.String,
78
+ count: Counter,
79
+ upToDate: Schema.optionalKey(Schema.Boolean),
80
+ ...terminal
81
+ });
82
+ /** A unit pinned before its handler or append; settled by the next pass. */
83
+ const PendingUnit = Schema.Struct({
84
+ ranges: Schema.Record(Schema.String, PinnedRange),
85
+ /** Recorded wake time, preserved across retries. */
86
+ due: Schema.optionalKey(Counter),
87
+ seqs: Schema.optionalKey(Schema.Record(Schema.String, Counter))
88
+ });
89
+ /** Deterministic JSON: keys sorted, so equal maps always encode identically. */
90
+ const canonicalParams = (params) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(params), Order.String), (k) => [k, params[k]])));
91
+ const terminalOf = (source) => {
92
+ const keys = {};
93
+ if (source.closed === true) keys.closed = true;
94
+ if (source.gone === true) keys.gone = true;
95
+ return keys;
96
+ };
97
+ const canonicalRanges = (ranges) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(ranges), Order.String), (k) => {
98
+ const range = ranges[k];
99
+ return [k, {
100
+ from: range?.from,
101
+ nextOffset: range?.nextOffset,
102
+ ...terminalOf(range ?? {})
103
+ }];
104
+ })));
105
+ /** The key is stable across producer retries; transaction retries may read a longer tail. */
106
+ const unitOf = (projectionId, generation, params, ranges, due) => ({
107
+ projectionId,
108
+ generation,
109
+ params,
110
+ ranges,
111
+ due: Option.fromUndefinedOr(due),
112
+ key: encodeKey([
113
+ projectionId,
114
+ String(generation),
115
+ canonicalParams(params),
116
+ canonicalRanges(ranges),
117
+ ...due === void 0 ? [] : [String(due)]
118
+ ])
119
+ });
120
+ /** The handler view of a kernel unit, with the decoded params. */
121
+ const withParams = (unit, params) => ({
122
+ ...unit,
123
+ params
124
+ });
125
+ // src/checkpoint-store.ts
126
+ const CheckpointRecord = Schema.Struct({
127
+ identity: Schema.Struct({ inputs: Schema.Record(Schema.String, Schema.String) }),
128
+ /** Input key to accepted offset; the next pass reads after these. */
129
+ inputs: Schema.Record(Schema.String, Schema.String),
130
+ pending: Schema.optionalKey(PendingUnit),
131
+ /** Next process wake, in epoch milliseconds. Absent means no timer. */
132
+ wakeAt: Schema.optionalKey(Counter),
133
+ /** Inputs whose terminal close has already been processed. */
134
+ closed: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)),
135
+ /** The final gone unit committed; only forgetting remains. */
136
+ ended: Schema.optionalKey(Schema.Literal(true)),
137
+ state: Schema.optionalKey(Schema.String),
138
+ adapters: Schema.Struct({ outputs: Schema.optionalKey(Schema.Record(Schema.String, Schema.Struct({
139
+ epoch: Counter,
140
+ nextSeq: Counter
141
+ }))) })
142
+ });
143
+ /** Stored value. The version is the compare-and-set token exposed as a string. */
144
+ const Envelope = Schema.Struct({
145
+ version: Counter,
146
+ record: CheckpointRecord
147
+ });
148
+ const EnvelopeJson = Schema.fromJsonString(Envelope);
149
+ const Tombstone = Schema.Struct({
150
+ version: Counter,
151
+ retired: Schema.Struct({})
152
+ });
153
+ const TombstoneJson = Schema.fromJsonString(Tombstone);
154
+ const StoredJson = Schema.fromJsonString(Schema.Union([Envelope, Tombstone]));
155
+ const CHECKPOINT_NAMESPACE = "streamsy.projection.v1";
156
+ const STORED_VERSION_SLOT = "1";
157
+ const CheckpointKeyJson = Schema.fromJsonString(Schema.Tuple([
158
+ Schema.Literal(CHECKPOINT_NAMESPACE),
159
+ Schema.String,
160
+ Schema.String,
161
+ Schema.FiniteFromString,
162
+ Schema.fromJsonString(Schema.Record(Schema.String, Schema.String))
163
+ ]));
164
+ const assertCheckpointKeyVersion = (key) => {
165
+ if ("version" in key && key.version !== void 0 && key.version !== 1) throw new RangeError(`Projection ${key.id}: version was removed from checkpoint keys.`);
166
+ };
167
+ const keyParts = (key) => {
168
+ assertCheckpointKeyVersion(key);
169
+ return [
170
+ key.id,
171
+ STORED_VERSION_SLOT,
172
+ String(key.generation),
173
+ canonicalParams(key.params)
174
+ ];
175
+ };
176
+ const recordKey = (key) => encodeKey([CHECKPOINT_NAMESPACE, ...keyParts(key)]);
177
+ /** Token "0" means no record is stored yet. */
178
+ const ABSENT_TOKEN = "0";
179
+ const storageFailure = (phase, message) => (cause) => new ProjectionFault({
180
+ phase,
181
+ reason: "storage-failure",
182
+ message,
183
+ cause
184
+ });
185
+ /**
186
+ * SQL storage fails a write with this operation when the transaction read the key as
187
+ * absent and a concurrent save created it first. That save won the compare-and-set.
188
+ */
189
+ const OWNER_RECORD_CONFLICT = "records.conflict";
190
+ /** The load that `loadLatest` uses for a store, keyed by its `load` like the owner metadata. */
191
+ const latestLoads = /* @__PURE__ */ new WeakMap();
192
+ /** Load the latest committed record in a transaction whose snapshot can be older. */
193
+ const loadLatest = (store, key) => (latestLoads.get(store.load) ?? store.load)(key);
194
+ /** Stores each projection's offsets and encoded state in one compare-and-set record. */
195
+ var CheckpointStore = class extends Context.Service()("@streamsy/projection/CheckpointStore") {
196
+ /**
197
+ * Checkpoints on the storage owner, in its transaction. Works over every Streamsy
198
+ * storage host, so checkpoints and streams always share one owner.
199
+ */
200
+ static layer = Layer.effect(this, Effect.gen(function* () {
201
+ const boundary = yield* CommitBoundary;
202
+ const records = yield* OwnerRecords;
203
+ const checkpoints = fromStore({
204
+ list: (prefix) => records.list(prefix).pipe(Effect.mapError((cause) => new ProjectionFault({
205
+ phase: "load",
206
+ reason: cause.operation === OWNER_RECORDS_LIST_UNSUPPORTED ? "unsupported-composition" : "storage-failure",
207
+ message: cause.message,
208
+ cause
209
+ }))),
210
+ read: (key) => records.read(key).pipe(Effect.mapError(storageFailure("load", "Cannot read a checkpoint"))),
211
+ write: (key, value) => records.write(key, value).pipe(Effect.mapError((cause) => cause.operation === OWNER_RECORD_CONFLICT ? new ProjectionFault({
212
+ phase: "checkpoint",
213
+ reason: "token-conflict",
214
+ message: "A second writer on the same key likely created the checkpoint first. Use one writer per key: the follower or one run at a time.",
215
+ cause
216
+ }) : storageFailure("checkpoint", "Cannot write a checkpoint")(cause))),
217
+ remove: (key) => records.remove(key).pipe(Effect.mapError(storageFailure("checkpoint", "Cannot delete a checkpoint"))),
218
+ withTransaction: (body) => boundary.withTransaction(body).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(new ProjectionFault({
219
+ phase: "checkpoint",
220
+ reason: "storage-failure",
221
+ message: "The owner transaction failed",
222
+ cause
223
+ }))))
224
+ });
225
+ attachOwner(checkpoints.load, ownerOf(boundary));
226
+ return checkpoints;
227
+ }));
228
+ /** An independent store for rebuilt values and tests. It shares no owner with streams. */
229
+ static layerMemory = Layer.effect(this, Effect.gen(function* () {
230
+ const records = /* @__PURE__ */ new Map();
231
+ const lock = yield* Semaphore.make(1);
232
+ return fromStore({
233
+ list: (prefix) => lock.withPermits(1)(Effect.sync(() => Array.filter(Array.fromIterable(records), ([key]) => key.startsWith(prefix)))),
234
+ read: (key) => Effect.sync(() => Option.fromUndefinedOr(records.get(key))),
235
+ write: (key, value) => Effect.sync(() => {
236
+ records.set(key, value);
237
+ }),
238
+ remove: (key) => Effect.sync(() => {
239
+ records.delete(key);
240
+ }),
241
+ withTransaction: lock.withPermits(1)
242
+ });
243
+ }));
244
+ };
245
+ const decodeStored = (id, encoded) => Schema.decodeEffect(StoredJson)(encoded).pipe(Effect.mapError(() => new ProjectionFault({
246
+ phase: "load",
247
+ reason: "invalid-record",
248
+ message: `Invalid stored record for ${id}`
249
+ })));
250
+ const ROUTED_NAMESPACE = "streamsy.projection.routed.v1";
251
+ const routeKeyParts = (key) => [ROUTED_NAMESPACE, ...keyParts(key)];
252
+ const RouteKeyJson = Schema.fromJsonString(Schema.Tuple([
253
+ Schema.Literal(ROUTED_NAMESPACE),
254
+ Schema.String,
255
+ Schema.String,
256
+ Schema.String,
257
+ Schema.String,
258
+ Schema.String,
259
+ Schema.String
260
+ ]));
261
+ const RouteValueJson = Schema.fromJsonString(Schema.Struct({ forgotten: Schema.optionalKey(Schema.Literal(true)) }));
262
+ const routeSlot = (key, output, streamId) => encodeKey([
263
+ ...routeKeyParts(key),
264
+ output,
265
+ streamId
266
+ ]);
267
+ const routeRecords = (store) => {
268
+ const entries = (key) => {
269
+ const prefix = `${encodeKey(routeKeyParts(key)).slice(0, -1)},`;
270
+ return store.list === void 0 ? Effect.fail(new ProjectionFault({
271
+ phase: "checkpoint",
272
+ reason: "unsupported-composition",
273
+ message: "This CheckpointStore does not support listing routed outputs"
274
+ })) : store.list(prefix);
275
+ };
276
+ return {
277
+ has: (key, output, streamId) => store.read(routeSlot(key, output, streamId)).pipe(Effect.map(Option.isSome)),
278
+ state: (key, output, streamId) => Effect.gen(function* () {
279
+ const encoded = yield* store.read(routeSlot(key, output, streamId));
280
+ if (Option.isNone(encoded)) return "absent";
281
+ return (yield* Schema.decodeEffect(RouteValueJson, { onExcessProperty: "error" })(encoded.value).pipe(Effect.mapError((cause) => new ProjectionFault({
282
+ phase: "process",
283
+ reason: "invalid-record",
284
+ message: `Invalid routed output record for ${key.id}: ${output} at ${streamId}`,
285
+ cause
286
+ })))).forgotten === true ? "forgotten" : "live";
287
+ }),
288
+ add: (key, output, streamId) => store.write(routeSlot(key, output, streamId), "{}"),
289
+ list: (key) => Effect.flatMap(entries(key), (rows) => Effect.forEach(rows, ([slot]) => Schema.decodeEffect(RouteKeyJson)(slot).pipe(Effect.map(([, , , , , output, streamId]) => ({
290
+ output,
291
+ streamId
292
+ })), Effect.mapError((cause) => new ProjectionFault({
293
+ phase: "checkpoint",
294
+ reason: "invalid-record",
295
+ message: `Invalid routed output record for ${key.id}`,
296
+ cause
297
+ }))))),
298
+ forget: (key, options) => {
299
+ const listed = entries(key);
300
+ const available = options?.ignoreUnsupportedList ? listed.pipe(Effect.catchIf((fault) => fault.reason === "unsupported-composition", () => Effect.succeed([]))) : listed;
301
+ return Effect.flatMap(available, (rows) => Effect.forEach(rows, ([slot]) => store.write(slot, "{\"forgotten\":true}"), { discard: true }));
302
+ },
303
+ clear: (key) => Effect.flatMap(entries(key), (rows) => Effect.forEach(rows, ([slot]) => store.remove(slot), { discard: true }))
304
+ };
305
+ };
306
+ /**
307
+ * In a MySQL transaction a listing is a locking read, so it sees a record committed since
308
+ * the transaction's REPEATABLE READ snapshot. A plain read of an absent key does not.
309
+ * A range that cannot be listed, because of a legacy hashed key, counts as empty.
310
+ */
311
+ const readListed = (store, key) => store.list === void 0 ? Effect.succeedNone : store.list(key).pipe(Effect.map((entries) => Array.findFirst(entries, ([stored]) => stored === key).pipe(Option.map(([, encoded]) => encoded))), Effect.catchIf((fault) => fault.reason === "unsupported-composition", () => Effect.succeedNone));
312
+ const loadRecord = (read) => Effect.fn("Projection.CheckpointStore.load")(function* (key) {
313
+ const encoded = yield* read(recordKey(key));
314
+ if (Option.isNone(encoded)) return {
315
+ record: Option.none(),
316
+ token: ABSENT_TOKEN
317
+ };
318
+ const envelope = yield* decodeStored(key.id, encoded.value);
319
+ if ("retired" in envelope) return yield* new ProjectionFault({
320
+ phase: "load",
321
+ reason: "retired-generation",
322
+ message: `Generation ${key.generation} of ${key.id} is retired. Raise generation to run it again.`
323
+ });
324
+ return {
325
+ record: Option.some(envelope.record),
326
+ token: String(envelope.version)
327
+ };
328
+ });
329
+ const fromStore = (store) => {
330
+ const list = Effect.fn("Projection.CheckpointStore.list")(function* (id) {
331
+ if (store.list === void 0) return yield* unsupportedBindingList();
332
+ const prefix = `${encodeKey([CHECKPOINT_NAMESPACE, id]).slice(0, -1)},`;
333
+ const entries = yield* store.list(prefix);
334
+ const byKey = /* @__PURE__ */ new Map();
335
+ for (const [key, encoded] of entries) {
336
+ const [, , , generation, params] = yield* Schema.decodeEffect(CheckpointKeyJson)(key).pipe(Effect.mapError((cause) => new ProjectionFault({
337
+ phase: "load",
338
+ reason: "invalid-record",
339
+ message: `Invalid checkpoint key for ${id}`,
340
+ cause
341
+ })));
342
+ const stored = yield* decodeStored(id, encoded);
343
+ if ("retired" in stored || stored.record.ended === true) continue;
344
+ byKey.set(`${generation}:${canonicalParams(params)}`, {
345
+ generation,
346
+ params
347
+ });
348
+ }
349
+ return Array.fromIterable(byKey.values());
350
+ });
351
+ const load = loadRecord(store.read);
352
+ latestLoads.set(load, loadRecord((key) => store.read(key).pipe(Effect.filterOrElse(Option.isSome, () => readListed(store, key)))));
353
+ const compareAndSet = Effect.fn("Projection.CheckpointStore.compareAndSet")(function* (key, ifToken, record) {
354
+ return yield* store.withTransaction(Effect.gen(function* () {
355
+ const current = yield* load(key);
356
+ if (current.token !== ifToken) return yield* new ProjectionFault({
357
+ phase: "checkpoint",
358
+ reason: "token-conflict",
359
+ message: `Record for ${key.id} changed: expected token ${ifToken}, found ${current.token}. A second writer on the same key is the likely cause. Use one writer per key: the follower or one run at a time.`
360
+ });
361
+ const version = Number(ifToken) + 1;
362
+ const encoded = yield* Schema.encodeEffect(EnvelopeJson)({
363
+ version,
364
+ record
365
+ }).pipe(Effect.mapError(() => new ProjectionFault({
366
+ phase: "checkpoint",
367
+ reason: "invalid-record",
368
+ message: `Cannot encode record for ${key.id}`
369
+ })));
370
+ yield* store.write(recordKey(key), encoded);
371
+ return String(version);
372
+ }));
373
+ });
374
+ return {
375
+ list,
376
+ routes: routeRecords(store),
377
+ load,
378
+ compareAndSet,
379
+ remove: (key) => store.withTransaction(Effect.gen(function* () {
380
+ const slot = recordKey(key);
381
+ const encoded = yield* store.read(slot).pipe(Effect.mapError((fault) => new ProjectionFault({
382
+ phase: "checkpoint",
383
+ reason: fault.reason,
384
+ message: fault.message,
385
+ cause: fault.cause
386
+ })));
387
+ if (Option.isNone(encoded)) return;
388
+ const current = Schema.decodeOption(StoredJson)(encoded.value);
389
+ if (Option.isSome(current) && "retired" in current.value) return;
390
+ yield* store.remove(slot);
391
+ })),
392
+ retire: (key) => store.withTransaction(Effect.gen(function* () {
393
+ const slot = recordKey(key);
394
+ const existing = yield* store.read(slot);
395
+ const current = Option.flatMap(existing, Schema.decodeOption(StoredJson));
396
+ if (Option.isSome(current) && "retired" in current.value) return "already-retired";
397
+ const version = Option.isNone(current) ? 1 : current.value.version + 1;
398
+ const encoded = yield* Schema.encodeEffect(TombstoneJson)({
399
+ version,
400
+ retired: {}
401
+ }).pipe(Effect.mapError(() => new ProjectionFault({
402
+ phase: "checkpoint",
403
+ reason: "invalid-record",
404
+ message: `Cannot encode tombstone for ${key.id}`
405
+ })));
406
+ yield* store.write(slot, encoded);
407
+ return "retired";
408
+ }))
409
+ };
410
+ };
411
+ const unsupportedBindingList = () => new ProjectionFault({
412
+ phase: "load",
413
+ reason: "unsupported-composition",
414
+ message: "This CheckpointStore does not support listing bindings"
415
+ });
416
+ const identityOf = (inputs) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, address]) => [name, encodeKey([address.id, address.contentType])]));
417
+ const sameIdentity = (a, b) => {
418
+ const keys = Record.keys(a);
419
+ return keys.length === Record.keys(b).length && Array.every(keys, (k) => a[k] === b[k]);
420
+ };
421
+ /** The stored record, or the unstored initial record for a fresh key. */
422
+ const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
423
+ const loaded = yield* owner.load(projection);
424
+ const identity = { inputs: identityOf(projection.inputs) };
425
+ if (Option.isNone(loaded.record)) return {
426
+ record: {
427
+ identity,
428
+ inputs: Record.fromEntries(Array.map(Record.keys(projection.inputs), (name) => [name, ZERO_OFFSET])),
429
+ adapters: {}
430
+ },
431
+ token: loaded.token,
432
+ loaded
433
+ };
434
+ if (!sameIdentity(loaded.record.value.identity.inputs, identity.inputs)) return yield* new ProjectionFault({
435
+ phase: "load",
436
+ reason: "identity-mismatch",
437
+ message: `Stored inputs differ from the declaration of ${projection.id}`
438
+ });
439
+ for (const name of Record.keys(projection.inputs)) if (loaded.record.value.inputs[name] === void 0) return yield* new ProjectionFault({
440
+ phase: "load",
441
+ reason: "invalid-record",
442
+ input: name,
443
+ message: `Stored record of ${projection.id} has no offset for ${name}`
444
+ });
445
+ return {
446
+ record: loaded.record.value,
447
+ token: loaded.token,
448
+ loaded
449
+ };
450
+ });
451
+ /** Accepted offsets after a unit: every read input moves to its `nextOffset`. */
452
+ const advance = (inputs, ranges) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, offset]) => [name, ranges[name]?.nextOffset ?? offset]));
453
+ /** Items and terminal outcomes contribute ranges, including zero-length terminal ranges. */
454
+ const rangesOf = (slices) => Record.fromEntries(Array.map(Array.filter(Record.toEntries(slices), ([, slice]) => slice.items.length > 0 || slice.closed || slice.gone === true), ([name, slice]) => [name, {
455
+ from: slice.from,
456
+ nextOffset: slice.nextOffset,
457
+ ...terminalOf(slice)
458
+ }]));
459
+ export { NonRetryable as _, fromStore as a, recordKey as c, canonicalParams as d, encodeKey as f, InvalidBinding as g, withParams as h, assertCheckpointKeyVersion as i, restore as l, unitOf as m, CheckpointStore as n, loadLatest as o, terminalOf as p, advance as r, rangesOf as s, CheckpointRecord as t, unsupportedBindingList as u, NotAttached as v, ProjectionFault as y };