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