@streamsy/projection 0.0.0-tegami-trusted-publish-setup → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,972 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { a as rangesOf, c as canonicalParams, d as ProjectionFault, l as unitOf, n as CheckpointStore, r as advance, s as restore, t as CheckpointRecord, u as withParams } from "./checkpoint-store-CoDWYNbd.js";
3
+ import { Array, Context, Data, Duration, Effect, Function, Layer, Option, Pipeable, Predicate, Record, Ref, Result, Schedule, Schema } from "effect";
4
+ import { CommitBoundary, DurableState, Offset, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
5
+ import { Streams, StreamsWriter } from "@streamsy/core/protocol";
6
+ import { CurrentOwner, isForeignOwner, ownerOf } from "@streamsy/core/internal";
7
+ import { SqlClient } from "effect/sql";
8
+ // src/batch.ts
9
+ /** An input that was skipped this pass: nothing read, nothing known beyond its cursor. */
10
+ const emptySlice = (from) => ({
11
+ from,
12
+ items: [],
13
+ nextOffset: from,
14
+ upToDate: false,
15
+ closed: false
16
+ });
17
+ /** Iteration preserves the union of the declared input stream requirements. */
18
+ const inputEntries = (inputs) => Record.toEntries(inputs);
19
+ // src/read.ts
20
+ const validateOptions = (options) => Effect.suspend(() => options.limit === void 0 || Number.isSafeInteger(options.limit) && options.limit > 0 ? Effect.void : Effect.fail(new ProjectionFault({
21
+ phase: "load",
22
+ reason: "invalid-options",
23
+ message: "limit must be a positive safe integer"
24
+ })));
25
+ /** One bounded read after `from`; retain input history and never reuse a deleted stream id. */
26
+ const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, from) {
27
+ const { wire: reader } = yield* address.stream;
28
+ const historyUnavailable = () => new ProjectionFault({
29
+ phase: "read",
30
+ reason: "history-unavailable",
31
+ input,
32
+ message: `Required history of ${address.id} after ${from} is unavailable`
33
+ });
34
+ const storageFailure = (cause) => new ProjectionFault({
35
+ phase: "read",
36
+ reason: "storage-failure",
37
+ input,
38
+ message: `Cannot read ${address.id}`,
39
+ cause
40
+ });
41
+ if (Option.isNone(Schema.decodeOption(Offset)(from))) return yield* new ProjectionFault({
42
+ phase: "load",
43
+ reason: "invalid-record",
44
+ input,
45
+ message: `Stored offset for ${input} is not a valid offset`
46
+ });
47
+ const result = yield* reader.read(address.id, { offset: from }).pipe(Effect.catchTags({
48
+ InvalidReadRequest: (cause) => new ProjectionFault({
49
+ phase: "read",
50
+ reason: "invalid-source",
51
+ input,
52
+ message: cause.message,
53
+ cause
54
+ }),
55
+ StreamNotFound: () => historyUnavailable(),
56
+ StreamGone: () => historyUnavailable(),
57
+ StorageFault: storageFailure,
58
+ TransportFault: storageFailure
59
+ }));
60
+ if (result.nextOffset < from || result.messages.length === 0 && result.nextOffset !== from) return yield* historyUnavailable();
61
+ if (result.nextOffset === from && (result.messages.length > 0 || !result.upToDate)) return yield* new ProjectionFault({
62
+ phase: "read",
63
+ reason: "invalid-source",
64
+ input,
65
+ message: `Read of ${address.id} did not advance past ${from}`
66
+ });
67
+ return { slice: {
68
+ from,
69
+ items: yield* decodeMessages(input, address, result.messages),
70
+ nextOffset: result.nextOffset,
71
+ upToDate: result.upToDate,
72
+ closed: result.closed
73
+ } };
74
+ });
75
+ /** Decode failure is an input fault: the stored bytes do not match the declared codec. */
76
+ const decodeMessages = (input, address, messages) => Effect.forEach(messages, (message, index) => Schema.decodeEffect(address.codec)(Predicate.isTagged(address, "Json") ? new TextDecoder().decode(message.data) : message.data).pipe(Effect.mapError(() => new ProjectionFault({
77
+ phase: "read",
78
+ reason: "invalid-source",
79
+ input,
80
+ message: `Cannot decode ${address.id} at read message ${index}`
81
+ }))));
82
+ /** Re-read server pages, retaining the pinned count and checking the boundary where available. */
83
+ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, range) {
84
+ const { wire: reader } = yield* address.stream;
85
+ const unreproducible = (detail) => new ProjectionFault({
86
+ phase: "pin",
87
+ reason: "range-unreproducible",
88
+ input,
89
+ message: `Pinned range of ${address.id} after ${range.from} cannot be reproduced: ${detail}`
90
+ });
91
+ let messages = [];
92
+ let cursor = range.from;
93
+ let last;
94
+ while (messages.length < range.count) {
95
+ const page = yield* reader.read(address.id, { offset: cursor }).pipe(Effect.catchTags({
96
+ InvalidReadRequest: (cause) => new ProjectionFault({
97
+ phase: "pin",
98
+ reason: "invalid-record",
99
+ input,
100
+ message: cause.message,
101
+ cause
102
+ }),
103
+ StreamNotFound: () => unreproducible("the input is missing"),
104
+ StreamGone: () => unreproducible("the input is gone"),
105
+ StorageFault: (cause) => new ProjectionFault({
106
+ phase: "pin",
107
+ reason: "storage-failure",
108
+ input,
109
+ message: `Cannot read ${address.id}`,
110
+ cause
111
+ }),
112
+ TransportFault: (cause) => new ProjectionFault({
113
+ phase: "pin",
114
+ reason: "storage-failure",
115
+ input,
116
+ message: `Cannot read ${address.id}`,
117
+ cause
118
+ })
119
+ }));
120
+ if (page.messages.length === 0) return yield* unreproducible("the input ended early");
121
+ messages.push(...page.messages);
122
+ cursor = page.nextOffset;
123
+ last = page;
124
+ if (page.upToDate && messages.length < range.count) return yield* unreproducible("the input ended early");
125
+ }
126
+ if (last === void 0) return yield* unreproducible("the input ended early");
127
+ if (messages.length === range.count) {
128
+ if (cursor !== range.nextOffset) return yield* unreproducible(`the range ends at ${cursor}, not ${range.nextOffset}`);
129
+ } else {
130
+ messages = messages.slice(0, range.count);
131
+ if (compare(cursor, range.nextOffset) < 0) return yield* unreproducible("the input is shorter than the pin");
132
+ }
133
+ return { slice: {
134
+ from: range.from,
135
+ items: yield* decodeMessages(input, address, messages),
136
+ nextOffset: range.nextOffset,
137
+ upToDate: last.upToDate && cursor === range.nextOffset,
138
+ closed: last.closed && cursor === range.nextOffset
139
+ } };
140
+ });
141
+ /** Read one server page per input in declaration order. */
142
+ const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets) {
143
+ const slices = {};
144
+ let items = 0;
145
+ for (const [name, address] of inputEntries(inputs)) {
146
+ const read = yield* readSlice(name, address, offsets[name] ?? "");
147
+ slices[name] = read.slice;
148
+ items += read.slice.items.length;
149
+ }
150
+ return {
151
+ slices,
152
+ items
153
+ };
154
+ });
155
+ /** Tagged items in declaration order, then stream order within each input. */
156
+ const items = (batch) => {
157
+ const out = [];
158
+ for (const [input, slice] of Record.toEntries(batch)) for (const item of slice.items) out.push({
159
+ input,
160
+ item,
161
+ index: out.length
162
+ });
163
+ return out;
164
+ };
165
+ // src/outputs.ts
166
+ /** Resolve routes just like inputs, retaining the route codec and collection names. */
167
+ const resolveOutputs = (outputs, params, inputs) => {
168
+ const streams = addressesOf(outputs, params);
169
+ const ids = Array.map(Record.values(streams), (address) => address.id);
170
+ if (new Set(ids).size !== ids.length) throw new RangeError("Two outputs may not name the same stream");
171
+ const inputIds = new Set(Array.map(Record.values(inputs), (address) => address.id));
172
+ if (Array.some(ids, (id) => inputIds.has(id))) throw new RangeError("An output may not name an input stream");
173
+ if (Array.some(Record.values(streams), (address) => !Predicate.isTagged(address, "Json"))) throw new RangeError("Projection outputs require JSON or state routes");
174
+ return streams;
175
+ };
176
+ const collect = (outputs, buffers, emitted) => Effect.gen(function* () {
177
+ for (const [name, entries] of Record.toEntries(emitted)) {
178
+ const output = outputs[name];
179
+ if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* new ProjectionFault({
180
+ phase: "process",
181
+ reason: "invalid-output",
182
+ message: `Invalid output array ${name}`
183
+ });
184
+ const values = yield* Effect.try({
185
+ try: () => "collections" in output ? DurableState.changes(output, {}, entries) : entries,
186
+ catch: (cause) => new ProjectionFault({
187
+ phase: "process",
188
+ reason: "invalid-output",
189
+ message: `Invalid row change for ${name}`,
190
+ cause
191
+ })
192
+ });
193
+ (buffers[name] ??= []).push(...values);
194
+ }
195
+ return yield* Effect.void;
196
+ });
197
+ const pin$1 = (reason, message, cause) => new ProjectionFault({
198
+ phase: "pin",
199
+ reason,
200
+ message,
201
+ cause
202
+ });
203
+ /** Append one unit under its pinned tuple; appended and duplicate are one outcome. */
204
+ const appendPinned = Effect.fn("Projection.appendPinned")(function* (output, wire, items, position) {
205
+ return yield* Streams.append(output, items, { producer: position }).pipe(Effect.provideService(StreamsWriter, wire), Effect.catchTags({
206
+ EncodeFault: () => new ProjectionFault({
207
+ phase: "process",
208
+ reason: "invalid-output",
209
+ message: `Cannot encode output for ${output.id}`
210
+ }),
211
+ StaleEpoch: (error) => pin$1("stale-epoch", `Epoch ${position.producerEpoch} of ${output.id} is behind ${error.currentEpoch}`),
212
+ ProducerGap: (error) => pin$1("invalid-record", `Sequence ${error.receivedSeq} of ${output.id} does not follow ${error.expectedSeq}`),
213
+ NotSupported: (error) => pin$1("unsupported-composition", `${output.id} does not support ${error.feature}`),
214
+ StorageFault: (cause) => pin$1("storage-failure", `Cannot append to ${output.id}`, cause),
215
+ TransportFault: (cause) => pin$1("storage-failure", `Cannot append to ${output.id}`, cause),
216
+ StreamNotFound: () => pin$1("invalid-output", `Output ${output.id} does not exist`),
217
+ StreamGone: () => pin$1("invalid-output", `Output ${output.id} is gone`),
218
+ StreamClosed: () => pin$1("invalid-output", `Output ${output.id} is closed`),
219
+ AppendConflict: () => pin$1("invalid-output", `Output ${output.id} refused the append`),
220
+ StreamBusy: () => pin$1("invalid-output", `Output ${output.id} is busy`)
221
+ }));
222
+ });
223
+ // src/commit/range.ts
224
+ const RangeKey = Symbol.for("@streamsy/projection/internal/Range");
225
+ const extend = (commit) => Object.defineProperty(commit, RangeKey, {
226
+ value: "extend",
227
+ configurable: true
228
+ });
229
+ const pin = (commit) => Object.defineProperty(commit, RangeKey, {
230
+ value: "pin",
231
+ configurable: true
232
+ });
233
+ const isPinned = (commit) => RangeKey in commit && commit[RangeKey] === "pin";
234
+ const inherit = (source, target) => {
235
+ if (supportsPrepare(source)) withPrepare(target);
236
+ return isPinned(source) ? pin(target) : extend(target);
237
+ };
238
+ const PrepareKey = Symbol.for("@streamsy/projection/internal/Prepare");
239
+ const withPrepare = (commit) => Object.defineProperty(commit, PrepareKey, { value: true });
240
+ const supportsPrepare = (commit) => PrepareKey in commit && commit[PrepareKey] === true;
241
+ // src/commit/model.ts
242
+ const TypeId = "~@streamsy/projection/Commit";
243
+ /** Opaque to Commit authors; the kernel restores the original typed handler error. */
244
+ var HandlerFailed = class extends Schema.TaggedError()("HandlerFailed", { error: Schema.Unknown }) {};
245
+ const { Folded, Emitted, Accumulated } = Data.taggedEnum();
246
+ /** Custom Commits extend the input range on retry. Never store next when run fails;
247
+ * condition the write on loaded.token (checkpoint / token-conflict when it moved),
248
+ * and return token "0" for an absent record.
249
+ * load must return the stored state. If run and the write are not atomic,
250
+ * declare at-least-once. The guarantee must describe the actual write. */
251
+ const make = (options) => extend({
252
+ ...options,
253
+ [TypeId]: {
254
+ result: () => {},
255
+ provides: () => {},
256
+ requires: () => {
257
+ throw new Error("Commit variance is type-only");
258
+ }
259
+ },
260
+ pipe() {
261
+ return Pipeable.pipeArguments(this, arguments);
262
+ }
263
+ });
264
+ // src/commit/internal.ts
265
+ const DetailsKey = Symbol.for("@streamsy/projection/internal/Pending");
266
+ const setDetails = (pending, value) => Object.defineProperty(pending, DetailsKey, { value });
267
+ const detailsOf = (pending) => {
268
+ return pending[DetailsKey] ?? {
269
+ ranges: {},
270
+ outputs: {}
271
+ };
272
+ };
273
+ const load = (key) => CheckpointStore.use((store) => store.load(key));
274
+ const remove = (key) => CheckpointStore.use((store) => store.remove(key));
275
+ const withState = (next, result) => result !== void 0 && "encoded" in result ? {
276
+ ...next,
277
+ state: result.encoded
278
+ } : next;
279
+ const beforeRecord = (pending) => Option.getOrElse(pending.loaded.record, () => ({
280
+ ...pending.next,
281
+ inputs: Record.fromEntries(Array.map(Record.toEntries(pending.next.inputs), ([name, offset]) => [name, pending.unit.ranges[name]?.from ?? offset]))
282
+ }));
283
+ const settle = (pending, result) => CheckpointStore.use((store) => store.compareAndSet(pending.key, pending.loaded.token, withState(pending.next, result))).pipe(Effect.asVoid);
284
+ // src/commit/checkpoint.ts
285
+ const checkpoint = make({
286
+ name: "checkpoint",
287
+ guarantee: "exactly-once",
288
+ load,
289
+ remove,
290
+ apply: (pending) => Effect.flatMap(pending.run, (result) => settle(pending, result))
291
+ });
292
+ // src/transaction.ts
293
+ /** The SQL transaction and stream owner used by Commit.transaction. */
294
+ var Transaction = class extends Context.Service()("@streamsy/projection/Transaction") {
295
+ /**
296
+ * The storage owner's SQL transaction, for Commit.transaction. Works over every SQL
297
+ * storage host. A memory host has no SqlClient, so this Layer does not fit it.
298
+ */
299
+ static layer = Layer.effect(this, Effect.gen(function* () {
300
+ const sql = yield* SqlClient.SqlClient;
301
+ const boundary = yield* CommitBoundary;
302
+ return {
303
+ owner: ownerOf(boundary),
304
+ sql,
305
+ withTransaction: (body) => boundary.withTransaction(body).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(new ProjectionFault({
306
+ phase: "checkpoint",
307
+ reason: "storage-failure",
308
+ message: "The owner transaction failed",
309
+ cause
310
+ }))))
311
+ };
312
+ }));
313
+ };
314
+ // src/commit/transaction.ts
315
+ const transaction = withPrepare(make({
316
+ name: "transaction",
317
+ guarantee: "exactly-once",
318
+ load,
319
+ remove,
320
+ apply: (pending) => Effect.gen(function* () {
321
+ const tx = yield* Transaction;
322
+ const store = yield* CheckpointStore;
323
+ const outputs = detailsOf(pending).outputs;
324
+ for (const { address, service } of Record.values(outputs)) if (service.owner !== tx.owner) return yield* new ProjectionFault({
325
+ phase: "load",
326
+ reason: "unsupported-composition",
327
+ message: `Output ${address.id} does not share the transaction owner`
328
+ });
329
+ const prepare = detailsOf(pending).prepare;
330
+ if (prepare !== void 0) yield* prepare;
331
+ yield* tx.withTransaction(Effect.gen(function* () {
332
+ if ((yield* store.load(pending.key)).token !== pending.loaded.token) return yield* new ProjectionFault({
333
+ phase: "checkpoint",
334
+ reason: "token-conflict",
335
+ message: `Record of ${pending.key.id} changed while the unit was read. A second writer on the same key is the likely cause. Use one writer per key: the follower or one run at a time.`
336
+ });
337
+ const result = yield* pending.run.pipe(Effect.provideService(SqlClient.SqlClient, tx.sql), Effect.provideService(CurrentOwner, tx.owner), Effect.catchDefect((defect) => isForeignOwner(defect) ? Effect.fail(new ProjectionFault({
338
+ phase: "process",
339
+ reason: "unsupported-composition",
340
+ message: defect.message
341
+ })) : Effect.die(defect)));
342
+ if (result !== void 0 && "outputs" in result) for (const [name, output] of Record.toEntries(result.outputs)) {
343
+ if (!Array.isReadonlyArrayNonEmpty(output.items)) continue;
344
+ const resolved = outputs[name];
345
+ if (resolved === void 0) return yield* new ProjectionFault({
346
+ phase: "process",
347
+ reason: "invalid-output",
348
+ message: `Undeclared output ${name}`
349
+ });
350
+ yield* Streams.append(output.address, output.items).pipe(Effect.provideService(StreamsWriter, resolved.service.wire), Effect.mapError((cause) => new ProjectionFault({
351
+ phase: "process",
352
+ reason: "invalid-output",
353
+ message: `Cannot append to ${output.address.id}`,
354
+ cause
355
+ })));
356
+ }
357
+ yield* settle(pending, result);
358
+ return yield* Effect.void;
359
+ }));
360
+ return yield* Effect.void;
361
+ })
362
+ }));
363
+ // src/commit/producer.ts
364
+ /** The pinned tuple identity: the params join the id so two parameterisations never share a sequence. */
365
+ const producerId = (id, version, params) => `${id}/v${version}${Record.keys(params).length === 0 ? "" : `/${canonicalParams(params)}`}`;
366
+ /** The pin write is the last save before the append, so its conflict is a pin failure. */
367
+ const asPin = (fault) => fault.phase === "checkpoint" && fault.reason === "token-conflict" ? new ProjectionFault({
368
+ phase: "pin",
369
+ reason: fault.reason,
370
+ message: fault.message
371
+ }) : fault;
372
+ const producer = pin(make({
373
+ name: "producer",
374
+ guarantee: "effectively-once",
375
+ remove,
376
+ load: (key) => Effect.gen(function* () {
377
+ const loaded = yield* load(key);
378
+ if (Option.isSome(loaded.record)) {
379
+ if (loaded.record.value.pending !== void 0 && loaded.record.value.pending.seqs === void 0) return yield* new ProjectionFault({
380
+ phase: "load",
381
+ reason: "invalid-record",
382
+ message: "A producer pin must include output sequences"
383
+ });
384
+ for (const [name, position] of Record.toEntries(loaded.record.value.adapters.outputs ?? {})) if (position.epoch !== key.generation) return yield* new ProjectionFault({
385
+ phase: "load",
386
+ reason: "stale-epoch",
387
+ message: `Stored epoch ${position.epoch} of ${key.id}/${name} is not generation ${key.generation}`
388
+ });
389
+ }
390
+ return loaded;
391
+ }),
392
+ apply: (request) => Effect.gen(function* () {
393
+ const owner = yield* CheckpointStore;
394
+ const projection = request.key;
395
+ const before = {
396
+ record: beforeRecord(request),
397
+ token: request.loaded.token
398
+ };
399
+ const { identity, adapters } = before.record;
400
+ const streams = detailsOf(request).outputs;
401
+ const ranges = request.unit.ranges;
402
+ const positions = { ...adapters.outputs };
403
+ for (const [name, position] of Record.toEntries(positions)) if (position.epoch !== projection.generation) return yield* new ProjectionFault({
404
+ phase: "load",
405
+ reason: "stale-epoch",
406
+ message: `Stored epoch ${position.epoch} of ${projection.id}/${name} is not generation ${projection.generation}`
407
+ });
408
+ const pending = before.record.pending;
409
+ const result = yield* request.run;
410
+ const processed = { items: Record.fromEntries(Array.map(Record.toEntries(result.outputs), ([name, output]) => [name, output.items])) };
411
+ const seqs = pending === void 0 ? Record.fromEntries(Array.map(Array.filter(Record.keys(streams), (name) => (processed.items[name]?.length ?? 0) > 0), (name) => [name, positions[name]?.nextSeq ?? 0])) : pending.seqs ?? {};
412
+ for (const name of Record.keys(seqs)) if (streams[name] === void 0 || (processed.items[name]?.length ?? 0) === 0) return yield* new ProjectionFault({
413
+ phase: "process",
414
+ reason: "invalid-output",
415
+ message: `Cannot reproduce pinned output ${name}`
416
+ });
417
+ if (pending !== void 0) {
418
+ for (const name of Record.keys(streams)) if ((processed.items[name]?.length ?? 0) > 0 && seqs[name] === void 0) return yield* new ProjectionFault({
419
+ phase: "process",
420
+ reason: "invalid-output",
421
+ message: `Cannot reproduce pinned unit: output ${name} has items that were not pinned`
422
+ });
423
+ }
424
+ let token = before.token;
425
+ if (pending === void 0 && Record.keys(seqs).length > 0) {
426
+ for (const [name, output] of Record.toEntries(streams)) {
427
+ if (seqs[name] === void 0) continue;
428
+ const { wire, owner: outputOwner } = output.service;
429
+ if ((yield* wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== ownerOf(owner.load) ? Effect.fail(cause) : Streams.create(output.address).pipe(Effect.provideService(StreamsWriter, wire), Effect.andThen(wire.head(output.address.id)))), Effect.mapError((cause) => new ProjectionFault({
430
+ phase: "pin",
431
+ reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
432
+ message: `Cannot prepare output ${output.address.id}`,
433
+ cause
434
+ })))).closed) return yield* new ProjectionFault({
435
+ phase: "pin",
436
+ reason: "invalid-output",
437
+ message: `Output ${output.address.id} is closed`
438
+ });
439
+ positions[name] = positions[name] ?? {
440
+ epoch: projection.generation,
441
+ nextSeq: 0
442
+ };
443
+ }
444
+ const pinned = {
445
+ identity,
446
+ inputs: before.record.inputs,
447
+ adapters: { outputs: { ...positions } },
448
+ pending: {
449
+ seqs,
450
+ ranges: Record.fromEntries(Array.map(Record.toEntries(ranges), ([name, range]) => [name, {
451
+ from: range.from,
452
+ nextOffset: range.nextOffset,
453
+ count: detailsOf(request).ranges[name]?.count ?? 0
454
+ }]))
455
+ }
456
+ };
457
+ if (before.record.state !== void 0) Object.assign(pinned, { state: before.record.state });
458
+ token = yield* owner.compareAndSet(projection, before.token, pinned).pipe(Effect.mapError(asPin));
459
+ }
460
+ for (const [name, output] of Record.toEntries(streams)) {
461
+ const seq = seqs[name];
462
+ const items = processed.items[name] ?? [];
463
+ if (seq === void 0 || !Array.isReadonlyArrayNonEmpty(items)) continue;
464
+ yield* appendPinned(output.address, output.service.wire, items, {
465
+ producerId: producerId(projection.id, projection.version, projection.params),
466
+ producerEpoch: projection.generation,
467
+ producerSeq: seq
468
+ });
469
+ positions[name] = {
470
+ epoch: projection.generation,
471
+ nextSeq: seq + 1
472
+ };
473
+ }
474
+ const record = {
475
+ identity,
476
+ inputs: request.next.inputs,
477
+ adapters: Record.keys(positions).length === 0 ? adapters : { outputs: positions }
478
+ };
479
+ yield* owner.compareAndSet(projection, token, withState({
480
+ ...request.next,
481
+ ...record
482
+ }, result));
483
+ return yield* Effect.void;
484
+ })
485
+ }));
486
+ // src/commit/at-least-once.ts
487
+ const atLeastOnce = pin(make({
488
+ name: "atLeastOnce",
489
+ guarantee: "at-least-once",
490
+ load,
491
+ remove,
492
+ apply: (pending) => Effect.gen(function* () {
493
+ const store = yield* CheckpointStore;
494
+ const before = beforeRecord(pending);
495
+ const token = before.pending === void 0 ? yield* store.compareAndSet(pending.key, pending.loaded.token, {
496
+ ...before,
497
+ pending: { ranges: detailsOf(pending).ranges }
498
+ }) : pending.loaded.token;
499
+ yield* pending.run;
500
+ yield* store.compareAndSet(pending.key, token, pending.next);
501
+ })
502
+ }));
503
+ // src/commit/compensation.ts
504
+ const withCompensation = Function.dual(2, (self, f) => inherit(self, make({
505
+ ...self,
506
+ apply: (pending) => Effect.suspend(() => {
507
+ let completed = Option.none();
508
+ const observed = setDetails({
509
+ ...pending,
510
+ run: pending.run.pipe(Effect.tap((result) => Effect.sync(() => {
511
+ completed = Option.some(result);
512
+ })))
513
+ }, detailsOf(pending));
514
+ return self.apply(observed).pipe(Effect.catchCause((cause) => (Option.isSome(completed) ? f(completed.value, cause, pending.unit) : Effect.void).pipe(Effect.andThen(Effect.failCause(cause)))));
515
+ })
516
+ })));
517
+ // src/commit.ts
518
+ var commit_exports = /* @__PURE__ */ __exportAll({
519
+ Accumulated: () => Accumulated,
520
+ Emitted: () => Emitted,
521
+ Folded: () => Folded,
522
+ HandlerFailed: () => HandlerFailed,
523
+ TypeId: () => TypeId,
524
+ atLeastOnce: () => atLeastOnce,
525
+ checkpoint: () => checkpoint,
526
+ make: () => make,
527
+ producer: () => producer,
528
+ transaction: () => transaction,
529
+ withCompensation: () => withCompensation
530
+ });
531
+ // src/state.ts
532
+ const bindState = (definition, params) => {
533
+ const initial = definition.initial;
534
+ return {
535
+ schema: definition.schema,
536
+ initial: () => typeof initial === "function" ? initial(params) : initial
537
+ };
538
+ };
539
+ /** Decodes the state field. `None` means no state is stored. */
540
+ const decodeState = (key, schema, encoded) => Option.isNone(encoded) ? Effect.succeedNone : Schema.decodeEffect(Schema.fromJsonString(schema))(encoded.value).pipe(Effect.asSome, Effect.mapError((cause) => new ProjectionFault({
541
+ phase: "load",
542
+ reason: "invalid-record",
543
+ message: `Invalid stored state for ${key.id}`,
544
+ cause
545
+ })));
546
+ /** The stored state, or the initial value when stored state is absent. */
547
+ const currentState = (key, state, encoded) => Effect.gen(function* () {
548
+ const stored = yield* decodeState(key, state.schema, Option.fromUndefinedOr(encoded));
549
+ return Option.getOrElse(stored, state.initial);
550
+ });
551
+ const encodeState = (key, schema, value) => Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(Effect.mapError((cause) => new ProjectionFault({
552
+ phase: "process",
553
+ reason: "invalid-output",
554
+ message: `Cannot encode state for ${key.id}`,
555
+ cause
556
+ })));
557
+ // src/step.ts
558
+ /** One adapter invocation is one unit. Per-entry variants thread state and preserve order. */
559
+ const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepared) => Effect.gen(function* () {
560
+ if (kind === "process") return yield* Effect.asVoid(handler(batch, unit, prepared));
561
+ let value = state === void 0 ? void 0 : yield* currentState(key, state, encoded);
562
+ const buffers = Record.fromEntries(Array.map(Record.keys(streams), (name) => [name, []]));
563
+ const steps = kind === "mapAccumBatch" ? [batch] : items(batch);
564
+ for (const entry of steps) {
565
+ const step = kind === "emit" ? handler(entry, unit) : handler(value, entry, unit);
566
+ const result = Effect.isEffect(step) ? yield* step : step;
567
+ if (kind === "fold") value = result;
568
+ else {
569
+ const emitted = kind === "emit" ? result : result[1];
570
+ if (kind !== "emit") value = result[0];
571
+ yield* collect(streams, buffers, emitted);
572
+ }
573
+ }
574
+ const batchOutputs = Record.fromEntries(Array.map(Record.toEntries(streams), ([name, address]) => [name, {
575
+ address,
576
+ items: buffers[name] ?? []
577
+ }]));
578
+ if (state === void 0) return Emitted({ outputs: batchOutputs });
579
+ const next = yield* encodeState(key, state.schema, value);
580
+ return kind === "fold" ? Folded({
581
+ value,
582
+ encoded: next
583
+ }) : Accumulated({
584
+ value,
585
+ encoded: next,
586
+ outputs: batchOutputs
587
+ });
588
+ });
589
+ // src/declaration.ts
590
+ const isDeclaration = (input) => "at" in input;
591
+ const encodeParams = (id, codecs, params) => {
592
+ const values = params;
593
+ return Record.fromEntries(Array.map(Record.toEntries(codecs), ([name, codec]) => {
594
+ const encoded = Schema.encodeOption(codec)(values[name]);
595
+ if (Option.isNone(encoded)) throw new RangeError(`Cannot encode projection ${id} parameter ${name}`);
596
+ return [name, encoded.value];
597
+ }));
598
+ };
599
+ const addressesOf = (inputs, params) => {
600
+ return Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, input]) => [name, isDeclaration(input) ? input.at(params) : input]));
601
+ };
602
+ const declare = (definition, bind) => {
603
+ const version = definition.version ?? 1;
604
+ const generation = definition.generation ?? 1;
605
+ return {
606
+ id: definition.id,
607
+ version,
608
+ generation,
609
+ params: definition.params,
610
+ at: (params) => bind({
611
+ id: definition.id,
612
+ version,
613
+ generation,
614
+ params: encodeParams(definition.id, definition.params, params),
615
+ decoded: params
616
+ }),
617
+ parse: (id) => {
618
+ for (const input of Record.values(definition.inputs)) {
619
+ if (!isDeclaration(input)) continue;
620
+ const parsed = input.parse(id);
621
+ if (Option.isSome(parsed)) return Option.some(parsed.value);
622
+ }
623
+ return Option.none();
624
+ }
625
+ };
626
+ };
627
+ const build = (kind, definition) => {
628
+ const commit = definition.commit ?? checkpoint;
629
+ if (definition.prepare !== void 0 && !supportsPrepare(commit)) throw new RangeError("prepare requires Commit.transaction");
630
+ return declare(definition, ({ decoded, ...key }) => {
631
+ const state = definition.state === void 0 ? void 0 : bindState(definition.state, decoded);
632
+ const inputs = addressesOf(definition.inputs, decoded);
633
+ const streams = resolveOutputs(definition.outputs ?? {}, decoded, inputs);
634
+ return {
635
+ ...key,
636
+ inputs,
637
+ state,
638
+ streams,
639
+ commit,
640
+ prepare: definition.prepare === void 0 ? void 0 : (batch, unit) => definition.prepare(batch, withParams(unit, decoded)),
641
+ process: (batch, unit, encoded, prepared) => adapt(kind, key, state, streams, definition[kind], batch, withParams(unit, decoded), encoded, prepared)
642
+ };
643
+ });
644
+ };
645
+ // src/fold.ts
646
+ function fold(definition) {
647
+ return build("fold", definition);
648
+ }
649
+ // src/process.ts
650
+ function process(definition) {
651
+ return build("process", definition);
652
+ }
653
+ // src/emit.ts
654
+ function emit(definition) {
655
+ return build("emit", definition);
656
+ }
657
+ // src/map-accum.ts
658
+ function mapAccum(definition) {
659
+ return build("mapAccum", definition);
660
+ }
661
+ function mapAccumBatch(definition) {
662
+ return build("mapAccumBatch", definition);
663
+ }
664
+ // src/snapshot.ts
665
+ /** Internal: the offsets of a record, typed by the declared inputs. */
666
+ const offsetsOf = (record) => record.inputs;
667
+ /**
668
+ * Reads the state and offsets from one checkpoint record, so the state
669
+ * always matches the offsets. Before the first unit, the state is the declared initial
670
+ * value and every offset is the start of its input.
671
+ */
672
+ const read = Effect.fn("Projection.read")(function* (projection) {
673
+ const declared = projection.state;
674
+ const restored = yield* restore(projection, projection.commit);
675
+ const encoded = Option.fromUndefinedOr(restored.record.state);
676
+ const stored = declared === void 0 ? Option.none() : yield* decodeState(projection, declared.schema, encoded);
677
+ return {
678
+ state: declared === void 0 ? void 0 : Option.getOrElse(stored, declared.initial),
679
+ offsets: offsetsOf(restored.record)
680
+ };
681
+ });
682
+ // src/run.ts
683
+ /** Restore and adapt one input unit; the Commit owns every write. */
684
+ const pass = Effect.fn("Projection.pass")(function* (projection) {
685
+ const before = yield* restore(projection, projection.commit);
686
+ const pending = before.record.pending;
687
+ if (pending !== void 0 && !isPinned(projection.commit)) return yield* new ProjectionFault({
688
+ phase: "load",
689
+ reason: "invalid-record",
690
+ message: `Commit ${projection.commit.name} cannot resume a pinned unit`
691
+ });
692
+ let batch;
693
+ let count = 0;
694
+ if (pending !== void 0) {
695
+ const slices = {};
696
+ for (const [name, address] of inputEntries(projection.inputs)) {
697
+ const range = pending.ranges[name];
698
+ if (range === void 0) slices[name] = emptySlice(before.record.inputs[name] ?? "");
699
+ else {
700
+ const read = yield* reproduce(name, address, range);
701
+ slices[name] = read.slice;
702
+ count += read.slice.items.length;
703
+ }
704
+ }
705
+ batch = slices;
706
+ } else {
707
+ const read = yield* readInputs(projection.inputs, before.record.inputs);
708
+ batch = read.slices;
709
+ count = read.items;
710
+ if (count === 0) return {
711
+ status: Array.every(Record.values(batch), (slice) => slice.closed) ? "source-closed" : "caught-up",
712
+ units: 0,
713
+ items: 0,
714
+ offsets: offsetsOf(before.record)
715
+ };
716
+ }
717
+ const ranges = pending?.ranges ?? rangesOf(batch);
718
+ const unit = unitOf(projection.id, projection.version, projection.generation, projection.params, ranges);
719
+ const { pending: _pending, ...record } = before.record;
720
+ const next = {
721
+ ...record,
722
+ inputs: advance(record.inputs, ranges)
723
+ };
724
+ const outputs = {};
725
+ for (const [name, address] of Record.toEntries(projection.streams ?? {})) outputs[name] = {
726
+ address,
727
+ service: yield* address.stream
728
+ };
729
+ let prepared;
730
+ const run = Effect.suspend(() => projection.process(batch, unit, before.record.state, prepared)).pipe(Effect.mapError((error) => new HandlerFailed({ error })));
731
+ const prepare = projection.prepare === void 0 ? void 0 : Effect.suspend(() => projection.prepare(batch, unit)).pipe(Effect.tap((value) => Effect.sync(() => {
732
+ prepared = value;
733
+ })), Effect.asVoid, Effect.mapError((error) => new HandlerFailed({ error })));
734
+ const request = setDetails({
735
+ key: projection,
736
+ unit,
737
+ loaded: before.loaded,
738
+ next,
739
+ run
740
+ }, {
741
+ outputs,
742
+ prepare,
743
+ ranges: Record.fromEntries(Array.map(Record.toEntries(ranges), ([name, range]) => [name, {
744
+ from: range.from,
745
+ nextOffset: range.nextOffset,
746
+ count: batch[name]?.items.length ?? 0
747
+ }]))
748
+ });
749
+ yield* projection.commit.apply(request).pipe(Effect.catchTag("HandlerFailed", (failure) => Effect.fail(failure.error)));
750
+ return {
751
+ status: "progress",
752
+ units: 1,
753
+ items: count,
754
+ offsets: offsetsOf(next)
755
+ };
756
+ });
757
+ /** Repeats pass until caught up, closed, or limited. Use one writer per key. */
758
+ const run = Effect.fn("Projection.run")(function* (projection, options = {}) {
759
+ yield* validateOptions(options);
760
+ const cap = options.limit ?? Number.POSITIVE_INFINITY;
761
+ let units = 0;
762
+ let items = 0;
763
+ let result;
764
+ do {
765
+ result = yield* pass(projection);
766
+ units += result.units;
767
+ items += result.items;
768
+ if (result.status !== "progress") return {
769
+ ...result,
770
+ units,
771
+ items
772
+ };
773
+ } while (units < cap);
774
+ return {
775
+ ...result,
776
+ status: "limit-reached",
777
+ units,
778
+ items
779
+ };
780
+ });
781
+ // src/retry.ts
782
+ const defaultRetry = Schedule.exponential("200 millis").pipe(Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.millis(Math.min(3e4, Duration.toMillis(duration))))), Schedule.jittered, Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.millis(Math.min(3e4, Duration.toMillis(duration))))));
783
+ /** Default storage-failure retry for follow; an explicit options.retry takes precedence. */
784
+ const ProjectionRetry = Context.Reference("@streamsy/projection/ProjectionRetry", { defaultValue: () => defaultRetry });
785
+ // src/follow.ts
786
+ /**
787
+ * One wake hint per input; the messages are discarded because the next run is
788
+ * authoritative. Only the response cursor is kept, so the next hint on that
789
+ * input echoes it. A closed input answers `readNext` at once, so a closed and
790
+ * drained input parks for the interval instead of waking every cycle; the
791
+ * open inputs, and the interval itself, decide when the next run happens.
792
+ */
793
+ const hint = Effect.fn("Projection.wake")(function* (input, address, offset, interval, cursors) {
794
+ const cursor = (yield* Ref.get(cursors))[input];
795
+ const { wire: reader } = yield* address.stream;
796
+ const historyUnavailable = () => new ProjectionFault({
797
+ phase: "read",
798
+ reason: "history-unavailable",
799
+ input,
800
+ message: `Required history of ${address.id} after ${offset} is unavailable`
801
+ });
802
+ const storageFailure = (cause) => new ProjectionFault({
803
+ phase: "read",
804
+ reason: "storage-failure",
805
+ input,
806
+ message: `Cannot wait on ${address.id}`,
807
+ cause
808
+ });
809
+ return yield* reader.readNext(address.id, {
810
+ offset,
811
+ cursor
812
+ }).pipe(Effect.tap((result) => Ref.update(cursors, (current) => ({
813
+ ...current,
814
+ [input]: result.cursor
815
+ }))), Effect.flatMap((result) => result.closed && result.messages.length === 0 ? Effect.never : Effect.void), Effect.catchTags({
816
+ InvalidReadRequest: (cause) => new ProjectionFault({
817
+ phase: "read",
818
+ reason: "invalid-source",
819
+ input,
820
+ message: cause.message,
821
+ cause
822
+ }),
823
+ StreamNotFound: () => historyUnavailable(),
824
+ StreamGone: () => historyUnavailable(),
825
+ NotSupported: (error) => new ProjectionFault({
826
+ phase: "read",
827
+ reason: "unsupported-composition",
828
+ input,
829
+ message: `${address.id} does not support ${error.feature}`
830
+ }),
831
+ StorageFault: storageFailure,
832
+ TransportFault: storageFailure
833
+ }), Effect.timeoutOption(interval), Effect.asVoid);
834
+ });
835
+ /**
836
+ * Runs to caught-up, then waits for the first input to hint at a change and runs
837
+ * again. The caller's scope owns the fiber and every parked wait; joining exposes
838
+ * the terminal close or a typed failure. On HTTP backends a parked hint is cancelled
839
+ * and replaced once per `repairIntervalMs` until an input changes.
840
+ */
841
+ const follow = Effect.fn("Projection.follow")(function* (projection, options = {}) {
842
+ yield* validateOptions(options);
843
+ const interval = options.repairIntervalMs ?? 3e4;
844
+ if (!Number.isSafeInteger(interval) || interval <= 0) return yield* new ProjectionFault({
845
+ phase: "load",
846
+ reason: "invalid-options",
847
+ message: "repairIntervalMs must be a positive safe integer"
848
+ });
849
+ const cursors = yield* Ref.make({});
850
+ const wake = (result) => Effect.raceAllFirst(Array.map(inputEntries(projection.inputs), ([name, address]) => hint(name, address, result.offsets[name] ?? ZERO_OFFSET, interval, cursors)));
851
+ return yield* run(projection, options).pipe(Effect.tap((result) => result.status === "caught-up" ? wake(result) : Effect.yieldNow)).pipe(Effect.retry({
852
+ while: (fault) => Schema.is(ProjectionFault)(fault) && fault.retryable,
853
+ schedule: (options.retry ?? (yield* ProjectionRetry)).pipe(Schedule.tap(({ input }) => Schema.is(ProjectionFault)(input) && input.retryable ? Effect.logWarning("Projection.follow retry", input) : Effect.void))
854
+ }), Effect.repeat({ while: (result) => result.status !== "source-closed" }), Effect.forkScoped);
855
+ });
856
+ // src/current.ts
857
+ /**
858
+ * Folds the checkpoint and input tail in memory, without locks or writes.
859
+ * Includes entries appended before the call. A growing input can delay completion.
860
+ * Fold steps must be replayable. Pending ranges are read from committed offsets.
861
+ */
862
+ const current = Effect.fn("Projection.current")(function* (projection) {
863
+ const { record } = yield* restore(projection, projection.commit);
864
+ let offsets = record.inputs;
865
+ let encoded = record.state;
866
+ let state = yield* currentState(projection, projection.state, encoded);
867
+ while (true) {
868
+ const page = yield* readInputs(projection.inputs, offsets);
869
+ if (page.items === 0) return {
870
+ state,
871
+ offsets: offsetsOf({ inputs: offsets })
872
+ };
873
+ const ranges = rangesOf(page.slices);
874
+ const unit = unitOf(projection.id, projection.version, projection.generation, projection.params, ranges);
875
+ const result = yield* projection.process(page.slices, unit, encoded);
876
+ state = result.value;
877
+ encoded = result.encoded;
878
+ offsets = advance(offsets, ranges);
879
+ }
880
+ });
881
+ // src/decide.ts
882
+ /** Up to three retries after a lost race, so at most four appends per call. */
883
+ const defaultDecideRetry = Schedule.recurs(3);
884
+ /**
885
+ * Fold in memory, decide, and append with the snapshot input offset.
886
+ * Retry only this append's OffsetMismatch while the retry schedule allows.
887
+ */
888
+ const decide = Effect.fn("Projection.decide")(function* (projection, spec) {
889
+ const address = projection.inputs[spec.input];
890
+ const attempt = Effect.gen(function* () {
891
+ const snapshot = yield* current(projection);
892
+ const offset = snapshot.offsets[spec.input];
893
+ const { value, items } = yield* spec.decide(snapshot);
894
+ if (!Array.isReadonlyArrayNonEmpty(items)) return {
895
+ value,
896
+ offset,
897
+ appended: false
898
+ };
899
+ const { wire } = yield* address.stream;
900
+ return {
901
+ value,
902
+ offset: (yield* Streams.append(address, items, { expectedOffset: offset }).pipe(Effect.provideService(StreamsWriter, wire), Effect.mapError((error) => isOffsetMismatch(error) ? new LostRace(error) : error))).offset,
903
+ appended: true
904
+ };
905
+ });
906
+ return yield* retryLostRace(attempt, spec.retry ?? defaultDecideRetry);
907
+ });
908
+ /**
909
+ * Marks the `OffsetMismatch` of this call's own append. As in `Streams.decide`,
910
+ * only this error is retried: an `OffsetMismatch` that the caller's `decide`
911
+ * raises is its own failure and passes through.
912
+ */
913
+ var LostRace = class {
914
+ mismatch;
915
+ constructor(mismatch) {
916
+ this.mismatch = mismatch;
917
+ }
918
+ };
919
+ /**
920
+ * Retry `attempt` after a `LostRace` while `schedule` allows, then fail with the
921
+ * last `OffsetMismatch`. `retry` steps its schedule with every error it sees, so
922
+ * every other outcome passes the retry as a `Result` and is raised after.
923
+ */
924
+ const retryLostRace = Effect.fnUntraced(function* (attempt, schedule) {
925
+ const outcome = yield* attempt.pipe(Effect.matchEffect({
926
+ onFailure: (error) => error instanceof LostRace ? Effect.fail(error.mismatch) : Effect.succeed(Result.fail(error)),
927
+ onSuccess: (value) => Effect.succeed(Result.succeed(value))
928
+ }), Effect.retry(schedule));
929
+ return yield* Effect.fromResult(outcome);
930
+ });
931
+ const isOffsetMismatch = (error) => Predicate.isTagged(error, "OffsetMismatch");
932
+ // src/forget.ts
933
+ /**
934
+ * Deletes the record. Stop the follower first, or use a new generation.
935
+ * Delete stream outputs first, because forgetting restarts their producer sequences.
936
+ */
937
+ const forget = (projection) => Effect.gen(function* () {
938
+ if (projection.commit.remove === void 0) return yield* new ProjectionFault({
939
+ phase: "checkpoint",
940
+ reason: "unsupported-composition",
941
+ message: "This Commit does not support forgetting"
942
+ });
943
+ yield* projection.commit.remove(projection);
944
+ return yield* Effect.void;
945
+ });
946
+ // src/projection.ts
947
+ var projection_exports = /* @__PURE__ */ __exportAll({
948
+ current: () => current,
949
+ decide: () => decide,
950
+ each: () => each,
951
+ emit: () => emit,
952
+ fold: () => fold,
953
+ follow: () => follow,
954
+ forget: () => forget,
955
+ items: () => items,
956
+ key: () => key,
957
+ mapAccum: () => mapAccum,
958
+ mapAccumBatch: () => mapAccumBatch,
959
+ pass: () => pass,
960
+ process: () => process,
961
+ read: () => read,
962
+ run: () => run
963
+ });
964
+ const key = (projection) => ({
965
+ id: projection.id,
966
+ version: projection.version,
967
+ generation: projection.generation,
968
+ params: projection.params
969
+ });
970
+ /** Runs each tagged entry in order and discards its success value. */
971
+ const each = (handle) => (batch, unit) => Effect.forEach(items(batch), (entry) => handle(entry, unit), { discard: true });
972
+ export { CheckpointRecord, CheckpointStore, commit_exports as Commit, HandlerFailed, projection_exports as Projection, ProjectionFault, ProjectionRetry, Transaction };