@streamsy/projection 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
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";
1
+ import { Array, Context, Effect, Layer, Match, Option, Order, Predicate, Record, Schema, Semaphore } from "effect";
2
+ import { DecodeFault, EncodeFault, InvalidStreamParams, StorageFault, StorageOwner, StreamBusy, TransportFault, ZERO_OFFSET, isStreamsFault } from "@streamsy/core";
3
+ import { OWNER_RECORDS_LIST_UNSUPPORTED, ownerParts } from "@streamsy/core/internal";
4
+ import { SqlError } from "effect/sql";
4
5
  // src/fault.ts
5
6
  /** A typed handler failure bearing this marker stops its binding without retry. */
6
7
  const NonRetryable = Symbol.for("@streamsy/projection/NonRetryable");
@@ -11,7 +12,174 @@ var InvalidBinding = class extends Schema.TaggedError()("InvalidBinding", {
11
12
  projection: Schema.String,
12
13
  params: Schema.Record(Schema.String, Schema.String)
13
14
  }) {};
14
- /** Phase says where the run stopped; a `checkpoint` failure means processing already completed. */
15
+ const reasonFields = {
16
+ message: Schema.String,
17
+ cause: Schema.optionalKey(Schema.Defect())
18
+ };
19
+ /** Another writer saved the record or claimed the output first. A retry reloads the token. */
20
+ var TokenConflict = class extends Schema.TaggedError()("TokenConflict", reasonFields) {
21
+ get isRetryable() {
22
+ return true;
23
+ }
24
+ };
25
+ /** An input does not have the history after its checkpoint offset, or the binding ended after losing one. */
26
+ var HistoryUnavailable = class extends Schema.TaggedError()("HistoryUnavailable", {
27
+ ...reasonFields,
28
+ stream: Schema.optionalKey(Schema.String)
29
+ }) {
30
+ get isRetryable() {
31
+ return false;
32
+ }
33
+ };
34
+ /**
35
+ * An input stream does not exist: the store has no record of it, because it was never created or
36
+ * was removed. Create the stream before the first run. A soft-deleted stream, or history missing
37
+ * after the checkpoint offset, is `HistoryUnavailable`. Not retryable: no retry creates the stream.
38
+ */
39
+ var InputNotFound = class extends Schema.TaggedError()("InputNotFound", {
40
+ ...reasonFields,
41
+ stream: Schema.String
42
+ }) {
43
+ get isRetryable() {
44
+ return false;
45
+ }
46
+ };
47
+ /** The generation was retired. A newer generation owns the projection. */
48
+ var RetiredGeneration = class extends Schema.TaggedError()("RetiredGeneration", reasonFields) {
49
+ get isRetryable() {
50
+ return false;
51
+ }
52
+ };
53
+ /** A pinned range can no longer be read the same way. A new generation fixes it. */
54
+ var RangeUnreproducible = class extends Schema.TaggedError()("RangeUnreproducible", reasonFields) {
55
+ get isRetryable() {
56
+ return false;
57
+ }
58
+ };
59
+ /** The stored identity does not match the deployed declaration. */
60
+ var IdentityMismatch = class extends Schema.TaggedError()("IdentityMismatch", reasonFields) {
61
+ get isRetryable() {
62
+ return false;
63
+ }
64
+ };
65
+ /** A wait names a generation other than the attached one. */
66
+ var GenerationMismatch = class extends Schema.TaggedError()("GenerationMismatch", reasonFields) {
67
+ get isRetryable() {
68
+ return false;
69
+ }
70
+ };
71
+ /** A newer generation has written. This runner must stop. */
72
+ var SupersededGeneration = class extends Schema.TaggedError()("SupersededGeneration", reasonFields) {
73
+ get isRetryable() {
74
+ return false;
75
+ }
76
+ };
77
+ /** Stored projection data does not decode, including a record from a newer release. */
78
+ var InvalidRecord = class extends Schema.TaggedError()("InvalidRecord", reasonFields) {
79
+ get isRetryable() {
80
+ return false;
81
+ }
82
+ };
83
+ /** An input answered with an invalid offset, or a read that does not advance. */
84
+ var InvalidSource = class extends Schema.TaggedError()("InvalidSource", reasonFields) {
85
+ get isRetryable() {
86
+ return false;
87
+ }
88
+ };
89
+ /** An output is closed, is not empty, or refused the append. */
90
+ var OutputRejected = class extends Schema.TaggedError()("OutputRejected", reasonFields) {
91
+ get isRetryable() {
92
+ return false;
93
+ }
94
+ };
95
+ /** The layers, stores or commit do not compose for this operation. */
96
+ var UnsupportedComposition = class extends Schema.TaggedError()("UnsupportedComposition", reasonFields) {
97
+ get isRetryable() {
98
+ return false;
99
+ }
100
+ };
101
+ /**
102
+ * A process handler returned `wakeAt` with a time that is not a non-negative safe integer in epoch
103
+ * milliseconds. `wakeAt` holds the value. Not retryable: the same data gives the same time again.
104
+ */
105
+ var InvalidWakeTime = class extends Schema.TaggedError()("InvalidWakeTime", {
106
+ ...reasonFields,
107
+ wakeAt: Schema.Number
108
+ }) {
109
+ get isRetryable() {
110
+ return false;
111
+ }
112
+ };
113
+ /** Why a projection pass failed. Core errors are used directly where they say it. */
114
+ const ProjectionFaultReason = Schema.Union([
115
+ TokenConflict,
116
+ HistoryUnavailable,
117
+ InputNotFound,
118
+ RetiredGeneration,
119
+ RangeUnreproducible,
120
+ IdentityMismatch,
121
+ GenerationMismatch,
122
+ SupersededGeneration,
123
+ InvalidRecord,
124
+ InvalidSource,
125
+ OutputRejected,
126
+ UnsupportedComposition,
127
+ InvalidWakeTime,
128
+ StorageFault,
129
+ TransportFault,
130
+ StreamBusy,
131
+ DecodeFault,
132
+ EncodeFault,
133
+ InvalidStreamParams
134
+ ]);
135
+ /** The `_tag` of a projection fault reason. `RunnerFailure.reason` holds one. */
136
+ const ProjectionFaultReasonTag = Schema.Literals([
137
+ "TokenConflict",
138
+ "HistoryUnavailable",
139
+ "InputNotFound",
140
+ "RetiredGeneration",
141
+ "RangeUnreproducible",
142
+ "IdentityMismatch",
143
+ "GenerationMismatch",
144
+ "SupersededGeneration",
145
+ "InvalidRecord",
146
+ "InvalidSource",
147
+ "OutputRejected",
148
+ "UnsupportedComposition",
149
+ "InvalidWakeTime",
150
+ "StorageFault",
151
+ "TransportFault",
152
+ "StreamBusy",
153
+ "DecodeFault",
154
+ "EncodeFault",
155
+ "InvalidStreamParams"
156
+ ]);
157
+ /** Whether a reason can succeed later. Core reasons without a retry property keep their old rule. */
158
+ const reasonRetryable = (reason) => Match.valueTags(reason, {
159
+ StorageFault: (fault) => fault.isRetryable,
160
+ TransportFault: (fault) => fault.isRetryable,
161
+ StreamBusy: () => true,
162
+ DecodeFault: () => false,
163
+ EncodeFault: () => false,
164
+ InvalidStreamParams: () => false,
165
+ TokenConflict: (fault) => fault.isRetryable,
166
+ HistoryUnavailable: (fault) => fault.isRetryable,
167
+ InputNotFound: (fault) => fault.isRetryable,
168
+ RetiredGeneration: (fault) => fault.isRetryable,
169
+ RangeUnreproducible: (fault) => fault.isRetryable,
170
+ IdentityMismatch: (fault) => fault.isRetryable,
171
+ GenerationMismatch: (fault) => fault.isRetryable,
172
+ SupersededGeneration: (fault) => fault.isRetryable,
173
+ InvalidRecord: (fault) => fault.isRetryable,
174
+ InvalidSource: (fault) => fault.isRetryable,
175
+ OutputRejected: (fault) => fault.isRetryable,
176
+ UnsupportedComposition: (fault) => fault.isRetryable,
177
+ InvalidWakeTime: (fault) => fault.isRetryable
178
+ });
179
+ /**
180
+ * Phase says where the run stopped; a `checkpoint` failure means processing already completed.
181
+ * `reason` is a tagged error: narrow it with `Effect.catchReason("ProjectionFault", tag, ...)`.
182
+ */
15
183
  var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
16
184
  phase: Schema.Literals([
17
185
  "load",
@@ -20,44 +188,47 @@ var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
20
188
  "process",
21
189
  "checkpoint"
22
190
  ]),
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
191
  input: Schema.optionalKey(Schema.String),
39
- message: Schema.String,
40
- cause: Schema.optionalKey(Schema.Defect())
192
+ reason: ProjectionFaultReason
41
193
  }) {
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;
194
+ /** The reason, as the JavaScript error cause. */
195
+ cause = this.reason;
196
+ get message() {
197
+ return this.reason.message;
198
+ }
199
+ get isRetryable() {
200
+ return reasonRetryable(this.reason);
59
201
  }
60
202
  };
203
+ const passesThrough = Schema.is(Schema.Union([
204
+ StorageFault,
205
+ TransportFault,
206
+ StreamBusy,
207
+ EncodeFault
208
+ ]));
209
+ /**
210
+ * The reason for a failed output create or append. A storage or transport fault, `StreamBusy`
211
+ * and `EncodeFault` say it themselves; any other rejection is `OutputRejected`.
212
+ */
213
+ const outputReason = (message, cause) => isStreamsFault(cause) || passesThrough(cause) ? cause : new OutputRejected({
214
+ message,
215
+ cause
216
+ });
217
+ /** Whether a wake time is a non-negative safe integer in epoch milliseconds. */
218
+ const isValidWakeTime = (time) => Number.isSafeInteger(time) && time >= 0;
219
+ /** The reason for a wake time that is not a non-negative safe integer in epoch milliseconds. */
220
+ const invalidWakeTime = (wakeAt) => new InvalidWakeTime({
221
+ wakeAt,
222
+ message: `wakeAt must be a non-negative safe integer in epoch milliseconds, got ${wakeAt}`
223
+ });
224
+ /** The reason for an input stream that has no record. */
225
+ const inputNotFound = (stream, cause) => new InputNotFound({
226
+ stream,
227
+ message: `Input stream ${stream} does not exist. Create it before the first run.`,
228
+ cause
229
+ });
230
+ /** Whether a fault says an input is missing: never created, deleted, or without its history. */
231
+ const isInputLoss = (fault) => Predicate.isTagged(fault.reason, "HistoryUnavailable") || Predicate.isTagged(fault.reason, "InputNotFound");
61
232
  // src/unit.ts
62
233
  /** Length-safe encoding of inert string components; no persistence decoding here. */
63
234
  const encodeKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
@@ -122,6 +293,33 @@ const withParams = (unit, params) => ({
122
293
  ...unit,
123
294
  params
124
295
  });
296
+ // src/storage-fault.ts
297
+ /** Preserve SQL retryability at the runner's storage boundary. */
298
+ const storageFault = (operation) => (cause) => new StorageFault({
299
+ operation,
300
+ message: cause.message,
301
+ isRetryable: cause.isRetryable,
302
+ cause
303
+ });
304
+ /** A body failure, kept apart from the owner's own `StorageFault`. */
305
+ var BodyFailure = class {
306
+ error;
307
+ constructor(error) {
308
+ this.error = error;
309
+ }
310
+ };
311
+ /**
312
+ * Run `body` in the owner's transaction. A SQL failure, in the body or in the owner,
313
+ * becomes a `ProjectionFault` in the checkpoint phase that keeps the SQL retry flag.
314
+ * Other body failures pass through unchanged.
315
+ */
316
+ const inOwnerTransaction = (owner) => (body) => owner.withTransaction(body.pipe(Effect.mapError((error) => SqlError.isSqlError(error) ? error : new BodyFailure(error)))).pipe(Effect.catch((error) => {
317
+ if (error instanceof BodyFailure) return Effect.fail(error.error);
318
+ return Effect.fail(new ProjectionFault({
319
+ phase: "checkpoint",
320
+ reason: SqlError.isSqlError(error) ? storageFault("transaction")(error) : error
321
+ }));
322
+ }));
125
323
  // src/checkpoint-store.ts
126
324
  const CheckpointRecord = Schema.Struct({
127
325
  identity: Schema.Struct({ inputs: Schema.Record(Schema.String, Schema.String) }),
@@ -176,55 +374,63 @@ const keyParts = (key) => {
176
374
  const recordKey = (key) => encodeKey([CHECKPOINT_NAMESPACE, ...keyParts(key)]);
177
375
  /** Token "0" means no record is stored yet. */
178
376
  const ABSENT_TOKEN = "0";
179
- const storageFailure = (phase, message) => (cause) => new ProjectionFault({
377
+ const storageFailure = (phase) => (cause) => new ProjectionFault({
180
378
  phase,
181
- reason: "storage-failure",
182
- message,
183
- cause
379
+ reason: cause
184
380
  });
381
+ /** A listing failure of a range, such as MySQL legacy hashed keys, not a missing `list`. */
382
+ const isUnlistable = (fault) => Predicate.isTagged(fault.reason, "UnsupportedComposition");
185
383
  /**
186
384
  * SQL storage fails a write with this operation when the transaction read the key as
187
385
  * absent and a concurrent save created it first. That save won the compare-and-set.
188
386
  */
189
387
  const OWNER_RECORD_CONFLICT = "records.conflict";
190
- /** The load that `loadLatest` uses for a store, keyed by its `load` like the owner metadata. */
388
+ /** The load that `loadLatest` uses for a store, keyed by its `load`. */
191
389
  const latestLoads = /* @__PURE__ */ new WeakMap();
192
390
  /** Load the latest committed record in a transaction whose snapshot can be older. */
193
391
  const loadLatest = (store, key) => (latestLoads.get(store.load) ?? store.load)(key);
392
+ /** One checkpoint store for each owner value, so the store's `load` keeps its identity. */
393
+ const ownerStores = /* @__PURE__ */ new WeakMap();
394
+ /**
395
+ * The checkpoints on a storage owner's records, in its transaction. `Commit.transaction`
396
+ * and `CheckpointStore.layer` both use it, so they share one place on the owner.
397
+ */
398
+ const ownerCheckpoints = (owner) => {
399
+ const cached = ownerStores.get(owner);
400
+ if (cached !== void 0) return cached;
401
+ const { records } = ownerParts(owner);
402
+ const checkpoints = {
403
+ ...fromStore({
404
+ list: (prefix) => records.list(prefix).pipe(Effect.mapError((cause) => new ProjectionFault({
405
+ phase: "load",
406
+ reason: cause.operation === OWNER_RECORDS_LIST_UNSUPPORTED ? new UnsupportedComposition({
407
+ message: cause.message,
408
+ cause
409
+ }) : cause
410
+ }))),
411
+ read: (key) => records.read(key).pipe(Effect.mapError(storageFailure("load"))),
412
+ write: (key, value) => records.write(key, value).pipe(Effect.mapError((cause) => cause.operation === OWNER_RECORD_CONFLICT ? new ProjectionFault({
413
+ phase: "checkpoint",
414
+ reason: new TokenConflict({
415
+ 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.",
416
+ cause
417
+ })
418
+ }) : storageFailure("checkpoint")(cause))),
419
+ remove: (key) => records.remove(key).pipe(Effect.mapError(storageFailure("checkpoint"))),
420
+ withTransaction: inOwnerTransaction(owner)
421
+ }),
422
+ owner: owner.id
423
+ };
424
+ ownerStores.set(owner, checkpoints);
425
+ return checkpoints;
426
+ };
194
427
  /** Stores each projection's offsets and encoded state in one compare-and-set record. */
195
428
  var CheckpointStore = class extends Context.Service()("@streamsy/projection/CheckpointStore") {
196
429
  /**
197
430
  * Checkpoints on the storage owner, in its transaction. Works over every Streamsy
198
431
  * storage host, so checkpoints and streams always share one owner.
199
432
  */
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
- }));
433
+ static layer = Layer.effect(this, Effect.map(StorageOwner, ownerCheckpoints));
228
434
  /** An independent store for rebuilt values and tests. It shares no owner with streams. */
229
435
  static layerMemory = Layer.effect(this, Effect.gen(function* () {
230
436
  const records = /* @__PURE__ */ new Map();
@@ -244,8 +450,7 @@ var CheckpointStore = class extends Context.Service()("@streamsy/projection/Chec
244
450
  };
245
451
  const decodeStored = (id, encoded) => Schema.decodeEffect(StoredJson)(encoded).pipe(Effect.mapError(() => new ProjectionFault({
246
452
  phase: "load",
247
- reason: "invalid-record",
248
- message: `Invalid stored record for ${id}`
453
+ reason: new InvalidRecord({ message: `Invalid stored record for ${id}` })
249
454
  })));
250
455
  const ROUTED_NAMESPACE = "streamsy.projection.routed.v1";
251
456
  const routeKeyParts = (key) => [ROUTED_NAMESPACE, ...keyParts(key)];
@@ -269,8 +474,7 @@ const routeRecords = (store) => {
269
474
  const prefix = `${encodeKey(routeKeyParts(key)).slice(0, -1)},`;
270
475
  return store.list === void 0 ? Effect.fail(new ProjectionFault({
271
476
  phase: "checkpoint",
272
- reason: "unsupported-composition",
273
- message: "This CheckpointStore does not support listing routed outputs"
477
+ reason: new UnsupportedComposition({ message: "This CheckpointStore does not support listing routed outputs" })
274
478
  })) : store.list(prefix);
275
479
  };
276
480
  return {
@@ -280,9 +484,10 @@ const routeRecords = (store) => {
280
484
  if (Option.isNone(encoded)) return "absent";
281
485
  return (yield* Schema.decodeEffect(RouteValueJson, { onExcessProperty: "error" })(encoded.value).pipe(Effect.mapError((cause) => new ProjectionFault({
282
486
  phase: "process",
283
- reason: "invalid-record",
284
- message: `Invalid routed output record for ${key.id}: ${output} at ${streamId}`,
285
- cause
487
+ reason: new InvalidRecord({
488
+ message: `Invalid routed output record for ${key.id}: ${output} at ${streamId}`,
489
+ cause
490
+ })
286
491
  })))).forgotten === true ? "forgotten" : "live";
287
492
  }),
288
493
  add: (key, output, streamId) => store.write(routeSlot(key, output, streamId), "{}"),
@@ -291,13 +496,14 @@ const routeRecords = (store) => {
291
496
  streamId
292
497
  })), Effect.mapError((cause) => new ProjectionFault({
293
498
  phase: "checkpoint",
294
- reason: "invalid-record",
295
- message: `Invalid routed output record for ${key.id}`,
296
- cause
499
+ reason: new InvalidRecord({
500
+ message: `Invalid routed output record for ${key.id}`,
501
+ cause
502
+ })
297
503
  }))))),
298
504
  forget: (key, options) => {
299
505
  const listed = entries(key);
300
- const available = options?.ignoreUnsupportedList ? listed.pipe(Effect.catchIf((fault) => fault.reason === "unsupported-composition", () => Effect.succeed([]))) : listed;
506
+ const available = !options?.ignoreUnsupportedList ? listed : store.list === void 0 ? Effect.succeed([]) : listed.pipe(Effect.catchIf(isUnlistable, () => Effect.succeed([])));
301
507
  return Effect.flatMap(available, (rows) => Effect.forEach(rows, ([slot]) => store.write(slot, "{\"forgotten\":true}"), { discard: true }));
302
508
  },
303
509
  clear: (key) => Effect.flatMap(entries(key), (rows) => Effect.forEach(rows, ([slot]) => store.remove(slot), { discard: true }))
@@ -308,7 +514,7 @@ const routeRecords = (store) => {
308
514
  * the transaction's REPEATABLE READ snapshot. A plain read of an absent key does not.
309
515
  * A range that cannot be listed, because of a legacy hashed key, counts as empty.
310
516
  */
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));
517
+ 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(isUnlistable, () => Effect.succeedNone));
312
518
  const loadRecord = (read) => Effect.fn("Projection.CheckpointStore.load")(function* (key) {
313
519
  const encoded = yield* read(recordKey(key));
314
520
  if (Option.isNone(encoded)) return {
@@ -318,8 +524,7 @@ const loadRecord = (read) => Effect.fn("Projection.CheckpointStore.load")(functi
318
524
  const envelope = yield* decodeStored(key.id, encoded.value);
319
525
  if ("retired" in envelope) return yield* new ProjectionFault({
320
526
  phase: "load",
321
- reason: "retired-generation",
322
- message: `Generation ${key.generation} of ${key.id} is retired. Raise generation to run it again.`
527
+ reason: new RetiredGeneration({ message: `Generation ${key.generation} of ${key.id} is retired. Raise generation to run it again.` })
323
528
  });
324
529
  return {
325
530
  record: Option.some(envelope.record),
@@ -335,9 +540,10 @@ const fromStore = (store) => {
335
540
  for (const [key, encoded] of entries) {
336
541
  const [, , , generation, params] = yield* Schema.decodeEffect(CheckpointKeyJson)(key).pipe(Effect.mapError((cause) => new ProjectionFault({
337
542
  phase: "load",
338
- reason: "invalid-record",
339
- message: `Invalid checkpoint key for ${id}`,
340
- cause
543
+ reason: new InvalidRecord({
544
+ message: `Invalid checkpoint key for ${id}`,
545
+ cause
546
+ })
341
547
  })));
342
548
  const stored = yield* decodeStored(id, encoded);
343
549
  if ("retired" in stored || stored.record.ended === true) continue;
@@ -355,8 +561,7 @@ const fromStore = (store) => {
355
561
  const current = yield* load(key);
356
562
  if (current.token !== ifToken) return yield* new ProjectionFault({
357
563
  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.`
564
+ reason: new TokenConflict({ 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
565
  });
361
566
  const version = Number(ifToken) + 1;
362
567
  const encoded = yield* Schema.encodeEffect(EnvelopeJson)({
@@ -364,8 +569,7 @@ const fromStore = (store) => {
364
569
  record
365
570
  }).pipe(Effect.mapError(() => new ProjectionFault({
366
571
  phase: "checkpoint",
367
- reason: "invalid-record",
368
- message: `Cannot encode record for ${key.id}`
572
+ reason: new InvalidRecord({ message: `Cannot encode record for ${key.id}` })
369
573
  })));
370
574
  yield* store.write(recordKey(key), encoded);
371
575
  return String(version);
@@ -380,9 +584,7 @@ const fromStore = (store) => {
380
584
  const slot = recordKey(key);
381
585
  const encoded = yield* store.read(slot).pipe(Effect.mapError((fault) => new ProjectionFault({
382
586
  phase: "checkpoint",
383
- reason: fault.reason,
384
- message: fault.message,
385
- cause: fault.cause
587
+ reason: fault.reason
386
588
  })));
387
589
  if (Option.isNone(encoded)) return;
388
590
  const current = Schema.decodeOption(StoredJson)(encoded.value);
@@ -400,8 +602,7 @@ const fromStore = (store) => {
400
602
  retired: {}
401
603
  }).pipe(Effect.mapError(() => new ProjectionFault({
402
604
  phase: "checkpoint",
403
- reason: "invalid-record",
404
- message: `Cannot encode tombstone for ${key.id}`
605
+ reason: new InvalidRecord({ message: `Cannot encode tombstone for ${key.id}` })
405
606
  })));
406
607
  yield* store.write(slot, encoded);
407
608
  return "retired";
@@ -410,8 +611,7 @@ const fromStore = (store) => {
410
611
  };
411
612
  const unsupportedBindingList = () => new ProjectionFault({
412
613
  phase: "load",
413
- reason: "unsupported-composition",
414
- message: "This CheckpointStore does not support listing bindings"
614
+ reason: new UnsupportedComposition({ message: "This CheckpointStore does not support listing bindings" })
415
615
  });
416
616
  const identityOf = (inputs) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, address]) => [name, encodeKey([address.id, address.contentType])]));
417
617
  const sameIdentity = (a, b) => {
@@ -433,14 +633,12 @@ const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
433
633
  };
434
634
  if (!sameIdentity(loaded.record.value.identity.inputs, identity.inputs)) return yield* new ProjectionFault({
435
635
  phase: "load",
436
- reason: "identity-mismatch",
437
- message: `Stored inputs differ from the declaration of ${projection.id}`
636
+ reason: new IdentityMismatch({ message: `Stored inputs differ from the declaration of ${projection.id}` })
438
637
  });
439
638
  for (const name of Record.keys(projection.inputs)) if (loaded.record.value.inputs[name] === void 0) return yield* new ProjectionFault({
440
639
  phase: "load",
441
- reason: "invalid-record",
442
640
  input: name,
443
- message: `Stored record of ${projection.id} has no offset for ${name}`
641
+ reason: new InvalidRecord({ message: `Stored record of ${projection.id} has no offset for ${name}` })
444
642
  });
445
643
  return {
446
644
  record: loaded.record.value,
@@ -450,10 +648,10 @@ const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
450
648
  });
451
649
  /** Accepted offsets after a unit: every read input moves to its `nextOffset`. */
452
650
  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, {
651
+ /** Advances and terminal outcomes contribute ranges, even when no items were decoded. */
652
+ const rangesOf = (slices) => Record.fromEntries(Array.map(Array.filter(Record.toEntries(slices), ([, slice]) => slice.from !== slice.nextOffset || slice.closed || slice.gone === true), ([name, slice]) => [name, {
455
653
  from: slice.from,
456
654
  nextOffset: slice.nextOffset,
457
655
  ...terminalOf(slice)
458
656
  }]));
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 };
657
+ export { ProjectionFault as A, isInputLoss as B, InvalidBinding as C, NonRetryable as D, InvalidWakeTime as E, SupersededGeneration as F, outputReason as H, TokenConflict as I, UnsupportedComposition as L, ProjectionFaultReasonTag as M, RangeUnreproducible as N, NotAttached as O, RetiredGeneration as P, inputNotFound as R, InputNotFound as S, InvalidSource as T, isValidWakeTime as V, unitOf as _, fromStore as a, HistoryUnavailable as b, rangesOf as c, unsupportedBindingList as d, inOwnerTransaction as f, terminalOf as g, encodeKey as h, assertCheckpointKeyVersion as i, ProjectionFaultReason as j, OutputRejected as k, recordKey as l, canonicalParams as m, CheckpointStore as n, loadLatest as o, storageFault as p, advance as r, ownerCheckpoints as s, CheckpointRecord as t, restore as u, withParams as v, InvalidRecord as w, IdentityMismatch as x, GenerationMismatch as y, invalidWakeTime as z };