@streamsy/projection 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -82,6 +82,13 @@ across producer outputs. Chain projections for sinks with different guarantees.
82
82
  outside the transaction. It runs at least once and passes its result to
83
83
  `process`. A retry can read new input and change `unit.key`.
84
84
 
85
+ `Commit.transactionWithCleanup((key, sql) => cleanup)` passes the binding's
86
+ checkpoint key and transaction SQL client to the cleanup Effect.
87
+ `Projection.forget` runs cleanup after deleting any live checkpoint.
88
+ `Projection.retire` runs it after the tombstone write and owned output cleanup.
89
+ The callback also runs on a repeated retirement. A cleanup failure rolls back
90
+ changes in the same transaction, including SQL run with the supplied client.
91
+
85
92
  `Commit.withCompensation(f)` calls `f(result, cause, unit)` after successful
86
93
  processing if the commit fails. It is also available as a `.pipe` combinator.
87
94
  For external delivery, use `Commit.atLeastOnce` with `unit.key` as the idempotency key,
@@ -89,6 +96,11 @@ the declaration's [binding retry policy](https://streamsy.dev/docs/reference/pro
89
96
  for a retry budget and `onExhausted`, and [`Projection.wakeAt`](https://streamsy.dev/docs/projections/process#timers)
90
97
  for a deferred retry or a snooze. See the [effects guide](https://streamsy.dev/docs/projections/effects) for the complete pattern.
91
98
 
99
+ To stop a binding on a permanent typed handler error, add
100
+ `readonly [NonRetryable] = true` using `NonRetryable` from `@streamsy/projection`.
101
+ Attached runners report the failure without stepping the retry schedule or
102
+ calling `onExhausted`.
103
+
92
104
  `Commit.make` defines `load`, `apply`, and optional `remove`. Custom Commits
93
105
  extend ranges on retry. Never save after a failed handler; compare-and-set on
94
106
  `loaded.token`; report `checkpoint / token-conflict` for a moved token; return
@@ -30,6 +30,8 @@ type Entry<Inputs extends InputMap> = { readonly [K in keyof Inputs]: {
30
30
  readonly offset?: string;
31
31
  }; }[keyof Inputs];
32
32
  type InputServices<Inputs extends InputMap> = Inputs[keyof Inputs]["stream"]["Identifier"];
33
+ /** A typed handler failure bearing this marker stops its binding without retry. */
34
+ declare const NonRetryable: unique symbol;
33
35
  declare const NotAttached_base: Schema.Class<NotAttached, Schema.TaggedStruct<"NotAttached", {
34
36
  readonly projection: Schema.String;
35
37
  }>, import("effect/Cause").YieldableError>;
@@ -43,7 +45,7 @@ declare const InvalidBinding_base: Schema.Class<InvalidBinding, Schema.TaggedStr
43
45
  declare class InvalidBinding extends InvalidBinding_base {}
44
46
  declare const ProjectionFault_base: Schema.Class<ProjectionFault, Schema.TaggedStruct<"ProjectionFault", {
45
47
  readonly phase: Schema.Literals<readonly ["load", "read", "pin", "process", "checkpoint"]>;
46
- readonly reason: Schema.Literals<readonly ["history-unavailable", "identity-mismatch", "invalid-record", "invalid-source", "invalid-options", "invalid-output", "token-conflict", "output-busy", "range-unreproducible", "stale-epoch", "storage-failure", "unsupported-composition"]>;
48
+ readonly reason: Schema.Literals<readonly ["history-unavailable", "identity-mismatch", "invalid-record", "invalid-source", "invalid-options", "invalid-output", "token-conflict", "output-busy", "range-unreproducible", "stale-epoch", "retired-generation", "storage-failure", "unsupported-composition"]>;
47
49
  readonly input: Schema.optionalKey<Schema.String>;
48
50
  readonly message: Schema.String;
49
51
  readonly cause: Schema.optionalKey<Schema.Defect>;
@@ -105,6 +107,7 @@ declare const CheckpointRecord: Schema.Struct<{
105
107
  }>;
106
108
  }>;
107
109
  interface CheckpointRecord extends Schema.Schema.Type<typeof CheckpointRecord> {}
110
+ type RetirementStatus = "retired" | "already-retired";
108
111
  interface ProjectionKey {
109
112
  readonly id: string;
110
113
  readonly version: number;
@@ -116,13 +119,39 @@ interface Loaded {
116
119
  readonly record: Option.Option<CheckpointRecord>;
117
120
  readonly token: string;
118
121
  }
122
+ /** A binding found by `CheckpointStoreApi.list`. */
123
+ interface ListedBinding {
124
+ readonly generation: number;
125
+ readonly params: Record<string, string>;
126
+ }
127
+ interface RoutedStreamRecord {
128
+ readonly output: string;
129
+ readonly streamId: string;
130
+ }
131
+ /** Access the route inventory in the checkpoint owner's transaction. */
132
+ interface RouteRecords {
133
+ readonly has: (key: ProjectionKey, output: string, streamId: string) => Effect.Effect<boolean, ProjectionFault>;
134
+ readonly add: (key: ProjectionKey, output: string, streamId: string) => Effect.Effect<void, ProjectionFault>;
135
+ readonly list: (key: ProjectionKey) => Effect.Effect<ReadonlyArray<RoutedStreamRecord>, ProjectionFault>;
136
+ readonly clear: (key: ProjectionKey) => Effect.Effect<void, ProjectionFault>;
137
+ }
119
138
  interface CheckpointStoreApi {
120
139
  readonly load: (key: ProjectionKey) => Effect.Effect<Loaded, ProjectionFault>;
140
+ /**
141
+ * Lists each generation and encoded params with a live checkpoint for an id, across
142
+ * checkpoint versions. Each pair appears once, in unspecified order.
143
+ */
144
+ readonly list?: (id: string) => Effect.Effect<ReadonlyArray<ListedBinding>, ProjectionFault>;
145
+ /** Generation-owned streams opened lazily by routed outputs. */
146
+ readonly routes?: RouteRecords;
121
147
  /** Compare-and-set inside the owner transaction; returns the new token. */
122
148
  readonly compareAndSet: (key: ProjectionKey, ifToken: string, record: CheckpointRecord) => Effect.Effect<string, ProjectionFault>;
123
- /** Deletes the record. Absent keys are ignored. */
149
+ /** Deletes a live record. Absent keys and tombstones are ignored. */
124
150
  readonly remove: (key: ProjectionKey) => Effect.Effect<void, ProjectionFault>;
151
+ /** Replaces the live or absent record with a tombstone. */
152
+ readonly retire?: (key: ProjectionKey) => Effect.Effect<RetirementStatus, ProjectionFault>;
125
153
  }
154
+ type EncodedEntries = ReadonlyArray<readonly [key: string, encoded: string]>;
126
155
  declare const CheckpointStore_base: Context.ServiceClass<CheckpointStore, "@streamsy/projection/CheckpointStore", CheckpointStoreApi>;
127
156
  /** Stores each projection's offsets and encoded state in one compare-and-set record. */
128
157
  declare class CheckpointStore extends CheckpointStore_base {
@@ -136,6 +165,8 @@ declare class CheckpointStore extends CheckpointStore_base {
136
165
  }
137
166
  /** The encoded seam a checkpoint Layer builds on; both shipped Layers use it. */
138
167
  interface EncodedStore {
168
+ /** A snapshot of the stored entries whose keys start with the exact prefix. */
169
+ readonly list?: (prefix: string) => Effect.Effect<EncodedEntries, ProjectionFault>;
139
170
  readonly read: (key: string) => Effect.Effect<Option.Option<string>, ProjectionFault>;
140
171
  readonly write: (key: string, value: string) => Effect.Effect<void, ProjectionFault>;
141
172
  readonly remove: (key: string) => Effect.Effect<void, ProjectionFault>;
@@ -150,4 +181,4 @@ interface Identity {
150
181
  readonly params: Record<string, string>;
151
182
  readonly inputs: InputMap;
152
183
  }
153
- export { InputServices as _, Identity as a, Slices as b, fromStore as c, Unit as d, InvalidBinding as f, InputMap as g, Entry as h, EncodedStore as i, recordKey as l, ProjectionFault as m, CheckpointStore as n, Loaded as o, NotAttached as p, CheckpointStoreApi as r, ProjectionKey as s, CheckpointRecord as t, Range as u, ItemOf as v, Slice as y };
184
+ export { ItemOf as C, InputServices as S, Slices as T, NonRetryable as _, Identity as a, Entry as b, ProjectionKey as c, RoutedStreamRecord as d, fromStore as f, InvalidBinding as g, Unit as h, EncodedStore as i, RetirementStatus as l, Range as m, CheckpointStore as n, ListedBinding as o, recordKey as p, CheckpointStoreApi as r, Loaded as s, CheckpointRecord as t, RouteRecords as u, NotAttached as v, Slice as w, InputMap as x, ProjectionFault as y };
@@ -1,7 +1,9 @@
1
1
  import { Array, Context, Effect, Layer, Option, Order, Record, Schema, Semaphore } from "effect";
2
2
  import { CommitBoundary, ZERO_OFFSET, isStreamsFault } from "@streamsy/core";
3
- import { OwnerRecords, attachOwner, ownerOf } from "@streamsy/core/internal";
3
+ import { OWNER_RECORDS_LIST_UNSUPPORTED, OwnerRecords, attachOwner, ownerOf } from "@streamsy/core/internal";
4
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");
5
7
  /** No live runner for this declaration exists in the selected registry. */
6
8
  var NotAttached = class extends Schema.TaggedError()("NotAttached", { projection: Schema.String }) {};
7
9
  /** Encoded params do not round-trip through the attached declaration's codecs. */
@@ -29,6 +31,7 @@ var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
29
31
  "output-busy",
30
32
  "range-unreproducible",
31
33
  "stale-epoch",
34
+ "retired-generation",
32
35
  "storage-failure",
33
36
  "unsupported-composition"
34
37
  ]),
@@ -49,6 +52,7 @@ var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
49
52
  case "invalid-output":
50
53
  case "range-unreproducible":
51
54
  case "stale-epoch":
55
+ case "retired-generation":
52
56
  case "unsupported-composition": return false;
53
57
  }
54
58
  return false;
@@ -143,8 +147,22 @@ const Envelope = Schema.Struct({
143
147
  record: CheckpointRecord
144
148
  });
145
149
  const EnvelopeJson = Schema.fromJsonString(Envelope);
150
+ const Tombstone = Schema.Struct({
151
+ version: Counter,
152
+ retired: Schema.Struct({})
153
+ });
154
+ const TombstoneJson = Schema.fromJsonString(Tombstone);
155
+ const StoredJson = Schema.fromJsonString(Schema.Union([Envelope, Tombstone]));
156
+ const CHECKPOINT_NAMESPACE = "streamsy.projection.v1";
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
+ ]));
146
164
  const recordKey = (key) => encodeKey([
147
- "streamsy.projection.v1",
165
+ CHECKPOINT_NAMESPACE,
148
166
  key.id,
149
167
  String(key.version),
150
168
  String(key.generation),
@@ -173,6 +191,12 @@ var CheckpointStore = class extends Context.Service()("@streamsy/projection/Chec
173
191
  const boundary = yield* CommitBoundary;
174
192
  const records = yield* OwnerRecords;
175
193
  const checkpoints = fromStore({
194
+ list: (prefix) => records.list(prefix).pipe(Effect.mapError((cause) => new ProjectionFault({
195
+ phase: "load",
196
+ reason: cause.operation === OWNER_RECORDS_LIST_UNSUPPORTED ? "unsupported-composition" : "storage-failure",
197
+ message: cause.message,
198
+ cause
199
+ }))),
176
200
  read: (key) => records.read(key).pipe(Effect.mapError(storageFailure("load", "Cannot read a checkpoint"))),
177
201
  write: (key, value) => records.write(key, value).pipe(Effect.mapError((cause) => cause.operation === OWNER_RECORD_CONFLICT ? new ProjectionFault({
178
202
  phase: "checkpoint",
@@ -196,60 +220,174 @@ var CheckpointStore = class extends Context.Service()("@streamsy/projection/Chec
196
220
  const records = /* @__PURE__ */ new Map();
197
221
  const lock = yield* Semaphore.make(1);
198
222
  return fromStore({
223
+ list: (prefix) => lock.withPermits(1)(Effect.sync(() => Array.filter(Array.fromIterable(records), ([key]) => key.startsWith(prefix)))),
199
224
  read: (key) => Effect.sync(() => Option.fromUndefinedOr(records.get(key))),
200
225
  write: (key, value) => Effect.sync(() => {
201
226
  records.set(key, value);
202
227
  }),
203
- remove: (key) => lock.withPermits(1)(Effect.sync(() => {
228
+ remove: (key) => Effect.sync(() => {
204
229
  records.delete(key);
205
- })),
230
+ }),
206
231
  withTransaction: lock.withPermits(1)
207
232
  });
208
233
  }));
209
234
  };
235
+ const decodeStored = (id, encoded) => Schema.decodeEffect(StoredJson)(encoded).pipe(Effect.mapError(() => new ProjectionFault({
236
+ phase: "load",
237
+ reason: "invalid-record",
238
+ message: `Invalid stored record for ${id}`
239
+ })));
240
+ const ROUTED_NAMESPACE = "streamsy.projection.routed.v1";
241
+ const routeKeyParts = (key) => [
242
+ ROUTED_NAMESPACE,
243
+ key.id,
244
+ String(key.version),
245
+ String(key.generation),
246
+ canonicalParams(key.params)
247
+ ];
248
+ const RouteKeyJson = Schema.fromJsonString(Schema.Tuple([
249
+ Schema.Literal(ROUTED_NAMESPACE),
250
+ Schema.String,
251
+ Schema.String,
252
+ Schema.String,
253
+ Schema.String,
254
+ Schema.String,
255
+ Schema.String
256
+ ]));
257
+ const routeRecords = (store) => {
258
+ const entries = (key) => store.list === void 0 ? Effect.fail(new ProjectionFault({
259
+ phase: "checkpoint",
260
+ reason: "unsupported-composition",
261
+ message: "This CheckpointStore does not support listing routed outputs"
262
+ })) : store.list(`${encodeKey(routeKeyParts(key)).slice(0, -1)},`);
263
+ return {
264
+ has: (key, output, streamId) => store.read(encodeKey([
265
+ ...routeKeyParts(key),
266
+ output,
267
+ streamId
268
+ ])).pipe(Effect.map(Option.isSome)),
269
+ add: (key, output, streamId) => store.write(encodeKey([
270
+ ...routeKeyParts(key),
271
+ output,
272
+ streamId
273
+ ]), "{}"),
274
+ list: (key) => Effect.flatMap(entries(key), (rows) => Effect.forEach(rows, ([slot]) => Schema.decodeEffect(RouteKeyJson)(slot).pipe(Effect.map(([, , , , , output, streamId]) => ({
275
+ output,
276
+ streamId
277
+ })), Effect.mapError((cause) => new ProjectionFault({
278
+ phase: "checkpoint",
279
+ reason: "invalid-record",
280
+ message: `Invalid routed output record for ${key.id}`,
281
+ cause
282
+ }))))),
283
+ clear: (key) => Effect.flatMap(entries(key), (rows) => Effect.forEach(rows, ([slot]) => store.remove(slot), { discard: true }))
284
+ };
285
+ };
210
286
  const fromStore = (store) => {
287
+ const list = Effect.fn("Projection.CheckpointStore.list")(function* (id) {
288
+ if (store.list === void 0) return yield* unsupportedBindingList();
289
+ const prefix = `${encodeKey([CHECKPOINT_NAMESPACE, id]).slice(0, -1)},`;
290
+ const entries = yield* store.list(prefix);
291
+ const byKey = /* @__PURE__ */ new Map();
292
+ for (const [key, encoded] of entries) {
293
+ const [, , , generation, params] = yield* Schema.decodeEffect(CheckpointKeyJson)(key).pipe(Effect.mapError((cause) => new ProjectionFault({
294
+ phase: "load",
295
+ reason: "invalid-record",
296
+ message: `Invalid checkpoint key for ${id}`,
297
+ cause
298
+ })));
299
+ const stored = yield* decodeStored(id, encoded);
300
+ if ("retired" in stored || stored.record.ended === true) continue;
301
+ byKey.set(`${generation}:${canonicalParams(params)}`, {
302
+ generation,
303
+ params
304
+ });
305
+ }
306
+ return Array.fromIterable(byKey.values());
307
+ });
211
308
  const load = Effect.fn("Projection.CheckpointStore.load")(function* (key) {
212
309
  const encoded = yield* store.read(recordKey(key));
213
310
  if (Option.isNone(encoded)) return {
214
311
  record: Option.none(),
215
312
  token: ABSENT_TOKEN
216
313
  };
217
- const envelope = yield* Schema.decodeEffect(EnvelopeJson)(encoded.value).pipe(Effect.mapError(() => new ProjectionFault({
314
+ const envelope = yield* decodeStored(key.id, encoded.value);
315
+ if ("retired" in envelope) return yield* new ProjectionFault({
218
316
  phase: "load",
219
- reason: "invalid-record",
220
- message: `Invalid stored record for ${key.id}`
221
- })));
317
+ reason: "retired-generation",
318
+ message: `Generation ${key.generation} of ${key.id} is retired. Raise generation to run it again.`
319
+ });
222
320
  return {
223
321
  record: Option.some(envelope.record),
224
322
  token: String(envelope.version)
225
323
  };
226
324
  });
325
+ const compareAndSet = Effect.fn("Projection.CheckpointStore.compareAndSet")(function* (key, ifToken, record) {
326
+ return yield* store.withTransaction(Effect.gen(function* () {
327
+ const current = yield* load(key);
328
+ if (current.token !== ifToken) return yield* new ProjectionFault({
329
+ phase: "checkpoint",
330
+ reason: "token-conflict",
331
+ 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.`
332
+ });
333
+ const version = Number(ifToken) + 1;
334
+ const encoded = yield* Schema.encodeEffect(EnvelopeJson)({
335
+ version,
336
+ record
337
+ }).pipe(Effect.mapError(() => new ProjectionFault({
338
+ phase: "checkpoint",
339
+ reason: "invalid-record",
340
+ message: `Cannot encode record for ${key.id}`
341
+ })));
342
+ yield* store.write(recordKey(key), encoded);
343
+ return String(version);
344
+ }));
345
+ });
227
346
  return {
347
+ list,
348
+ routes: routeRecords(store),
228
349
  load,
229
- compareAndSet: Effect.fn("Projection.CheckpointStore.compareAndSet")(function* (key, ifToken, record) {
230
- return yield* store.withTransaction(Effect.gen(function* () {
231
- const current = yield* load(key);
232
- if (current.token !== ifToken) return yield* new ProjectionFault({
233
- phase: "checkpoint",
234
- reason: "token-conflict",
235
- 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.`
236
- });
237
- const version = Number(ifToken) + 1;
238
- const encoded = yield* Schema.encodeEffect(EnvelopeJson)({
239
- version,
240
- record
241
- }).pipe(Effect.mapError(() => new ProjectionFault({
242
- phase: "checkpoint",
243
- reason: "invalid-record",
244
- message: `Cannot encode record for ${key.id}`
245
- })));
246
- yield* store.write(recordKey(key), encoded);
247
- return String(version);
248
- }));
249
- }),
250
- remove: (key) => store.remove(recordKey(key))
350
+ compareAndSet,
351
+ remove: (key) => store.withTransaction(Effect.gen(function* () {
352
+ const slot = recordKey(key);
353
+ const encoded = yield* store.read(slot).pipe(Effect.mapError((fault) => new ProjectionFault({
354
+ phase: "checkpoint",
355
+ reason: fault.reason,
356
+ message: fault.message,
357
+ cause: fault.cause
358
+ })));
359
+ if (Option.isNone(encoded)) return;
360
+ const current = Schema.decodeOption(StoredJson)(encoded.value);
361
+ if (Option.isSome(current) && "retired" in current.value) return;
362
+ yield* store.remove(slot);
363
+ })),
364
+ retire: (key) => store.withTransaction(Effect.gen(function* () {
365
+ const slot = recordKey(key);
366
+ const existing = yield* store.read(slot);
367
+ let version = 1;
368
+ if (Option.isSome(existing)) {
369
+ const current = yield* decodeStored(key.id, existing.value);
370
+ if ("retired" in current) return "already-retired";
371
+ version = current.version + 1;
372
+ }
373
+ const encoded = yield* Schema.encodeEffect(TombstoneJson)({
374
+ version,
375
+ retired: {}
376
+ }).pipe(Effect.mapError(() => new ProjectionFault({
377
+ phase: "checkpoint",
378
+ reason: "invalid-record",
379
+ message: `Cannot encode tombstone for ${key.id}`
380
+ })));
381
+ yield* store.write(slot, encoded);
382
+ return "retired";
383
+ }))
251
384
  };
252
385
  };
386
+ const unsupportedBindingList = () => new ProjectionFault({
387
+ phase: "load",
388
+ reason: "unsupported-composition",
389
+ message: "This CheckpointStore does not support listing bindings"
390
+ });
253
391
  const identityOf = (inputs) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, address]) => [name, encodeKey([address.id, address.contentType])]));
254
392
  const sameIdentity = (a, b) => {
255
393
  const keys = Record.keys(a);
@@ -293,4 +431,4 @@ const rangesOf = (slices) => Record.fromEntries(Array.map(Array.filter(Record.to
293
431
  nextOffset: slice.nextOffset,
294
432
  ...terminalOf(slice)
295
433
  }]));
296
- export { rangesOf as a, canonicalParams as c, unitOf as d, withParams as f, ProjectionFault as h, fromStore as i, encodeKey as l, NotAttached as m, CheckpointStore as n, recordKey as o, InvalidBinding as p, advance as r, restore as s, CheckpointRecord as t, terminalOf as u };
434
+ export { ProjectionFault as _, rangesOf as a, unsupportedBindingList as c, terminalOf as d, unitOf as f, NotAttached as g, NonRetryable as h, fromStore as i, canonicalParams as l, InvalidBinding as m, CheckpointStore as n, recordKey as o, withParams as p, advance as r, restore as s, CheckpointRecord as t, encodeKey as u };
@@ -1,2 +1,2 @@
1
- import { c as fromStore, i as EncodedStore, l as recordKey, n as CheckpointStore, o as Loaded, r as CheckpointStoreApi, s as ProjectionKey, t as CheckpointRecord } from "./checkpoint-store-DCfrS4Fd.js";
2
- export { CheckpointRecord, CheckpointStore, type CheckpointStoreApi, type EncodedStore, type Loaded, type ProjectionKey, fromStore, recordKey };
1
+ import { c as ProjectionKey, d as RoutedStreamRecord, f as fromStore, i as EncodedStore, n as CheckpointStore, o as ListedBinding, p as recordKey, r as CheckpointStoreApi, s as Loaded, t as CheckpointRecord, u as RouteRecords } from "./checkpoint-store-B1199nDD.js";
2
+ export { CheckpointRecord, CheckpointStore, type CheckpointStoreApi, type EncodedStore, type ListedBinding, type Loaded, type ProjectionKey, type RouteRecords, type RoutedStreamRecord, fromStore, recordKey };
@@ -1 +1 @@
1
- export { t as CheckpointRecord, n as CheckpointStore, i as fromStore, o as recordKey } from "./checkpoint-store--bWf1qeP.js";
1
+ export { t as CheckpointRecord, n as CheckpointStore, i as fromStore, o as recordKey } from "./checkpoint-store-ViVETLzZ.js";