@streamsy/projection 0.4.0 → 0.6.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 +129 -7
- package/dist/{checkpoint-store-DacqeoMQ.js → checkpoint-store-Bm8z-f-l.js} +43 -24
- package/dist/{checkpoint-store-yQb6UDAb.d.ts → checkpoint-store-D1saxIIM.d.ts} +12 -9
- package/dist/checkpoint.d.ts +1 -1
- package/dist/checkpoint.js +1 -1
- package/dist/index.d.ts +136 -74
- package/dist/index.js +464 -173
- package/dist/{rolldown-runtime-D7D4PA-g.js → rolldown-runtime-D8jQpDG7.js} +1 -2
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-
|
|
2
|
-
import { a as rangesOf, c as canonicalParams, d as ProjectionFault, l as
|
|
3
|
-
import { Array
|
|
4
|
-
import { CommitBoundary, DurableState, Offset, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
+
import { a as rangesOf, c as canonicalParams, d as withParams, f as ProjectionFault, l as terminalOf, n as CheckpointStore, r as advance, s as restore, t as CheckpointRecord, u as unitOf } from "./checkpoint-store-Bm8z-f-l.js";
|
|
3
|
+
import { Array, Cause, Clock, Context, Data, Duration, Effect, Exit, Function, Layer, Option, Pipeable, Predicate, PubSub, Record, Ref, Result, Schedule, Schema, Stream } from "effect";
|
|
4
|
+
import { CommitBoundary, DurableState, Offset, Storage, StreamId, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
|
|
5
5
|
import { Streams, StreamsWriter } from "@streamsy/core/protocol";
|
|
6
|
-
import {
|
|
7
|
-
import { CurrentOwner, isForeignOwner, ownerOf } from "@streamsy/core/internal";
|
|
6
|
+
import { CurrentOwner, compileSegments, isForeignOwner, ownerOf } from "@streamsy/core/internal";
|
|
8
7
|
import { SqlClient } from "effect/sql";
|
|
9
|
-
|
|
10
|
-
import { isReadonlyArrayNonEmpty } from "effect/Array";
|
|
11
|
-
//#region src/batch.ts
|
|
8
|
+
// src/batch.ts
|
|
12
9
|
/** An input that was skipped this pass: nothing read, nothing known beyond its cursor. */
|
|
13
10
|
const emptySlice = (from) => ({
|
|
14
11
|
from,
|
|
@@ -18,9 +15,8 @@ const emptySlice = (from) => ({
|
|
|
18
15
|
closed: false
|
|
19
16
|
});
|
|
20
17
|
/** Iteration preserves the union of the declared input stream requirements. */
|
|
21
|
-
const inputEntries = (inputs) =>
|
|
22
|
-
|
|
23
|
-
//#region src/read.ts
|
|
18
|
+
const inputEntries = (inputs) => Record.toEntries(inputs);
|
|
19
|
+
// src/read.ts
|
|
24
20
|
const validateOptions = (options) => Effect.suspend(() => options.limit === void 0 || Number.isSafeInteger(options.limit) && options.limit > 0 ? Effect.void : Effect.fail(new ProjectionFault({
|
|
25
21
|
phase: "load",
|
|
26
22
|
reason: "invalid-options",
|
|
@@ -76,6 +72,35 @@ const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, f
|
|
|
76
72
|
closed: result.closed
|
|
77
73
|
} };
|
|
78
74
|
});
|
|
75
|
+
/**
|
|
76
|
+
* A lost history is terminal only when a known input's head confirms it is gone.
|
|
77
|
+
* A pinned unit is replayed with `reproduce` and never takes this path: a
|
|
78
|
+
* removal between a pin and its append is a `range-unreproducible` fault.
|
|
79
|
+
*/
|
|
80
|
+
const readOrGone = Effect.fn("Projection.readOrGone")(function* (input, address, from, read, seen) {
|
|
81
|
+
return yield* read.pipe(Effect.catchTag("ProjectionFault", (fault) => {
|
|
82
|
+
if (!seen || fault.reason !== "history-unavailable") return Effect.fail(fault);
|
|
83
|
+
return Effect.gen(function* () {
|
|
84
|
+
const { wire } = yield* address.stream;
|
|
85
|
+
if (!(yield* wire.head(address.id).pipe(Effect.as(false), Effect.catchTags({
|
|
86
|
+
StreamNotFound: () => Effect.succeed(true),
|
|
87
|
+
StreamGone: () => Effect.succeed(true)
|
|
88
|
+
}), Effect.mapError((cause) => new ProjectionFault({
|
|
89
|
+
phase: "read",
|
|
90
|
+
reason: "storage-failure",
|
|
91
|
+
input,
|
|
92
|
+
message: `Cannot read the head of ${address.id}`,
|
|
93
|
+
cause
|
|
94
|
+
}))))) return yield* fault;
|
|
95
|
+
return { slice: {
|
|
96
|
+
...emptySlice(from),
|
|
97
|
+
upToDate: true,
|
|
98
|
+
closed: true,
|
|
99
|
+
gone: true
|
|
100
|
+
} };
|
|
101
|
+
});
|
|
102
|
+
}));
|
|
103
|
+
});
|
|
79
104
|
/** Decode failure is an input fault: the stored bytes do not match the declared codec. */
|
|
80
105
|
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({
|
|
81
106
|
phase: "read",
|
|
@@ -92,6 +117,16 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
|
|
|
92
117
|
input,
|
|
93
118
|
message: `Pinned range of ${address.id} after ${range.from} cannot be reproduced: ${detail}`
|
|
94
119
|
});
|
|
120
|
+
if (range.count === 0) {
|
|
121
|
+
if (range.from !== range.nextOffset || !range.closed && !range.gone) return yield* unreproducible("an empty pin must describe a terminal outcome at the same offset");
|
|
122
|
+
return { slice: {
|
|
123
|
+
...emptySlice(range.from),
|
|
124
|
+
nextOffset: range.nextOffset,
|
|
125
|
+
closed: range.closed === true,
|
|
126
|
+
upToDate: true,
|
|
127
|
+
...terminalOf(range)
|
|
128
|
+
} };
|
|
129
|
+
}
|
|
95
130
|
let messages = [];
|
|
96
131
|
let cursor = range.from;
|
|
97
132
|
let last;
|
|
@@ -138,16 +173,17 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
|
|
|
138
173
|
from: range.from,
|
|
139
174
|
items: yield* decodeMessages(input, address, messages),
|
|
140
175
|
nextOffset: range.nextOffset,
|
|
141
|
-
upToDate: last.upToDate && cursor === range.nextOffset,
|
|
142
|
-
closed:
|
|
176
|
+
upToDate: range.upToDate ?? (last.upToDate && cursor === range.nextOffset),
|
|
177
|
+
closed: range.closed === true
|
|
143
178
|
} };
|
|
144
179
|
});
|
|
145
180
|
/** Read one server page per input in declaration order. */
|
|
146
|
-
const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets) {
|
|
181
|
+
const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets, seen = false) {
|
|
147
182
|
const slices = {};
|
|
148
183
|
let items = 0;
|
|
149
184
|
for (const [name, address] of inputEntries(inputs)) {
|
|
150
|
-
const
|
|
185
|
+
const from = offsets[name] ?? "";
|
|
186
|
+
const read = yield* readOrGone(name, address, from, readSlice(name, address, from), seen);
|
|
151
187
|
slices[name] = read.slice;
|
|
152
188
|
items += read.slice.items.length;
|
|
153
189
|
}
|
|
@@ -159,29 +195,28 @@ const readInputs = Effect.fn("Projection.readInputs")(function* (inputs, offsets
|
|
|
159
195
|
/** Tagged items in declaration order, then stream order within each input. */
|
|
160
196
|
const items = (batch) => {
|
|
161
197
|
const out = [];
|
|
162
|
-
for (const [input, slice] of
|
|
198
|
+
for (const [input, slice] of Record.toEntries(batch)) for (const item of slice.items) out.push({
|
|
163
199
|
input,
|
|
164
200
|
item,
|
|
165
201
|
index: out.length
|
|
166
202
|
});
|
|
167
203
|
return out;
|
|
168
204
|
};
|
|
169
|
-
|
|
170
|
-
//#region src/outputs.ts
|
|
205
|
+
// src/outputs.ts
|
|
171
206
|
/** Resolve routes just like inputs, retaining the route codec and collection names. */
|
|
172
207
|
const resolveOutputs = (outputs, params, inputs) => {
|
|
173
208
|
const streams = addressesOf(outputs, params);
|
|
174
|
-
const ids =
|
|
209
|
+
const ids = Array.map(Record.values(streams), (address) => address.id);
|
|
175
210
|
if (new Set(ids).size !== ids.length) throw new RangeError("Two outputs may not name the same stream");
|
|
176
|
-
const inputIds = new Set(
|
|
177
|
-
if (
|
|
178
|
-
if (
|
|
211
|
+
const inputIds = new Set(Array.map(Record.values(inputs), (address) => address.id));
|
|
212
|
+
if (Array.some(ids, (id) => inputIds.has(id))) throw new RangeError("An output may not name an input stream");
|
|
213
|
+
if (Array.some(Record.values(streams), (address) => !Predicate.isTagged(address, "Json"))) throw new RangeError("Projection outputs require JSON or state routes");
|
|
179
214
|
return streams;
|
|
180
215
|
};
|
|
181
216
|
const collect = (outputs, buffers, emitted) => Effect.gen(function* () {
|
|
182
|
-
for (const [name, entries] of
|
|
217
|
+
for (const [name, entries] of Record.toEntries(emitted)) {
|
|
183
218
|
const output = outputs[name];
|
|
184
|
-
if (!
|
|
219
|
+
if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* new ProjectionFault({
|
|
185
220
|
phase: "process",
|
|
186
221
|
reason: "invalid-output",
|
|
187
222
|
message: `Invalid output array ${name}`
|
|
@@ -225,8 +260,7 @@ const appendPinned = Effect.fn("Projection.appendPinned")(function* (output, wir
|
|
|
225
260
|
StreamBusy: () => pin$1("invalid-output", `Output ${output.id} is busy`)
|
|
226
261
|
}));
|
|
227
262
|
});
|
|
228
|
-
|
|
229
|
-
//#region src/commit/range.ts
|
|
263
|
+
// src/commit/range.ts
|
|
230
264
|
const RangeKey = Symbol.for("@streamsy/projection/internal/Range");
|
|
231
265
|
const extend = (commit) => Object.defineProperty(commit, RangeKey, {
|
|
232
266
|
value: "extend",
|
|
@@ -244,8 +278,7 @@ const inherit = (source, target) => {
|
|
|
244
278
|
const PrepareKey = Symbol.for("@streamsy/projection/internal/Prepare");
|
|
245
279
|
const withPrepare = (commit) => Object.defineProperty(commit, PrepareKey, { value: true });
|
|
246
280
|
const supportsPrepare = (commit) => PrepareKey in commit && commit[PrepareKey] === true;
|
|
247
|
-
|
|
248
|
-
//#region src/commit/model.ts
|
|
281
|
+
// src/commit/model.ts
|
|
249
282
|
const TypeId = "~@streamsy/projection/Commit";
|
|
250
283
|
/** Opaque to Commit authors; the kernel restores the original typed handler error. */
|
|
251
284
|
var HandlerFailed = class extends Schema.TaggedError()("HandlerFailed", { error: Schema.Unknown }) {};
|
|
@@ -265,11 +298,10 @@ const make = (options) => extend({
|
|
|
265
298
|
}
|
|
266
299
|
},
|
|
267
300
|
pipe() {
|
|
268
|
-
return pipeArguments(this, arguments);
|
|
301
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
269
302
|
}
|
|
270
303
|
});
|
|
271
|
-
|
|
272
|
-
//#region src/commit/internal.ts
|
|
304
|
+
// src/commit/internal.ts
|
|
273
305
|
const DetailsKey = Symbol.for("@streamsy/projection/internal/Pending");
|
|
274
306
|
const setDetails = (pending, value) => Object.defineProperty(pending, DetailsKey, { value });
|
|
275
307
|
const detailsOf = (pending) => {
|
|
@@ -286,11 +318,10 @@ const withState = (next, result) => result !== void 0 && "encoded" in result ? {
|
|
|
286
318
|
} : next;
|
|
287
319
|
const beforeRecord = (pending) => Option.getOrElse(pending.loaded.record, () => ({
|
|
288
320
|
...pending.next,
|
|
289
|
-
inputs:
|
|
321
|
+
inputs: Record.fromEntries(Array.map(Record.toEntries(pending.next.inputs), ([name, offset]) => [name, pending.unit.ranges[name]?.from ?? offset]))
|
|
290
322
|
}));
|
|
291
323
|
const settle = (pending, result) => CheckpointStore.use((store) => store.compareAndSet(pending.key, pending.loaded.token, withState(pending.next, result))).pipe(Effect.asVoid);
|
|
292
|
-
|
|
293
|
-
//#region src/commit/checkpoint.ts
|
|
324
|
+
// src/commit/checkpoint.ts
|
|
294
325
|
const checkpoint = make({
|
|
295
326
|
name: "checkpoint",
|
|
296
327
|
guarantee: "exactly-once",
|
|
@@ -298,8 +329,7 @@ const checkpoint = make({
|
|
|
298
329
|
remove,
|
|
299
330
|
apply: (pending) => Effect.flatMap(pending.run, (result) => settle(pending, result))
|
|
300
331
|
});
|
|
301
|
-
|
|
302
|
-
//#region src/transaction.ts
|
|
332
|
+
// src/transaction.ts
|
|
303
333
|
/** The SQL transaction and stream owner used by Commit.transaction. */
|
|
304
334
|
var Transaction = class extends Context.Service()("@streamsy/projection/Transaction") {
|
|
305
335
|
/**
|
|
@@ -321,8 +351,7 @@ var Transaction = class extends Context.Service()("@streamsy/projection/Transact
|
|
|
321
351
|
};
|
|
322
352
|
}));
|
|
323
353
|
};
|
|
324
|
-
|
|
325
|
-
//#region src/commit/transaction.ts
|
|
354
|
+
// src/commit/transaction.ts
|
|
326
355
|
const transaction = withPrepare(make({
|
|
327
356
|
name: "transaction",
|
|
328
357
|
guarantee: "exactly-once",
|
|
@@ -332,7 +361,7 @@ const transaction = withPrepare(make({
|
|
|
332
361
|
const tx = yield* Transaction;
|
|
333
362
|
const store = yield* CheckpointStore;
|
|
334
363
|
const outputs = detailsOf(pending).outputs;
|
|
335
|
-
for (const { address, service } of
|
|
364
|
+
for (const { address, service } of Record.values(outputs)) if (service.owner !== tx.owner) return yield* new ProjectionFault({
|
|
336
365
|
phase: "load",
|
|
337
366
|
reason: "unsupported-composition",
|
|
338
367
|
message: `Output ${address.id} does not share the transaction owner`
|
|
@@ -350,8 +379,8 @@ const transaction = withPrepare(make({
|
|
|
350
379
|
reason: "unsupported-composition",
|
|
351
380
|
message: defect.message
|
|
352
381
|
})) : Effect.die(defect)));
|
|
353
|
-
if (result !== void 0 && "outputs" in result) for (const [name, output] of
|
|
354
|
-
if (!Array
|
|
382
|
+
if (result !== void 0 && "outputs" in result) for (const [name, output] of Record.toEntries(result.outputs)) {
|
|
383
|
+
if (!Array.isReadonlyArrayNonEmpty(output.items)) continue;
|
|
355
384
|
const resolved = outputs[name];
|
|
356
385
|
if (resolved === void 0) return yield* new ProjectionFault({
|
|
357
386
|
phase: "process",
|
|
@@ -371,10 +400,19 @@ const transaction = withPrepare(make({
|
|
|
371
400
|
return yield* Effect.void;
|
|
372
401
|
})
|
|
373
402
|
}));
|
|
374
|
-
|
|
375
|
-
//#region src/commit/producer.ts
|
|
403
|
+
// src/commit/producer.ts
|
|
376
404
|
/** The pinned tuple identity: the params join the id so two parameterisations never share a sequence. */
|
|
377
|
-
const producerId = (id, version, params) => `${id}/v${version}${
|
|
405
|
+
const producerId = (id, version, params) => `${id}/v${version}${Record.keys(params).length === 0 ? "" : `/${canonicalParams(params)}`}`;
|
|
406
|
+
/** The head of one output. A missing output on the checkpoint's owner is created here. */
|
|
407
|
+
const prepareOutput = (output, store) => {
|
|
408
|
+
const { wire, owner: outputOwner } = output.service;
|
|
409
|
+
return wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== ownerOf(store.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({
|
|
410
|
+
phase: "pin",
|
|
411
|
+
reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
412
|
+
message: `Cannot prepare output ${output.address.id}`,
|
|
413
|
+
cause
|
|
414
|
+
})));
|
|
415
|
+
};
|
|
378
416
|
/** The pin write is the last save before the append, so its conflict is a pin failure. */
|
|
379
417
|
const asPin = (fault) => fault.phase === "checkpoint" && fault.reason === "token-conflict" ? new ProjectionFault({
|
|
380
418
|
phase: "pin",
|
|
@@ -393,7 +431,7 @@ const producer = pin(make({
|
|
|
393
431
|
reason: "invalid-record",
|
|
394
432
|
message: "A producer pin must include output sequences"
|
|
395
433
|
});
|
|
396
|
-
for (const [name, position] of
|
|
434
|
+
for (const [name, position] of Record.toEntries(loaded.record.value.adapters.outputs ?? {})) if (position.epoch !== key.generation) return yield* new ProjectionFault({
|
|
397
435
|
phase: "load",
|
|
398
436
|
reason: "stale-epoch",
|
|
399
437
|
message: `Stored epoch ${position.epoch} of ${key.id}/${name} is not generation ${key.generation}`
|
|
@@ -410,40 +448,33 @@ const producer = pin(make({
|
|
|
410
448
|
};
|
|
411
449
|
const { identity, adapters } = before.record;
|
|
412
450
|
const streams = detailsOf(request).outputs;
|
|
413
|
-
const ranges = request.unit.ranges;
|
|
414
451
|
const positions = { ...adapters.outputs };
|
|
415
|
-
for (const [name, position] of
|
|
452
|
+
for (const [name, position] of Record.toEntries(positions)) if (position.epoch !== projection.generation) return yield* new ProjectionFault({
|
|
416
453
|
phase: "load",
|
|
417
454
|
reason: "stale-epoch",
|
|
418
455
|
message: `Stored epoch ${position.epoch} of ${projection.id}/${name} is not generation ${projection.generation}`
|
|
419
456
|
});
|
|
420
457
|
const pending = before.record.pending;
|
|
421
458
|
const result = yield* request.run;
|
|
422
|
-
const processed = { items:
|
|
423
|
-
const seqs = pending === void 0 ?
|
|
424
|
-
for (const name of
|
|
459
|
+
const processed = { items: Record.fromEntries(Array.map(Record.toEntries(result.outputs), ([name, output]) => [name, output.items])) };
|
|
460
|
+
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 ?? {};
|
|
461
|
+
for (const name of Record.keys(seqs)) if (streams[name] === void 0 || (processed.items[name]?.length ?? 0) === 0) return yield* new ProjectionFault({
|
|
425
462
|
phase: "process",
|
|
426
463
|
reason: "invalid-output",
|
|
427
464
|
message: `Cannot reproduce pinned output ${name}`
|
|
428
465
|
});
|
|
429
466
|
if (pending !== void 0) {
|
|
430
|
-
for (const name of
|
|
467
|
+
for (const name of Record.keys(streams)) if ((processed.items[name]?.length ?? 0) > 0 && seqs[name] === void 0) return yield* new ProjectionFault({
|
|
431
468
|
phase: "process",
|
|
432
469
|
reason: "invalid-output",
|
|
433
470
|
message: `Cannot reproduce pinned unit: output ${name} has items that were not pinned`
|
|
434
471
|
});
|
|
435
472
|
}
|
|
436
473
|
let token = before.token;
|
|
437
|
-
if (pending === void 0 &&
|
|
438
|
-
for (const [name, output] of
|
|
474
|
+
if (pending === void 0 && Record.keys(seqs).length > 0) {
|
|
475
|
+
for (const [name, output] of Record.toEntries(streams)) {
|
|
439
476
|
if (seqs[name] === void 0) continue;
|
|
440
|
-
|
|
441
|
-
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({
|
|
442
|
-
phase: "pin",
|
|
443
|
-
reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
444
|
-
message: `Cannot prepare output ${output.address.id}`,
|
|
445
|
-
cause
|
|
446
|
-
})))).closed) return yield* new ProjectionFault({
|
|
477
|
+
if ((yield* prepareOutput(output, owner)).closed) return yield* new ProjectionFault({
|
|
447
478
|
phase: "pin",
|
|
448
479
|
reason: "invalid-output",
|
|
449
480
|
message: `Output ${output.address.id} is closed`
|
|
@@ -459,20 +490,17 @@ const producer = pin(make({
|
|
|
459
490
|
adapters: { outputs: { ...positions } },
|
|
460
491
|
pending: {
|
|
461
492
|
seqs,
|
|
462
|
-
ranges:
|
|
463
|
-
from: range.from,
|
|
464
|
-
nextOffset: range.nextOffset,
|
|
465
|
-
count: detailsOf(request).ranges[name]?.count ?? 0
|
|
466
|
-
}]))
|
|
493
|
+
ranges: detailsOf(request).ranges
|
|
467
494
|
}
|
|
468
495
|
};
|
|
496
|
+
if (before.record.closed !== void 0) Object.assign(pinned, { closed: before.record.closed });
|
|
469
497
|
if (before.record.state !== void 0) Object.assign(pinned, { state: before.record.state });
|
|
470
498
|
token = yield* owner.compareAndSet(projection, before.token, pinned).pipe(Effect.mapError(asPin));
|
|
471
499
|
}
|
|
472
|
-
for (const [name, output] of
|
|
500
|
+
for (const [name, output] of Record.toEntries(streams)) {
|
|
473
501
|
const seq = seqs[name];
|
|
474
502
|
const items = processed.items[name] ?? [];
|
|
475
|
-
if (seq === void 0 || !Array
|
|
503
|
+
if (seq === void 0 || !Array.isReadonlyArrayNonEmpty(items)) continue;
|
|
476
504
|
yield* appendPinned(output.address, output.service.wire, items, {
|
|
477
505
|
producerId: producerId(projection.id, projection.version, projection.params),
|
|
478
506
|
producerEpoch: projection.generation,
|
|
@@ -486,7 +514,7 @@ const producer = pin(make({
|
|
|
486
514
|
const record = {
|
|
487
515
|
identity,
|
|
488
516
|
inputs: request.next.inputs,
|
|
489
|
-
adapters:
|
|
517
|
+
adapters: Record.keys(positions).length === 0 ? adapters : { outputs: positions }
|
|
490
518
|
};
|
|
491
519
|
yield* owner.compareAndSet(projection, token, withState({
|
|
492
520
|
...request.next,
|
|
@@ -495,8 +523,7 @@ const producer = pin(make({
|
|
|
495
523
|
return yield* Effect.void;
|
|
496
524
|
})
|
|
497
525
|
}));
|
|
498
|
-
|
|
499
|
-
//#region src/commit/at-least-once.ts
|
|
526
|
+
// src/commit/at-least-once.ts
|
|
500
527
|
const atLeastOnce = pin(make({
|
|
501
528
|
name: "atLeastOnce",
|
|
502
529
|
guarantee: "at-least-once",
|
|
@@ -513,9 +540,8 @@ const atLeastOnce = pin(make({
|
|
|
513
540
|
yield* store.compareAndSet(pending.key, token, pending.next);
|
|
514
541
|
})
|
|
515
542
|
}));
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
const withCompensation = dual(2, (self, f) => inherit(self, make({
|
|
543
|
+
// src/commit/compensation.ts
|
|
544
|
+
const withCompensation = Function.dual(2, (self, f) => inherit(self, make({
|
|
519
545
|
...self,
|
|
520
546
|
apply: (pending) => Effect.suspend(() => {
|
|
521
547
|
let completed = Option.none();
|
|
@@ -528,8 +554,7 @@ const withCompensation = dual(2, (self, f) => inherit(self, make({
|
|
|
528
554
|
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)))));
|
|
529
555
|
})
|
|
530
556
|
})));
|
|
531
|
-
|
|
532
|
-
//#region src/commit.ts
|
|
557
|
+
// src/commit.ts
|
|
533
558
|
var commit_exports = /* @__PURE__ */ __exportAll({
|
|
534
559
|
Accumulated: () => Accumulated,
|
|
535
560
|
Emitted: () => Emitted,
|
|
@@ -543,8 +568,7 @@ var commit_exports = /* @__PURE__ */ __exportAll({
|
|
|
543
568
|
transaction: () => transaction,
|
|
544
569
|
withCompensation: () => withCompensation
|
|
545
570
|
});
|
|
546
|
-
|
|
547
|
-
//#region src/state.ts
|
|
571
|
+
// src/state.ts
|
|
548
572
|
const bindState = (definition, params) => {
|
|
549
573
|
const initial = definition.initial;
|
|
550
574
|
return {
|
|
@@ -570,13 +594,12 @@ const encodeState = (key, schema, value) => Schema.encodeEffect(Schema.fromJsonS
|
|
|
570
594
|
message: `Cannot encode state for ${key.id}`,
|
|
571
595
|
cause
|
|
572
596
|
})));
|
|
573
|
-
|
|
574
|
-
//#region src/step.ts
|
|
597
|
+
// src/step.ts
|
|
575
598
|
/** One adapter invocation is one unit. Per-entry variants thread state and preserve order. */
|
|
576
599
|
const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepared) => Effect.gen(function* () {
|
|
577
600
|
if (kind === "process") return yield* Effect.asVoid(handler(batch, unit, prepared));
|
|
578
601
|
let value = state === void 0 ? void 0 : yield* currentState(key, state, encoded);
|
|
579
|
-
const buffers =
|
|
602
|
+
const buffers = Record.fromEntries(Array.map(Record.keys(streams), (name) => [name, []]));
|
|
580
603
|
const steps = kind === "mapAccumBatch" ? [batch] : items(batch);
|
|
581
604
|
for (const entry of steps) {
|
|
582
605
|
const step = kind === "emit" ? handler(entry, unit) : handler(value, entry, unit);
|
|
@@ -588,7 +611,7 @@ const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepare
|
|
|
588
611
|
yield* collect(streams, buffers, emitted);
|
|
589
612
|
}
|
|
590
613
|
}
|
|
591
|
-
const batchOutputs =
|
|
614
|
+
const batchOutputs = Record.fromEntries(Array.map(Record.toEntries(streams), ([name, address]) => [name, {
|
|
592
615
|
address,
|
|
593
616
|
items: buffers[name] ?? []
|
|
594
617
|
}]));
|
|
@@ -603,19 +626,18 @@ const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepare
|
|
|
603
626
|
outputs: batchOutputs
|
|
604
627
|
});
|
|
605
628
|
});
|
|
606
|
-
|
|
607
|
-
//#region src/declaration.ts
|
|
629
|
+
// src/declaration.ts
|
|
608
630
|
const isDeclaration = (input) => "at" in input;
|
|
609
631
|
const encodeParams = (id, codecs, params) => {
|
|
610
632
|
const values = params;
|
|
611
|
-
return
|
|
633
|
+
return Record.fromEntries(Array.map(Record.toEntries(codecs), ([name, codec]) => {
|
|
612
634
|
const encoded = Schema.encodeOption(codec)(values[name]);
|
|
613
635
|
if (Option.isNone(encoded)) throw new RangeError(`Cannot encode projection ${id} parameter ${name}`);
|
|
614
636
|
return [name, encoded.value];
|
|
615
637
|
}));
|
|
616
638
|
};
|
|
617
639
|
const addressesOf = (inputs, params) => {
|
|
618
|
-
return
|
|
640
|
+
return Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, input]) => [name, isDeclaration(input) ? input.at(params) : input]));
|
|
619
641
|
};
|
|
620
642
|
const declare = (definition, bind) => {
|
|
621
643
|
const version = definition.version ?? 1;
|
|
@@ -625,6 +647,7 @@ const declare = (definition, bind) => {
|
|
|
625
647
|
version,
|
|
626
648
|
generation,
|
|
627
649
|
params: definition.params,
|
|
650
|
+
inputs: definition.inputs,
|
|
628
651
|
at: (params) => bind({
|
|
629
652
|
id: definition.id,
|
|
630
653
|
version,
|
|
@@ -633,7 +656,7 @@ const declare = (definition, bind) => {
|
|
|
633
656
|
decoded: params
|
|
634
657
|
}),
|
|
635
658
|
parse: (id) => {
|
|
636
|
-
for (const input of
|
|
659
|
+
for (const input of Record.values(definition.inputs)) {
|
|
637
660
|
if (!isDeclaration(input)) continue;
|
|
638
661
|
const parsed = input.parse(id);
|
|
639
662
|
if (Option.isSome(parsed)) return Option.some(parsed.value);
|
|
@@ -660,53 +683,80 @@ const build = (kind, definition) => {
|
|
|
660
683
|
};
|
|
661
684
|
});
|
|
662
685
|
};
|
|
663
|
-
|
|
664
|
-
//#region src/fold.ts
|
|
686
|
+
// src/fold.ts
|
|
665
687
|
function fold(definition) {
|
|
666
688
|
return build("fold", definition);
|
|
667
689
|
}
|
|
668
|
-
|
|
669
|
-
//#region src/process.ts
|
|
690
|
+
// src/process.ts
|
|
670
691
|
function process(definition) {
|
|
671
692
|
return build("process", definition);
|
|
672
693
|
}
|
|
673
|
-
|
|
674
|
-
//#region src/emit.ts
|
|
694
|
+
// src/emit.ts
|
|
675
695
|
function emit(definition) {
|
|
676
696
|
return build("emit", definition);
|
|
677
697
|
}
|
|
678
|
-
|
|
679
|
-
//#region src/map-accum.ts
|
|
698
|
+
// src/map-accum.ts
|
|
680
699
|
function mapAccum(definition) {
|
|
681
700
|
return build("mapAccum", definition);
|
|
682
701
|
}
|
|
683
702
|
function mapAccumBatch(definition) {
|
|
684
703
|
return build("mapAccumBatch", definition);
|
|
685
704
|
}
|
|
686
|
-
|
|
687
|
-
|
|
705
|
+
// src/forget.ts
|
|
706
|
+
/**
|
|
707
|
+
* Deletes the record. Stop the follower first, or use a new generation.
|
|
708
|
+
* Delete stream outputs first, because forgetting restarts their producer sequences.
|
|
709
|
+
*/
|
|
710
|
+
const forget = (projection) => Effect.gen(function* () {
|
|
711
|
+
if (projection.commit.remove === void 0) return yield* new ProjectionFault({
|
|
712
|
+
phase: "checkpoint",
|
|
713
|
+
reason: "unsupported-composition",
|
|
714
|
+
message: "This Commit does not support forgetting"
|
|
715
|
+
});
|
|
716
|
+
yield* projection.commit.remove(projection);
|
|
717
|
+
return yield* Effect.void;
|
|
718
|
+
});
|
|
719
|
+
// src/snapshot.ts
|
|
688
720
|
/** Internal: the offsets of a record, typed by the declared inputs. */
|
|
689
721
|
const offsetsOf = (record) => record.inputs;
|
|
690
722
|
/**
|
|
723
|
+
* Internal: decodes one encoded state field. The result is the declared initial value
|
|
724
|
+
* when no state is stored, and `undefined` when the declaration has no `state:`.
|
|
725
|
+
*/
|
|
726
|
+
const stateOf = Effect.fnUntraced(function* (projection, encoded) {
|
|
727
|
+
const declared = projection.state;
|
|
728
|
+
const stored = declared === void 0 ? Option.none() : yield* decodeState(projection, declared.schema, Option.fromUndefinedOr(encoded));
|
|
729
|
+
return declared === void 0 ? void 0 : Option.getOrElse(stored, declared.initial);
|
|
730
|
+
});
|
|
731
|
+
/**
|
|
691
732
|
* Reads the state and offsets from one checkpoint record, so the state
|
|
692
733
|
* always matches the offsets. Before the first unit, the state is the declared initial
|
|
693
734
|
* value and every offset is the start of its input.
|
|
694
735
|
*/
|
|
695
736
|
const read = Effect.fn("Projection.read")(function* (projection) {
|
|
696
|
-
const declared = projection.state;
|
|
697
737
|
const restored = yield* restore(projection, projection.commit);
|
|
698
|
-
const encoded = Option.fromUndefinedOr(restored.record.state);
|
|
699
|
-
const stored = declared === void 0 ? Option.none() : yield* decodeState(projection, declared.schema, encoded);
|
|
700
738
|
return {
|
|
701
|
-
state:
|
|
739
|
+
state: yield* stateOf(projection, restored.record.state),
|
|
702
740
|
offsets: offsetsOf(restored.record)
|
|
703
741
|
};
|
|
704
742
|
});
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
743
|
+
// src/run.ts
|
|
744
|
+
/**
|
|
745
|
+
* Internal: one pass that also returns the encoded state it committed, or the stored
|
|
746
|
+
* state when it found no input.
|
|
747
|
+
*/
|
|
748
|
+
const step = Effect.fn("Projection.pass")(function* (projection) {
|
|
709
749
|
const before = yield* restore(projection, projection.commit);
|
|
750
|
+
if (before.record.ended) {
|
|
751
|
+
yield* forget(projection);
|
|
752
|
+
return {
|
|
753
|
+
status: "source-closed",
|
|
754
|
+
units: 0,
|
|
755
|
+
items: 0,
|
|
756
|
+
offsets: offsetsOf(before.record),
|
|
757
|
+
encoded: before.record.state
|
|
758
|
+
};
|
|
759
|
+
}
|
|
710
760
|
const pending = before.record.pending;
|
|
711
761
|
if (pending !== void 0 && !isPinned(projection.commit)) return yield* new ProjectionFault({
|
|
712
762
|
phase: "load",
|
|
@@ -728,30 +778,40 @@ const pass = Effect.fn("Projection.pass")(function* (projection) {
|
|
|
728
778
|
}
|
|
729
779
|
batch = slices;
|
|
730
780
|
} else {
|
|
731
|
-
const read = yield* readInputs(projection.inputs, before.record.inputs);
|
|
781
|
+
const read = yield* readInputs(projection.inputs, before.record.inputs, Option.isSome(before.loaded.record));
|
|
732
782
|
batch = read.slices;
|
|
733
783
|
count = read.items;
|
|
734
|
-
|
|
735
|
-
|
|
784
|
+
const terminal = Array.some(Record.toEntries(batch), ([name, slice]) => slice.gone === true || slice.closed && slice.upToDate && !before.record.closed?.[name]);
|
|
785
|
+
if (count === 0 && !terminal) return {
|
|
786
|
+
status: Array.every(Record.values(batch), (slice) => slice.closed) ? "source-closed" : "caught-up",
|
|
736
787
|
units: 0,
|
|
737
788
|
items: 0,
|
|
738
|
-
offsets: offsetsOf(before.record)
|
|
789
|
+
offsets: offsetsOf(before.record),
|
|
790
|
+
encoded: before.record.state
|
|
739
791
|
};
|
|
740
792
|
}
|
|
793
|
+
const gone = Array.some(Record.values(batch), (slice) => slice.gone === true);
|
|
741
794
|
const ranges = pending?.ranges ?? rangesOf(batch);
|
|
742
795
|
const unit = unitOf(projection.id, projection.version, projection.generation, projection.params, ranges);
|
|
743
796
|
const { pending: _pending, ...record } = before.record;
|
|
797
|
+
const closed = { ...record.closed };
|
|
798
|
+
for (const [name, slice] of Record.toEntries(batch)) if (slice.closed && slice.upToDate) closed[name] = true;
|
|
744
799
|
const next = {
|
|
745
800
|
...record,
|
|
746
|
-
inputs: advance(record.inputs, ranges)
|
|
801
|
+
inputs: advance(record.inputs, ranges),
|
|
802
|
+
closed
|
|
747
803
|
};
|
|
804
|
+
if (gone) Object.assign(next, { ended: true });
|
|
748
805
|
const outputs = {};
|
|
749
|
-
for (const [name, address] of
|
|
806
|
+
for (const [name, address] of Record.toEntries(projection.streams ?? {})) outputs[name] = {
|
|
750
807
|
address,
|
|
751
808
|
service: yield* address.stream
|
|
752
809
|
};
|
|
753
810
|
let prepared;
|
|
754
|
-
|
|
811
|
+
let result;
|
|
812
|
+
const run = Effect.suspend(() => projection.process(batch, unit, before.record.state, prepared)).pipe(Effect.tap((value) => Effect.sync(() => {
|
|
813
|
+
result = value;
|
|
814
|
+
})), Effect.mapError((error) => new HandlerFailed({ error })));
|
|
755
815
|
const prepare = projection.prepare === void 0 ? void 0 : Effect.suspend(() => projection.prepare(batch, unit)).pipe(Effect.tap((value) => Effect.sync(() => {
|
|
756
816
|
prepared = value;
|
|
757
817
|
})), Effect.asVoid, Effect.mapError((error) => new HandlerFailed({ error })));
|
|
@@ -764,67 +824,85 @@ const pass = Effect.fn("Projection.pass")(function* (projection) {
|
|
|
764
824
|
}, {
|
|
765
825
|
outputs,
|
|
766
826
|
prepare,
|
|
767
|
-
ranges:
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
827
|
+
ranges: Record.fromEntries(Array.map(Record.toEntries(ranges), ([name, range]) => [name, {
|
|
828
|
+
...range,
|
|
829
|
+
count: batch[name]?.items.length ?? 0,
|
|
830
|
+
closed: batch[name]?.closed ?? false,
|
|
831
|
+
upToDate: batch[name]?.upToDate ?? false
|
|
771
832
|
}]))
|
|
772
833
|
});
|
|
773
834
|
yield* projection.commit.apply(request).pipe(Effect.catchTag("HandlerFailed", (failure) => Effect.fail(failure.error)));
|
|
835
|
+
const stored = withState(next, result);
|
|
836
|
+
if (gone) yield* forget(projection);
|
|
774
837
|
return {
|
|
775
|
-
status: "progress",
|
|
838
|
+
status: gone ? "source-closed" : "progress",
|
|
776
839
|
units: 1,
|
|
777
840
|
items: count,
|
|
778
|
-
offsets: offsetsOf(next)
|
|
841
|
+
offsets: offsetsOf(next),
|
|
842
|
+
encoded: stored.state
|
|
779
843
|
};
|
|
780
844
|
});
|
|
781
|
-
/**
|
|
782
|
-
const
|
|
783
|
-
|
|
845
|
+
/** Restore and adapt one input unit; the Commit owns every write. */
|
|
846
|
+
const pass = (projection) => Effect.map(step(projection), ({ encoded: _encoded, ...result }) => result);
|
|
847
|
+
/** Internal: repeats pass until caught up, closed, or limited. The caller validates options. */
|
|
848
|
+
const catchUp = Effect.fnUntraced(function* (projection, options) {
|
|
784
849
|
const cap = options.limit ?? Number.POSITIVE_INFINITY;
|
|
785
850
|
let units = 0;
|
|
786
851
|
let items = 0;
|
|
787
|
-
let
|
|
852
|
+
let offsets;
|
|
853
|
+
let encoded;
|
|
788
854
|
do {
|
|
789
|
-
result = yield*
|
|
855
|
+
const result = yield* step(projection);
|
|
790
856
|
units += result.units;
|
|
791
857
|
items += result.items;
|
|
858
|
+
offsets = result.offsets;
|
|
859
|
+
encoded = result.encoded;
|
|
792
860
|
if (result.status !== "progress") return {
|
|
793
|
-
|
|
861
|
+
status: result.status,
|
|
794
862
|
units,
|
|
795
|
-
items
|
|
863
|
+
items,
|
|
864
|
+
offsets,
|
|
865
|
+
encoded
|
|
796
866
|
};
|
|
797
867
|
} while (units < cap);
|
|
798
868
|
return {
|
|
799
|
-
...result,
|
|
800
869
|
status: "limit-reached",
|
|
801
870
|
units,
|
|
802
|
-
items
|
|
871
|
+
items,
|
|
872
|
+
offsets,
|
|
873
|
+
encoded
|
|
803
874
|
};
|
|
804
875
|
});
|
|
805
|
-
|
|
806
|
-
|
|
876
|
+
/** Internal: a cycle with its state decoded once. It reads no checkpoint. */
|
|
877
|
+
const progressOf = (projection, { encoded, ...cycle }) => Effect.map(stateOf(projection, encoded), (state) => ({
|
|
878
|
+
...cycle,
|
|
879
|
+
state
|
|
880
|
+
}));
|
|
881
|
+
/**
|
|
882
|
+
* Repeats pass until caught up, closed, or limited, then decodes the state of the last
|
|
883
|
+
* pass once. After a gone input, the result holds the state that the final unit
|
|
884
|
+
* committed, although the kernel then deletes the record. Use one writer per key.
|
|
885
|
+
*/
|
|
886
|
+
const run = Effect.fn("Projection.run")(function* (projection, options = {}) {
|
|
887
|
+
yield* validateOptions(options);
|
|
888
|
+
return yield* progressOf(projection, yield* catchUp(projection, options));
|
|
889
|
+
});
|
|
890
|
+
// src/retry.ts
|
|
807
891
|
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))))));
|
|
808
|
-
/** Default
|
|
892
|
+
/** Default retry for following and attached runners; an explicit options.retry takes precedence. */
|
|
809
893
|
const ProjectionRetry = Context.Reference("@streamsy/projection/ProjectionRetry", { defaultValue: () => defaultRetry });
|
|
810
|
-
|
|
811
|
-
//#region src/follow.ts
|
|
894
|
+
// src/follow.ts
|
|
812
895
|
/**
|
|
813
896
|
* One wake hint per input; the messages are discarded because the next run is
|
|
814
897
|
* authoritative. Only the response cursor is kept, so the next hint on that
|
|
815
898
|
* input echoes it. A closed input answers `readNext` at once, so a closed and
|
|
816
899
|
* drained input parks for the interval instead of waking every cycle; the
|
|
817
|
-
* open inputs, and the interval itself, decide when the next run happens.
|
|
900
|
+
* open inputs, and the interval itself, decide when the next run happens. A
|
|
901
|
+
* gone input wakes the next run so it can end the binding.
|
|
818
902
|
*/
|
|
819
|
-
const hint = Effect.fn("Projection.
|
|
903
|
+
const hint = Effect.fn("Projection.hint")(function* (input, address, offset, interval, cursors) {
|
|
820
904
|
const cursor = (yield* Ref.get(cursors))[input];
|
|
821
905
|
const { wire: reader } = yield* address.stream;
|
|
822
|
-
const historyUnavailable = () => new ProjectionFault({
|
|
823
|
-
phase: "read",
|
|
824
|
-
reason: "history-unavailable",
|
|
825
|
-
input,
|
|
826
|
-
message: `Required history of ${address.id} after ${offset} is unavailable`
|
|
827
|
-
});
|
|
828
906
|
const storageFailure = (cause) => new ProjectionFault({
|
|
829
907
|
phase: "read",
|
|
830
908
|
reason: "storage-failure",
|
|
@@ -846,8 +924,8 @@ const hint = Effect.fn("Projection.wake")(function* (input, address, offset, int
|
|
|
846
924
|
message: cause.message,
|
|
847
925
|
cause
|
|
848
926
|
}),
|
|
849
|
-
StreamNotFound: () =>
|
|
850
|
-
StreamGone: () =>
|
|
927
|
+
StreamNotFound: () => Effect.void,
|
|
928
|
+
StreamGone: () => Effect.void,
|
|
851
929
|
NotSupported: (error) => new ProjectionFault({
|
|
852
930
|
phase: "read",
|
|
853
931
|
reason: "unsupported-composition",
|
|
@@ -859,12 +937,21 @@ const hint = Effect.fn("Projection.wake")(function* (input, address, offset, int
|
|
|
859
937
|
}), Effect.timeoutOption(interval), Effect.asVoid);
|
|
860
938
|
});
|
|
861
939
|
/**
|
|
862
|
-
*
|
|
863
|
-
*
|
|
864
|
-
*
|
|
865
|
-
*
|
|
940
|
+
* Follows a projection as a pull stream. Each element is one committed cycle: the
|
|
941
|
+
* state and offsets that the last pass left, plus the units and items of the cycle.
|
|
942
|
+
*
|
|
943
|
+
* To run the stream is to be the writer, so run one `follow` stream per key. The next
|
|
944
|
+
* cycle runs only when the consumer pulls, so a slow consumer gets one element that
|
|
945
|
+
* covers all the input that arrived meanwhile. The stream emits after the first cycle,
|
|
946
|
+
* after each cycle that commits a unit or reaches `limit`, and after the last cycle
|
|
947
|
+
* when every input is closed or an input is gone; then it ends. After a gone input, the
|
|
948
|
+
* last element holds the state that the final unit committed, and the kernel then
|
|
949
|
+
* deletes the record. A wake that finds no input emits nothing.
|
|
950
|
+
* Options are checked at the first pull. On HTTP backends a parked hint is cancelled
|
|
951
|
+
* and replaced once per `repairIntervalMs` until an input changes. One
|
|
952
|
+
* `Projection.follow` span covers the whole stream.
|
|
866
953
|
*/
|
|
867
|
-
const follow =
|
|
954
|
+
const follow = (projection, options = {}) => Stream.unwrap(Effect.gen(function* () {
|
|
868
955
|
yield* validateOptions(options);
|
|
869
956
|
const interval = options.repairIntervalMs ?? 3e4;
|
|
870
957
|
if (!Number.isSafeInteger(interval) || interval <= 0) return yield* new ProjectionFault({
|
|
@@ -873,14 +960,167 @@ const follow = Effect.fn("Projection.follow")(function* (projection, options = {
|
|
|
873
960
|
message: "repairIntervalMs must be a positive safe integer"
|
|
874
961
|
});
|
|
875
962
|
const cursors = yield* Ref.make({});
|
|
876
|
-
const
|
|
877
|
-
|
|
963
|
+
const schedule = (options.retry ?? (yield* ProjectionRetry)).pipe(Schedule.tap(({ input }) => Schema.is(ProjectionFault)(input) && input.retryable ? Effect.logWarning("Projection.follow retry", input) : Effect.void));
|
|
964
|
+
const retrying = (effect) => Effect.retry(effect, {
|
|
878
965
|
while: (fault) => Schema.is(ProjectionFault)(fault) && fault.retryable,
|
|
879
|
-
schedule
|
|
880
|
-
})
|
|
966
|
+
schedule
|
|
967
|
+
});
|
|
968
|
+
const wake = (offsets) => Effect.raceAllFirst(Array.map(inputEntries(projection.inputs), ([name, address]) => hint(name, address, offsets[name] ?? ZERO_OFFSET, interval, cursors)));
|
|
969
|
+
/**
|
|
970
|
+
* One cycle, retried on a retryable fault. When it follows a caught-up cycle it
|
|
971
|
+
* first waits for a hint; a retry after a failed wait runs at once.
|
|
972
|
+
*/
|
|
973
|
+
const cycle = (previous) => {
|
|
974
|
+
let waiting = previous?.status === "caught-up";
|
|
975
|
+
return retrying(Effect.suspend(() => {
|
|
976
|
+
const parked = waiting && previous !== void 0;
|
|
977
|
+
waiting = false;
|
|
978
|
+
return parked ? wake(previous.offsets).pipe(Effect.andThen(catchUp(projection, options))) : catchUp(projection, options);
|
|
979
|
+
}));
|
|
980
|
+
};
|
|
981
|
+
/** Runs cycles until one must be emitted: the first, a commit, a limit, or the close. */
|
|
982
|
+
const next = Effect.fnUntraced(function* (previous) {
|
|
983
|
+
let result = yield* cycle(previous);
|
|
984
|
+
if (previous === void 0) return result;
|
|
985
|
+
while (result.status === "caught-up" && result.units === 0) result = yield* cycle(result);
|
|
986
|
+
return result;
|
|
987
|
+
});
|
|
988
|
+
return Stream.unfold(void 0, (previous) => Effect.gen(function* () {
|
|
989
|
+
if (previous?.status === "source-closed") return void 0;
|
|
990
|
+
const result = yield* next(previous);
|
|
991
|
+
return [yield* progressOf(projection, result), result];
|
|
992
|
+
}));
|
|
993
|
+
})).pipe(Stream.withSpan("Projection.follow"));
|
|
994
|
+
/**
|
|
995
|
+
* The binding of a written stream id, if the projection reads that id.
|
|
996
|
+
*
|
|
997
|
+
* The rule: each input must give every projection param, so that one id picks
|
|
998
|
+
* one binding. A declaration input with a template is checked here and throws a
|
|
999
|
+
* RangeError. A custom route has no template, so an id whose parse misses a
|
|
1000
|
+
* param is skipped. A fixed address triggers only a projection with no params.
|
|
1001
|
+
*/
|
|
1002
|
+
const matcher = (declaration) => {
|
|
1003
|
+
const names = Record.keys(declaration.params);
|
|
1004
|
+
const inputs = Record.toEntries(declaration.inputs);
|
|
1005
|
+
for (const [name, input] of inputs) {
|
|
1006
|
+
const given = isDeclaration(input) ? input.template.length === 0 ? names : compileSegments(input.template).names : [];
|
|
1007
|
+
const missing = Array.filter(names, (param) => !given.includes(param));
|
|
1008
|
+
if (missing.length > 0) throw new RangeError(`Projection ${declaration.id} cannot attach: input ${name} does not give param ${Array.join(missing, ", ")}`);
|
|
1009
|
+
}
|
|
1010
|
+
const bound = (params) => {
|
|
1011
|
+
const binding = declaration.at(params);
|
|
1012
|
+
return Option.some([canonicalParams(binding.params), binding]);
|
|
1013
|
+
};
|
|
1014
|
+
return (id) => {
|
|
1015
|
+
for (const [, input] of inputs) {
|
|
1016
|
+
if (!isDeclaration(input)) {
|
|
1017
|
+
if (input.id === id) return bound({});
|
|
1018
|
+
continue;
|
|
1019
|
+
}
|
|
1020
|
+
const parsed = input.parse(id);
|
|
1021
|
+
if (Option.isNone(parsed)) continue;
|
|
1022
|
+
const params = parsed.value;
|
|
1023
|
+
if (Array.every(names, (name) => name in params)) return bound(params);
|
|
1024
|
+
}
|
|
1025
|
+
return Option.none();
|
|
1026
|
+
};
|
|
1027
|
+
};
|
|
1028
|
+
/**
|
|
1029
|
+
* A binding that faults with `history-unavailable` on an input whose head is
|
|
1030
|
+
* absent can never run: its source is gone, and an id never returns. With a
|
|
1031
|
+
* checkpoint, `readOrGone` turns this into a `gone` unit, so only a binding
|
|
1032
|
+
* with no checkpoint reaches here. Any other head answer keeps the fault.
|
|
1033
|
+
*/
|
|
1034
|
+
const sourceGone = (inputs, cause) => Effect.gen(function* () {
|
|
1035
|
+
const fault = Cause.findErrorOption(cause).pipe(Option.filter((error) => Schema.is(ProjectionFault)(error) && error.reason === "history-unavailable"));
|
|
1036
|
+
if (Option.isNone(fault) || fault.value.input === void 0) return false;
|
|
1037
|
+
const input = fault.value.input;
|
|
1038
|
+
const address = Array.findFirst(inputEntries(inputs), ([name]) => name === input);
|
|
1039
|
+
if (Option.isNone(address)) return false;
|
|
1040
|
+
const { wire } = yield* address.value[1].stream;
|
|
1041
|
+
return yield* wire.head(address.value[1].id).pipe(Effect.as(false), Effect.catchTags({
|
|
1042
|
+
StreamNotFound: () => Effect.succeed(true),
|
|
1043
|
+
StreamGone: () => Effect.succeed(true)
|
|
1044
|
+
}), Effect.orElseSucceed(() => false));
|
|
881
1045
|
});
|
|
882
|
-
|
|
883
|
-
|
|
1046
|
+
/**
|
|
1047
|
+
* One scoped commit subscription and pending set, shared by the two host
|
|
1048
|
+
* adapters. The subscription exists when this effect returns, so a commit
|
|
1049
|
+
* after that point always marks its binding.
|
|
1050
|
+
*/
|
|
1051
|
+
const runnerOf = (declaration, limit = 100) => {
|
|
1052
|
+
if (!Number.isSafeInteger(limit) || limit <= 0) throw new RangeError("Projection.attach limit must be a positive safe integer");
|
|
1053
|
+
const match = matcher(declaration);
|
|
1054
|
+
return Effect.gen(function* () {
|
|
1055
|
+
const committed = yield* (yield* Storage).committed;
|
|
1056
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1057
|
+
const add = (ids) => {
|
|
1058
|
+
for (const id of ids) {
|
|
1059
|
+
const found = match(id);
|
|
1060
|
+
if (Option.isSome(found)) pending.set(found.value[0], found.value[1]);
|
|
1061
|
+
}
|
|
1062
|
+
};
|
|
1063
|
+
const absorb = Effect.map(PubSub.takeUpTo(committed, Number.POSITIVE_INFINITY), Array.forEach(add));
|
|
1064
|
+
return {
|
|
1065
|
+
next: Effect.gen(function* () {
|
|
1066
|
+
yield* absorb;
|
|
1067
|
+
return pending.size > 0 ? Option.some(yield* Clock.currentTimeMillis) : Option.none();
|
|
1068
|
+
}),
|
|
1069
|
+
wait: Effect.gen(function* () {
|
|
1070
|
+
yield* absorb;
|
|
1071
|
+
if (pending.size === 0) add(yield* PubSub.take(committed));
|
|
1072
|
+
}),
|
|
1073
|
+
drain: Effect.fn("Projection.drain")(function* () {
|
|
1074
|
+
yield* absorb;
|
|
1075
|
+
let failure;
|
|
1076
|
+
for (const [key, binding] of Array.fromIterable(pending)) {
|
|
1077
|
+
pending.delete(key);
|
|
1078
|
+
const exit = yield* Effect.exit(run(binding, { limit }));
|
|
1079
|
+
if (Exit.isSuccess(exit) && exit.value.status !== "limit-reached") continue;
|
|
1080
|
+
if (Exit.isFailure(exit) && (yield* sourceGone(binding.inputs, exit.cause))) {
|
|
1081
|
+
yield* Effect.logWarning(`Projection ${declaration.id} dropped binding ${key}: its source was removed before its first run`);
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
pending.set(key, binding);
|
|
1085
|
+
if (Exit.isFailure(exit)) failure ??= exit.cause;
|
|
1086
|
+
}
|
|
1087
|
+
yield* absorb;
|
|
1088
|
+
if (failure !== void 0) return yield* Effect.failCause(failure);
|
|
1089
|
+
return { more: pending.size > 0 };
|
|
1090
|
+
})()
|
|
1091
|
+
};
|
|
1092
|
+
});
|
|
1093
|
+
};
|
|
1094
|
+
// src/attach.ts
|
|
1095
|
+
/**
|
|
1096
|
+
* Run a projection whenever a local commit writes one of its inputs. The layer
|
|
1097
|
+
* subscribes to `Storage.committed` when it is built, so build it with the
|
|
1098
|
+
* storage layer and before the app writes. For each written id, the input's
|
|
1099
|
+
* `parse` gives the params, and the runner runs `projection.at(params)`.
|
|
1100
|
+
*
|
|
1101
|
+
* Use it on long-lived hosts (Bun, Node). On a Cloudflare object, use
|
|
1102
|
+
* `ProjectionWakeup.attach(projection)`.
|
|
1103
|
+
*
|
|
1104
|
+
* The set of bindings with work lives in memory. A crash after a commit and
|
|
1105
|
+
* before the run leaves that binding late until its source gets its next write.
|
|
1106
|
+
* Inputs on another owner never commit here, so they never trigger. Do not run
|
|
1107
|
+
* an attached binding under `Projection.follow` too: use one writer per key.
|
|
1108
|
+
*
|
|
1109
|
+
* ```ts
|
|
1110
|
+
* const app = Layer.mergeAll(Api, Projection.attach(filesWake)).pipe(
|
|
1111
|
+
* Layer.provideMerge(BunStorage.layer(streams, { path })),
|
|
1112
|
+
* );
|
|
1113
|
+
* ```
|
|
1114
|
+
*/
|
|
1115
|
+
const attach$1 = (projection, options = {}) => {
|
|
1116
|
+
const runner = runnerOf(projection, options.limit);
|
|
1117
|
+
return Layer.effectDiscard(Effect.gen(function* () {
|
|
1118
|
+
const { wait, drain } = yield* runner;
|
|
1119
|
+
const retry = options.retry ?? (yield* ProjectionRetry);
|
|
1120
|
+
yield* wait.pipe(Effect.andThen(drain.pipe(Effect.tapError((error) => Effect.logError(`Projection.attach ${projection.id} failed`, error)), Effect.retry(retry))), Effect.repeat(Schedule.forever), Effect.withSpan("Projection.attach"), Effect.forkScoped);
|
|
1121
|
+
}));
|
|
1122
|
+
};
|
|
1123
|
+
// src/current.ts
|
|
884
1124
|
/**
|
|
885
1125
|
* Folds the checkpoint and input tail in memory, without locks or writes.
|
|
886
1126
|
* Includes entries appended before the call. A growing input can delay completion.
|
|
@@ -905,8 +1145,7 @@ const current = Effect.fn("Projection.current")(function* (projection) {
|
|
|
905
1145
|
offsets = advance(offsets, ranges);
|
|
906
1146
|
}
|
|
907
1147
|
});
|
|
908
|
-
|
|
909
|
-
//#region src/decide.ts
|
|
1148
|
+
// src/decide.ts
|
|
910
1149
|
/** Up to three retries after a lost race, so at most four appends per call. */
|
|
911
1150
|
const defaultDecideRetry = Schedule.recurs(3);
|
|
912
1151
|
/**
|
|
@@ -919,7 +1158,7 @@ const decide = Effect.fn("Projection.decide")(function* (projection, spec) {
|
|
|
919
1158
|
const snapshot = yield* current(projection);
|
|
920
1159
|
const offset = snapshot.offsets[spec.input];
|
|
921
1160
|
const { value, items } = yield* spec.decide(snapshot);
|
|
922
|
-
if (!isReadonlyArrayNonEmpty(items)) return {
|
|
1161
|
+
if (!Array.isReadonlyArrayNonEmpty(items)) return {
|
|
923
1162
|
value,
|
|
924
1163
|
offset,
|
|
925
1164
|
appended: false
|
|
@@ -957,24 +1196,57 @@ const retryLostRace = Effect.fnUntraced(function* (attempt, schedule) {
|
|
|
957
1196
|
return yield* Effect.fromResult(outcome);
|
|
958
1197
|
});
|
|
959
1198
|
const isOffsetMismatch = (error) => Predicate.isTagged(error, "OffsetMismatch");
|
|
960
|
-
|
|
961
|
-
|
|
1199
|
+
// src/wake.ts
|
|
1200
|
+
const row = (stream, offset, closed) => DurableState.upsert("stream", closed ? {
|
|
1201
|
+
stream,
|
|
1202
|
+
offset: Offset.make(offset),
|
|
1203
|
+
closed: true
|
|
1204
|
+
} : {
|
|
1205
|
+
stream,
|
|
1206
|
+
offset: Offset.make(offset)
|
|
1207
|
+
});
|
|
962
1208
|
/**
|
|
963
|
-
*
|
|
964
|
-
*
|
|
1209
|
+
* A wake projection: one source stream gives one keyed row in one wake stream.
|
|
1210
|
+
* Each unit appends one upsert `{ stream, offset, closed? }` with
|
|
1211
|
+
* `Commit.producer`, so several source writes in one unit fold into one row,
|
|
1212
|
+
* and a retry answers `Duplicate`. The producer creates a missing wake stream
|
|
1213
|
+
* on its own owner. A wake stream on another owner must exist before the first
|
|
1214
|
+
* append: its owner creates it at start. When the source is removed or
|
|
1215
|
+
* expires, the binding appends a State delete for its row and forgets itself.
|
|
1216
|
+
*
|
|
1217
|
+
* ```ts
|
|
1218
|
+
* const filesWake = Projection.wake({
|
|
1219
|
+
* id: "files-wake",
|
|
1220
|
+
* params: { user: UserKey, folderId: FolderKey },
|
|
1221
|
+
* input: Files,
|
|
1222
|
+
* output: UserWake,
|
|
1223
|
+
* });
|
|
1224
|
+
* ```
|
|
965
1225
|
*/
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
1226
|
+
function wake(definition) {
|
|
1227
|
+
const input = definition.input;
|
|
1228
|
+
return build("mapAccumBatch", {
|
|
1229
|
+
id: definition.id,
|
|
1230
|
+
version: definition.version,
|
|
1231
|
+
generation: definition.generation,
|
|
1232
|
+
params: definition.params,
|
|
1233
|
+
commit: producer,
|
|
1234
|
+
inputs: { source: input },
|
|
1235
|
+
outputs: { wake: definition.output },
|
|
1236
|
+
state: {
|
|
1237
|
+
schema: Schema.Null,
|
|
1238
|
+
initial: null
|
|
1239
|
+
},
|
|
1240
|
+
mapAccumBatch: (_state, batch, unit) => {
|
|
1241
|
+
const source = isDeclaration(input) ? input.at(unit.params) : input;
|
|
1242
|
+
const slice = batch.source;
|
|
1243
|
+
return [null, { wake: [slice.gone ? DurableState.remove("stream", StreamId.make(source.id)) : row(StreamId.make(source.id), slice.nextOffset, slice.closed)] }];
|
|
1244
|
+
}
|
|
971
1245
|
});
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
});
|
|
975
|
-
//#endregion
|
|
976
|
-
//#region src/projection.ts
|
|
1246
|
+
}
|
|
1247
|
+
// src/projection.ts
|
|
977
1248
|
var projection_exports = /* @__PURE__ */ __exportAll({
|
|
1249
|
+
attach: () => attach$1,
|
|
978
1250
|
current: () => current,
|
|
979
1251
|
decide: () => decide,
|
|
980
1252
|
each: () => each,
|
|
@@ -989,7 +1261,8 @@ var projection_exports = /* @__PURE__ */ __exportAll({
|
|
|
989
1261
|
pass: () => pass,
|
|
990
1262
|
process: () => process,
|
|
991
1263
|
read: () => read,
|
|
992
|
-
run: () => run
|
|
1264
|
+
run: () => run,
|
|
1265
|
+
wake: () => wake
|
|
993
1266
|
});
|
|
994
1267
|
const key = (projection) => ({
|
|
995
1268
|
id: projection.id,
|
|
@@ -999,5 +1272,23 @@ const key = (projection) => ({
|
|
|
999
1272
|
});
|
|
1000
1273
|
/** Runs each tagged entry in order and discards its success value. */
|
|
1001
1274
|
const each = (handle) => (batch, unit) => Effect.forEach(items(batch), (entry) => handle(entry, unit), { discard: true });
|
|
1002
|
-
|
|
1003
|
-
|
|
1275
|
+
// src/wakeup.ts
|
|
1276
|
+
/**
|
|
1277
|
+
* Local commits choose bindings; each alarm drains the same runner used by
|
|
1278
|
+
* Projection.attach. Acquire it in the object layer's scope, before any
|
|
1279
|
+
* request writes.
|
|
1280
|
+
*/
|
|
1281
|
+
const attach = (projection, options = {}) => {
|
|
1282
|
+
const runner = runnerOf(projection, options.limit);
|
|
1283
|
+
return Effect.gen(function* () {
|
|
1284
|
+
const { next, drain } = yield* runner;
|
|
1285
|
+
return {
|
|
1286
|
+
name: `streamsy/projection/${encodeURIComponent(projection.id)}`,
|
|
1287
|
+
next,
|
|
1288
|
+
run: drain,
|
|
1289
|
+
retry: options.retry ?? (yield* ProjectionRetry)
|
|
1290
|
+
};
|
|
1291
|
+
});
|
|
1292
|
+
};
|
|
1293
|
+
const ProjectionWakeup = { attach };
|
|
1294
|
+
export { CheckpointRecord, CheckpointStore, commit_exports as Commit, HandlerFailed, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, Transaction };
|