@streamsy/projection 0.11.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.
@@ -1,7 +1,16 @@
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");
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
+ }) {};
5
14
  /** Phase says where the run stopped; a `checkpoint` failure means processing already completed. */
6
15
  var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
7
16
  phase: Schema.Literals([
@@ -19,8 +28,10 @@ var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
19
28
  "invalid-options",
20
29
  "invalid-output",
21
30
  "token-conflict",
31
+ "output-busy",
22
32
  "range-unreproducible",
23
33
  "stale-epoch",
34
+ "retired-generation",
24
35
  "storage-failure",
25
36
  "unsupported-composition"
26
37
  ]),
@@ -29,7 +40,22 @@ var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
29
40
  cause: Schema.optionalKey(Schema.Defect())
30
41
  }) {
31
42
  get retryable() {
32
- return this.reason === "storage-failure" && (!isStreamsFault(this.cause) || this.cause.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;
33
59
  }
34
60
  };
35
61
  // src/unit.ts
@@ -53,9 +79,11 @@ const PinnedRange = Schema.Struct({
53
79
  upToDate: Schema.optionalKey(Schema.Boolean),
54
80
  ...terminal
55
81
  });
56
- /** An outputs unit that was pinned before its append; settled by the next pass. */
82
+ /** A unit pinned before its handler or append; settled by the next pass. */
57
83
  const PendingUnit = Schema.Struct({
58
84
  ranges: Schema.Record(Schema.String, PinnedRange),
85
+ /** Recorded wake time, preserved across retries. */
86
+ due: Schema.optionalKey(Counter),
59
87
  seqs: Schema.optionalKey(Schema.Record(Schema.String, Counter))
60
88
  });
61
89
  /** Deterministic JSON: keys sorted, so equal maps always encode identically. */
@@ -75,17 +103,19 @@ const canonicalRanges = (ranges) => JSON.stringify(Record.fromEntries(Array.map(
75
103
  }];
76
104
  })));
77
105
  /** The key is stable across producer retries; transaction retries may read a longer tail. */
78
- const unitOf = (projectionId, version, generation, params, ranges) => ({
106
+ const unitOf = (projectionId, version, generation, params, ranges, due) => ({
79
107
  projectionId,
80
108
  version,
81
109
  generation,
82
110
  params,
83
111
  ranges,
112
+ due: Option.fromUndefinedOr(due),
84
113
  key: encodeKey([
85
114
  projectionId,
86
115
  String(generation),
87
116
  canonicalParams(params),
88
- canonicalRanges(ranges)
117
+ canonicalRanges(ranges),
118
+ ...due === void 0 ? [] : [String(due)]
89
119
  ])
90
120
  });
91
121
  /** The handler view of a kernel unit, with the decoded params. */
@@ -99,6 +129,8 @@ const CheckpointRecord = Schema.Struct({
99
129
  /** Input key to accepted offset; the next pass reads after these. */
100
130
  inputs: Schema.Record(Schema.String, Schema.String),
101
131
  pending: Schema.optionalKey(PendingUnit),
132
+ /** Next process wake, in epoch milliseconds. Absent means no timer. */
133
+ wakeAt: Schema.optionalKey(Counter),
102
134
  /** Inputs whose terminal close has already been processed. */
103
135
  closed: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)),
104
136
  /** The final gone unit committed; only forgetting remains. */
@@ -115,8 +147,22 @@ const Envelope = Schema.Struct({
115
147
  record: CheckpointRecord
116
148
  });
117
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
+ ]));
118
164
  const recordKey = (key) => encodeKey([
119
- "streamsy.projection.v1",
165
+ CHECKPOINT_NAMESPACE,
120
166
  key.id,
121
167
  String(key.version),
122
168
  String(key.generation),
@@ -145,6 +191,12 @@ var CheckpointStore = class extends Context.Service()("@streamsy/projection/Chec
145
191
  const boundary = yield* CommitBoundary;
146
192
  const records = yield* OwnerRecords;
147
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
+ }))),
148
200
  read: (key) => records.read(key).pipe(Effect.mapError(storageFailure("load", "Cannot read a checkpoint"))),
149
201
  write: (key, value) => records.write(key, value).pipe(Effect.mapError((cause) => cause.operation === OWNER_RECORD_CONFLICT ? new ProjectionFault({
150
202
  phase: "checkpoint",
@@ -168,60 +220,174 @@ var CheckpointStore = class extends Context.Service()("@streamsy/projection/Chec
168
220
  const records = /* @__PURE__ */ new Map();
169
221
  const lock = yield* Semaphore.make(1);
170
222
  return fromStore({
223
+ list: (prefix) => lock.withPermits(1)(Effect.sync(() => Array.filter(Array.fromIterable(records), ([key]) => key.startsWith(prefix)))),
171
224
  read: (key) => Effect.sync(() => Option.fromUndefinedOr(records.get(key))),
172
225
  write: (key, value) => Effect.sync(() => {
173
226
  records.set(key, value);
174
227
  }),
175
- remove: (key) => lock.withPermits(1)(Effect.sync(() => {
228
+ remove: (key) => Effect.sync(() => {
176
229
  records.delete(key);
177
- })),
230
+ }),
178
231
  withTransaction: lock.withPermits(1)
179
232
  });
180
233
  }));
181
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
+ };
182
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
+ });
183
308
  const load = Effect.fn("Projection.CheckpointStore.load")(function* (key) {
184
309
  const encoded = yield* store.read(recordKey(key));
185
310
  if (Option.isNone(encoded)) return {
186
311
  record: Option.none(),
187
312
  token: ABSENT_TOKEN
188
313
  };
189
- 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({
190
316
  phase: "load",
191
- reason: "invalid-record",
192
- message: `Invalid stored record for ${key.id}`
193
- })));
317
+ reason: "retired-generation",
318
+ message: `Generation ${key.generation} of ${key.id} is retired. Raise generation to run it again.`
319
+ });
194
320
  return {
195
321
  record: Option.some(envelope.record),
196
322
  token: String(envelope.version)
197
323
  };
198
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
+ });
199
346
  return {
347
+ list,
348
+ routes: routeRecords(store),
200
349
  load,
201
- compareAndSet: Effect.fn("Projection.CheckpointStore.compareAndSet")(function* (key, ifToken, record) {
202
- return yield* store.withTransaction(Effect.gen(function* () {
203
- const current = yield* load(key);
204
- if (current.token !== ifToken) return yield* new ProjectionFault({
205
- phase: "checkpoint",
206
- reason: "token-conflict",
207
- 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.`
208
- });
209
- const version = Number(ifToken) + 1;
210
- const encoded = yield* Schema.encodeEffect(EnvelopeJson)({
211
- version,
212
- record
213
- }).pipe(Effect.mapError(() => new ProjectionFault({
214
- phase: "checkpoint",
215
- reason: "invalid-record",
216
- message: `Cannot encode record for ${key.id}`
217
- })));
218
- yield* store.write(recordKey(key), encoded);
219
- return String(version);
220
- }));
221
- }),
222
- 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
+ }))
223
384
  };
224
385
  };
386
+ const unsupportedBindingList = () => new ProjectionFault({
387
+ phase: "load",
388
+ reason: "unsupported-composition",
389
+ message: "This CheckpointStore does not support listing bindings"
390
+ });
225
391
  const identityOf = (inputs) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, address]) => [name, encodeKey([address.id, address.contentType])]));
226
392
  const sameIdentity = (a, b) => {
227
393
  const keys = Record.keys(a);
@@ -265,4 +431,4 @@ const rangesOf = (slices) => Record.fromEntries(Array.map(Array.filter(Record.to
265
431
  nextOffset: slice.nextOffset,
266
432
  ...terminalOf(slice)
267
433
  }]));
268
- export { rangesOf as a, canonicalParams as c, withParams as d, ProjectionFault as f, fromStore as i, terminalOf as l, CheckpointStore as n, recordKey as o, advance as r, restore as s, CheckpointRecord as t, unitOf 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-D1saxIIM.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-Bm8z-f-l.js";
1
+ export { t as CheckpointRecord, n as CheckpointStore, i as fromStore, o as recordKey } from "./checkpoint-store-ViVETLzZ.js";