@streamsy/projection 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{checkpoint-store-9roy8DEy.js → checkpoint-store-8FaC7V5x.js} +302 -104
- package/dist/{checkpoint-store-BQviDBDA.d.ts → checkpoint-store-C_Nipiyw.d.ts} +138 -9
- package/dist/checkpoint.d.ts +1 -1
- package/dist/checkpoint.js +1 -1
- package/dist/index.d.ts +209 -146
- package/dist/index.js +607 -555
- package/package.json +12 -12
package/dist/index.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
-
import {
|
|
2
|
+
import { A as ProjectionFault, B as isInputLoss, C as InvalidBinding, D as NonRetryable, E as InvalidWakeTime, F as SupersededGeneration, H as outputReason, I as TokenConflict, L as UnsupportedComposition, M as ProjectionFaultReasonTag, N as RangeUnreproducible, O as NotAttached, P as RetiredGeneration, R as inputNotFound, S as InputNotFound, T as InvalidSource, V as isValidWakeTime, _ as unitOf, b as HistoryUnavailable, c as rangesOf, d as unsupportedBindingList, f as inOwnerTransaction, g as terminalOf, h as encodeKey, i as assertCheckpointKeyVersion, j as ProjectionFaultReason, k as OutputRejected, l as recordKey, m as canonicalParams, n as CheckpointStore, o as loadLatest, p as storageFault, r as advance, s as ownerCheckpoints, t as CheckpointRecord, u as restore, v as withParams, w as InvalidRecord, x as IdentityMismatch, y as GenerationMismatch, z as invalidWakeTime } from "./checkpoint-store-8FaC7V5x.js";
|
|
3
3
|
import { Array, Cause, Clock, Context, Data, DateTime, Deferred, Duration, Effect, Exit, Function, Layer, Option, Order, Pipeable, Predicate, PubSub, Pull, Queue, Record, Ref, Result, Schedule, Schema, Semaphore, Stream } from "effect";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { DecodeFault, DurableState, EncodeFault, InvalidStreamParams, Offset, StorageFault, StorageOwner, StreamAddress, StreamId, Streamsy, StreamsyOffset, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
|
|
5
|
+
import { CurrentOwner, MAX_PRODUCER_ID_LENGTH, OwnerBackend, OwnerSlot, bindDeclaration, compileSegments, decodeMessage, decodeStateWire, fitKey, isForeignOwner, memoryProjectionMarks, offsetsOf, ownerParts, resolveParams, throwInvalidStreamParams } from "@streamsy/core/internal";
|
|
6
6
|
import { Streams, StreamsWriter } from "@streamsy/core/protocol";
|
|
7
|
-
import { SqlClient } from "effect/sql";
|
|
8
7
|
// src/batch.ts
|
|
9
8
|
/** An input that was skipped this pass: nothing read, nothing known beyond its cursor. */
|
|
10
9
|
const emptySlice = (from) => ({
|
|
@@ -17,43 +16,64 @@ const emptySlice = (from) => ({
|
|
|
17
16
|
});
|
|
18
17
|
/** Iteration preserves the union of the declared input stream requirements. */
|
|
19
18
|
const inputEntries = (inputs) => Record.toEntries(inputs);
|
|
19
|
+
// src/stored-offset.ts
|
|
20
|
+
/**
|
|
21
|
+
* Projection state keeps input offsets as the strings a Streamsy reader returned. Check one
|
|
22
|
+
* where it goes back into a read or an append; a value that fails is a corrupt record.
|
|
23
|
+
*/
|
|
24
|
+
const storedOffset = (value, fault) => Schema.decodeEffect(StreamsyOffset)(value).pipe(Effect.mapError((cause) => {
|
|
25
|
+
const message = `${fault.what} is not a valid offset: ${value}`;
|
|
26
|
+
return fault.input === void 0 ? new ProjectionFault({
|
|
27
|
+
phase: fault.phase,
|
|
28
|
+
reason: new InvalidRecord({
|
|
29
|
+
message,
|
|
30
|
+
cause
|
|
31
|
+
})
|
|
32
|
+
}) : new ProjectionFault({
|
|
33
|
+
phase: fault.phase,
|
|
34
|
+
input: fault.input,
|
|
35
|
+
reason: new InvalidRecord({
|
|
36
|
+
message,
|
|
37
|
+
cause
|
|
38
|
+
})
|
|
39
|
+
});
|
|
40
|
+
}));
|
|
20
41
|
// src/read.ts
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
reason: "invalid-options",
|
|
24
|
-
message: "limit must be a positive safe integer"
|
|
25
|
-
})));
|
|
42
|
+
/** A bad `limit` is a caller bug, so it is a defect that names the option and the value. */
|
|
43
|
+
const validateOptions = (options) => Effect.suspend(() => options.limit === void 0 || Number.isSafeInteger(options.limit) && options.limit > 0 ? Effect.void : Effect.die(/* @__PURE__ */ new RangeError(`Projection run option limit must be a positive safe integer, got ${String(options.limit)}`)));
|
|
26
44
|
/** One bounded read after `from`; retain input history and never reuse a deleted stream id. */
|
|
27
45
|
const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, from) {
|
|
28
46
|
const { wire: reader } = yield* address.stream;
|
|
29
47
|
const historyUnavailable = () => new ProjectionFault({
|
|
30
48
|
phase: "read",
|
|
31
|
-
reason: "history-unavailable",
|
|
32
49
|
input,
|
|
33
|
-
message: `Required history of ${address.id} after ${from} is unavailable`
|
|
50
|
+
reason: new HistoryUnavailable({ message: `Required history of ${address.id} after ${from} is unavailable` })
|
|
34
51
|
});
|
|
35
52
|
const storageFailure = (cause) => new ProjectionFault({
|
|
36
53
|
phase: "read",
|
|
37
|
-
reason: "storage-failure",
|
|
38
54
|
input,
|
|
39
|
-
|
|
40
|
-
cause
|
|
55
|
+
reason: cause
|
|
41
56
|
});
|
|
42
|
-
|
|
57
|
+
const start = Schema.decodeOption(StreamsyOffset)(from);
|
|
58
|
+
if (Option.isNone(start)) return yield* new ProjectionFault({
|
|
43
59
|
phase: "load",
|
|
44
|
-
reason: "invalid-record",
|
|
45
60
|
input,
|
|
46
|
-
message: `Stored offset for ${input} is not a valid offset`
|
|
61
|
+
reason: new InvalidRecord({ message: `Stored offset for ${input} is not a valid offset` })
|
|
47
62
|
});
|
|
48
|
-
const result = yield* reader.read(address.id, { offset:
|
|
63
|
+
const result = yield* reader.read(address.id, { offset: start.value }).pipe(Effect.catchTags({
|
|
49
64
|
InvalidReadRequest: (cause) => new ProjectionFault({
|
|
50
65
|
phase: "read",
|
|
51
|
-
reason: "invalid-source",
|
|
52
66
|
input,
|
|
53
|
-
|
|
54
|
-
|
|
67
|
+
reason: new InvalidSource({
|
|
68
|
+
message: cause.message,
|
|
69
|
+
cause
|
|
70
|
+
})
|
|
71
|
+
}),
|
|
72
|
+
StreamNotFound: (cause) => new ProjectionFault({
|
|
73
|
+
phase: "read",
|
|
74
|
+
input,
|
|
75
|
+
reason: inputNotFound(address.id, cause)
|
|
55
76
|
}),
|
|
56
|
-
StreamNotFound: () => historyUnavailable(),
|
|
57
77
|
StreamGone: () => historyUnavailable(),
|
|
58
78
|
StorageFault: storageFailure,
|
|
59
79
|
TransportFault: storageFailure
|
|
@@ -61,9 +81,8 @@ const readSlice = Effect.fn("Projection.readSlice")(function* (input, address, f
|
|
|
61
81
|
if (result.nextOffset < from || result.messages.length === 0 && result.nextOffset !== from) return yield* historyUnavailable();
|
|
62
82
|
if (result.nextOffset === from && (result.messages.length > 0 || !result.upToDate)) return yield* new ProjectionFault({
|
|
63
83
|
phase: "read",
|
|
64
|
-
reason: "invalid-source",
|
|
65
84
|
input,
|
|
66
|
-
message: `Read of ${address.id} did not advance past ${from}`
|
|
85
|
+
reason: new InvalidSource({ message: `Read of ${address.id} did not advance past ${from}` })
|
|
67
86
|
});
|
|
68
87
|
return {
|
|
69
88
|
slice: {
|
|
@@ -89,7 +108,7 @@ const pageOffsets = (result) => {
|
|
|
89
108
|
*/
|
|
90
109
|
const readOrGone = Effect.fn("Projection.readOrGone")(function* (input, address, from, read, seen) {
|
|
91
110
|
return yield* read.pipe(Effect.catchTag("ProjectionFault", (fault) => {
|
|
92
|
-
if (!seen || fault
|
|
111
|
+
if (!seen || !isInputLoss(fault)) return Effect.fail(fault);
|
|
93
112
|
return Effect.gen(function* () {
|
|
94
113
|
const { wire } = yield* address.stream;
|
|
95
114
|
if (!(yield* wire.head(address.id).pipe(Effect.as(false), Effect.catchTags({
|
|
@@ -97,10 +116,8 @@ const readOrGone = Effect.fn("Projection.readOrGone")(function* (input, address,
|
|
|
97
116
|
StreamGone: () => Effect.succeed(true)
|
|
98
117
|
}), Effect.mapError((cause) => new ProjectionFault({
|
|
99
118
|
phase: "read",
|
|
100
|
-
reason: "storage-failure",
|
|
101
119
|
input,
|
|
102
|
-
|
|
103
|
-
cause
|
|
120
|
+
reason: cause
|
|
104
121
|
}))))) return yield* fault;
|
|
105
122
|
return {
|
|
106
123
|
slice: {
|
|
@@ -121,10 +138,8 @@ const decodeMessages = (input, address, messages, offsets) => Effect.gen(functio
|
|
|
121
138
|
for (const [index, message] of messages.entries()) {
|
|
122
139
|
const decoded = yield* decodeMessage(address, message, index).pipe(Effect.mapError((cause) => new ProjectionFault({
|
|
123
140
|
phase: "read",
|
|
124
|
-
reason: "invalid-source",
|
|
125
141
|
input,
|
|
126
|
-
|
|
127
|
-
cause
|
|
142
|
+
reason: cause
|
|
128
143
|
})));
|
|
129
144
|
if (Option.isNone(decoded)) continue;
|
|
130
145
|
items.push(decoded.value);
|
|
@@ -141,9 +156,8 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
|
|
|
141
156
|
const { wire: reader } = yield* address.stream;
|
|
142
157
|
const unreproducible = (detail) => new ProjectionFault({
|
|
143
158
|
phase: "pin",
|
|
144
|
-
reason: "range-unreproducible",
|
|
145
159
|
input,
|
|
146
|
-
message: `Pinned range of ${address.id} after ${range.from} cannot be reproduced: ${detail}`
|
|
160
|
+
reason: new RangeUnreproducible({ message: `Pinned range of ${address.id} after ${range.from} cannot be reproduced: ${detail}` })
|
|
147
161
|
});
|
|
148
162
|
if (range.count === 0) {
|
|
149
163
|
if (range.from !== range.nextOffset || !range.closed && !range.gone) return yield* unreproducible("an empty pin must describe a terminal outcome at the same offset");
|
|
@@ -163,29 +177,31 @@ const reproduce = Effect.fn("Projection.reproduce")(function* (input, address, r
|
|
|
163
177
|
let cursor = range.from;
|
|
164
178
|
let last;
|
|
165
179
|
while (messages.length < range.count) {
|
|
166
|
-
const
|
|
180
|
+
const start = yield* storedOffset(cursor, {
|
|
181
|
+
phase: "pin",
|
|
182
|
+
input,
|
|
183
|
+
what: `The pinned offset of ${input}`
|
|
184
|
+
});
|
|
185
|
+
const page = yield* reader.read(address.id, { offset: start }).pipe(Effect.catchTags({
|
|
167
186
|
InvalidReadRequest: (cause) => new ProjectionFault({
|
|
168
187
|
phase: "pin",
|
|
169
|
-
reason: "invalid-record",
|
|
170
188
|
input,
|
|
171
|
-
|
|
172
|
-
|
|
189
|
+
reason: new InvalidRecord({
|
|
190
|
+
message: cause.message,
|
|
191
|
+
cause
|
|
192
|
+
})
|
|
173
193
|
}),
|
|
174
194
|
StreamNotFound: () => unreproducible("the input is missing"),
|
|
175
195
|
StreamGone: () => unreproducible("the input is gone"),
|
|
176
196
|
StorageFault: (cause) => new ProjectionFault({
|
|
177
197
|
phase: "pin",
|
|
178
|
-
reason: "storage-failure",
|
|
179
198
|
input,
|
|
180
|
-
|
|
181
|
-
cause
|
|
199
|
+
reason: cause
|
|
182
200
|
}),
|
|
183
201
|
TransportFault: (cause) => new ProjectionFault({
|
|
184
202
|
phase: "pin",
|
|
185
|
-
reason: "storage-failure",
|
|
186
203
|
input,
|
|
187
|
-
|
|
188
|
-
cause
|
|
204
|
+
reason: cause
|
|
189
205
|
})
|
|
190
206
|
}));
|
|
191
207
|
if (page.messages.length === 0) return yield* unreproducible("the input ended early");
|
|
@@ -298,6 +314,71 @@ const make$1 = (options) => extend({
|
|
|
298
314
|
return Pipeable.pipeArguments(this, arguments);
|
|
299
315
|
}
|
|
300
316
|
});
|
|
317
|
+
// src/routed-outputs.ts
|
|
318
|
+
const RoutedOutputs = Symbol.for("@streamsy/projection/internal/RoutedOutputs");
|
|
319
|
+
const processFault$1 = (reason) => new ProjectionFault({
|
|
320
|
+
phase: "process",
|
|
321
|
+
reason
|
|
322
|
+
});
|
|
323
|
+
const rejected$1 = (message) => processFault$1(new OutputRejected({ message }));
|
|
324
|
+
const requireRouteRecords = (store, phase) => store?.routes === void 0 ? Effect.fail(new ProjectionFault({
|
|
325
|
+
phase,
|
|
326
|
+
reason: new UnsupportedComposition({ message: "This CheckpointStore does not support routed outputs" })
|
|
327
|
+
})) : Effect.succeed(store.routes);
|
|
328
|
+
/** The checkpoint store of the commit whose retire runs the current cleanup. */
|
|
329
|
+
const CleanupCheckpoints = Context.Reference("@streamsy/projection/internal/CleanupCheckpoints", { defaultValue: () => void 0 });
|
|
330
|
+
/** The route records of the store whose retire runs the current cleanup. */
|
|
331
|
+
const currentRouteRecords = Effect.gen(function* () {
|
|
332
|
+
return yield* requireRouteRecords(yield* CleanupCheckpoints, "checkpoint");
|
|
333
|
+
});
|
|
334
|
+
const routedUnit = (key, store) => ({
|
|
335
|
+
key: recordKey(key),
|
|
336
|
+
store,
|
|
337
|
+
opened: /* @__PURE__ */ new Map(),
|
|
338
|
+
lock: Semaphore.makeUnsafe(1)
|
|
339
|
+
});
|
|
340
|
+
const TransactionRoutedOutputs = Context.Reference("@streamsy/projection/internal/TransactionRoutedOutputs", { defaultValue: () => void 0 });
|
|
341
|
+
const routedDefinition = (route) => ({
|
|
342
|
+
matches: route.match,
|
|
343
|
+
restore: (id) => {
|
|
344
|
+
const parsed = route.parse(id);
|
|
345
|
+
if (Option.isNone(parsed)) return void 0;
|
|
346
|
+
const address = bindDeclaration(route, parsed.value);
|
|
347
|
+
return address.id === id ? address : void 0;
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
const routedHandle = (name, route, names, params, key, occupied, routed) => ({ open: (values) => Effect.gen(function* () {
|
|
351
|
+
const unit = yield* TransactionRoutedOutputs;
|
|
352
|
+
if (unit === void 0 || unit.key !== recordKey(key)) return yield* processFault$1(new UnsupportedComposition({ message: `Routed output ${name} requires its binding's process transaction` }));
|
|
353
|
+
const unexpected = Array.findFirst([...names, ...Record.keys(values)], (param) => !Record.has(values, param) || !names.includes(param));
|
|
354
|
+
const address = yield* (Option.isSome(unexpected) ? Effect.fail(new InvalidStreamParams({
|
|
355
|
+
stream: route.template,
|
|
356
|
+
parameter: unexpected.value,
|
|
357
|
+
message: `Expected route parameters ${Array.join(names, ", ")}`
|
|
358
|
+
})) : resolveParams(() => bindDeclaration(route, {
|
|
359
|
+
...params,
|
|
360
|
+
...values
|
|
361
|
+
}))).pipe(Effect.mapError(processFault$1));
|
|
362
|
+
if (occupied.has(address.id)) return yield* rejected$1(`Routed output ${name} overlaps an input or output at ${address.id}`);
|
|
363
|
+
if (!Predicate.isTagged(address, "Json")) return yield* rejected$1("Projection outputs require JSON or state routes");
|
|
364
|
+
const service = yield* address.stream;
|
|
365
|
+
const owner = yield* CurrentOwner;
|
|
366
|
+
if (service.owner !== owner) return yield* Effect.die(/* @__PURE__ */ new Error(`Projection ${key.id}: routed output ${name} at ${address.id} is on storage owner ${service.owner}, but Commit.transaction runs on storage owner ${String(owner)}. Provide the output stream from the storage layer that provides the projection's StorageOwner.`));
|
|
367
|
+
return yield* unit.lock.withPermits(1)(Effect.gen(function* () {
|
|
368
|
+
const opened = unit.opened.get(address.id);
|
|
369
|
+
if (opened === name) return address;
|
|
370
|
+
if (opened !== void 0) return yield* rejected$1(`Routed outputs ${opened} and ${name} both name ${address.id}`);
|
|
371
|
+
const records = yield* requireRouteRecords(unit.store, "process");
|
|
372
|
+
if ((yield* records.state(key, name, address.id)) !== "live") {
|
|
373
|
+
for (const [other, definition] of routed) if (other !== name && definition.matches(address.id) && (yield* records.has(key, other, address.id))) return yield* rejected$1(`Routed outputs ${other} and ${name} both name ${address.id}`);
|
|
374
|
+
const created = yield* createOutput(address, service.wire);
|
|
375
|
+
if (created.closed || created.offset !== ZERO_OFFSET) return yield* rejected$1(`Generation-bound output ${address.id} must start empty and open`);
|
|
376
|
+
yield* records.add(key, name, address.id);
|
|
377
|
+
}
|
|
378
|
+
unit.opened.set(address.id, name);
|
|
379
|
+
return address;
|
|
380
|
+
}));
|
|
381
|
+
}) });
|
|
301
382
|
// src/commit/internal.ts
|
|
302
383
|
const DetailsKey = Symbol.for("@streamsy/projection/internal/Pending");
|
|
303
384
|
const setDetails = (pending, value) => Object.defineProperty(pending, DetailsKey, { value });
|
|
@@ -307,13 +388,21 @@ const detailsOf = (pending) => {
|
|
|
307
388
|
outputs: {}
|
|
308
389
|
};
|
|
309
390
|
};
|
|
391
|
+
/**
|
|
392
|
+
* A transactional output on another owner is a wiring defect. `Projection.attach` checks
|
|
393
|
+
* it once at layer build; a direct run finds it here.
|
|
394
|
+
*/
|
|
395
|
+
const foreignOutput = (projection, output, owner, found) => /* @__PURE__ */ new Error(`Projection ${projection}: output ${output} is on storage owner ${found}, but Commit.transaction runs on storage owner ${owner}. Provide the output stream from the storage layer that provides the projection's StorageOwner.`);
|
|
310
396
|
const load = (key) => CheckpointStore.use((store) => store.load(key));
|
|
311
397
|
const remove$1 = (key) => CheckpointStore.use((store) => store.remove(key));
|
|
312
|
-
|
|
398
|
+
/** The startup inventory of an id in `store`, or `UnsupportedComposition` without `list`. */
|
|
399
|
+
const listIn = (store, id) => store.list === void 0 ? Effect.fail(unsupportedBindingList()) : store.list(id);
|
|
400
|
+
const list = (id) => CheckpointStore.use((store) => listIn(store, id));
|
|
401
|
+
const retireIn = (store, { key, cleanup }) => store.retire === void 0 ? Effect.fail(new ProjectionFault({
|
|
313
402
|
phase: "checkpoint",
|
|
314
|
-
reason:
|
|
315
|
-
|
|
316
|
-
|
|
403
|
+
reason: new UnsupportedComposition({ message: `The checkpoint store cannot retire ${key.id}` })
|
|
404
|
+
})) : store.retire(key).pipe(Effect.tap(() => cleanup.pipe(Effect.provideService(CleanupCheckpoints, store))));
|
|
405
|
+
const retire$1 = (request) => CheckpointStore.use((store) => retireIn(store, request));
|
|
317
406
|
/** Merge the handler's state and timer into the same checkpoint write. */
|
|
318
407
|
const withState = (next, result) => {
|
|
319
408
|
const stored = result !== void 0 && "encoded" in result ? {
|
|
@@ -329,30 +418,18 @@ const beforeRecord = (pending) => Option.getOrElse(pending.loaded.record, () =>
|
|
|
329
418
|
...pending.next,
|
|
330
419
|
inputs: Record.fromEntries(Array.map(Record.toEntries(pending.next.inputs), ([name, offset]) => [name, pending.unit.ranges[name]?.from ?? offset]))
|
|
331
420
|
}));
|
|
332
|
-
const
|
|
421
|
+
const settleIn = (store, pending, result) => store.compareAndSet(pending.key, pending.loaded.token, withState(pending.next, result)).pipe(Effect.asVoid);
|
|
422
|
+
const settle = (pending, result) => CheckpointStore.use((store) => settleIn(store, pending, result));
|
|
333
423
|
// src/commit/checkpoint.ts
|
|
334
424
|
const checkpoint = make$1({
|
|
335
425
|
name: "checkpoint",
|
|
336
426
|
guarantee: "exactly-once",
|
|
337
427
|
load,
|
|
428
|
+
list,
|
|
338
429
|
remove: remove$1,
|
|
339
430
|
retire: retire$1,
|
|
340
431
|
apply: (pending) => Effect.flatMap(pending.run, (result) => settle(pending, result))
|
|
341
432
|
});
|
|
342
|
-
// src/transaction.ts
|
|
343
|
-
/** The storage owner's transaction, used by Commit.transaction. */
|
|
344
|
-
var Transaction = class extends Context.Service()("@streamsy/projection/Transaction") {
|
|
345
|
-
/** Join the commit boundary on a memory or SQL storage host. */
|
|
346
|
-
static layer = Layer.effect(this, Effect.map(CommitBoundary, (boundary) => ({
|
|
347
|
-
owner: ownerOf(boundary),
|
|
348
|
-
withTransaction: (body) => boundary.withTransaction(body).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(new ProjectionFault({
|
|
349
|
-
phase: "checkpoint",
|
|
350
|
-
reason: "storage-failure",
|
|
351
|
-
message: "The owner transaction failed",
|
|
352
|
-
cause
|
|
353
|
-
}))))
|
|
354
|
-
})));
|
|
355
|
-
};
|
|
356
433
|
// src/per-generation.ts
|
|
357
434
|
const TypeId = Symbol.for("@streamsy/projection/PerGeneration");
|
|
358
435
|
function perGeneration(route, param, options) {
|
|
@@ -389,86 +466,23 @@ const validateGenerationParam = (output, params) => {
|
|
|
389
466
|
const GenerationOutputs = Symbol.for("@streamsy/projection/internal/GenerationOutputs");
|
|
390
467
|
/** Outputs whose creation is managed by the current transaction. */
|
|
391
468
|
const TransactionGenerationOutputs = Context.Reference("@streamsy/projection/internal/TransactionGenerationOutputs", { defaultValue: () => void 0 });
|
|
392
|
-
// src/routed-outputs.ts
|
|
393
|
-
const RoutedOutputs = Symbol.for("@streamsy/projection/internal/RoutedOutputs");
|
|
394
|
-
const processFault = (reason, message, cause) => new ProjectionFault({
|
|
395
|
-
phase: "process",
|
|
396
|
-
reason,
|
|
397
|
-
message,
|
|
398
|
-
cause
|
|
399
|
-
});
|
|
400
|
-
const requireRouteRecords = (store, phase) => store?.routes === void 0 ? Effect.fail(new ProjectionFault({
|
|
401
|
-
phase,
|
|
402
|
-
reason: "unsupported-composition",
|
|
403
|
-
message: "This CheckpointStore does not support routed outputs"
|
|
404
|
-
})) : Effect.succeed(store.routes);
|
|
405
|
-
const currentRouteRecords = Effect.serviceOption(CheckpointStore).pipe(Effect.flatMap((store) => requireRouteRecords(Option.getOrUndefined(store), "checkpoint")));
|
|
406
|
-
const routedUnit = (key, store) => ({
|
|
407
|
-
key: recordKey(key),
|
|
408
|
-
store,
|
|
409
|
-
opened: /* @__PURE__ */ new Map(),
|
|
410
|
-
lock: Semaphore.makeUnsafe(1)
|
|
411
|
-
});
|
|
412
|
-
const TransactionRoutedOutputs = Context.Reference("@streamsy/projection/internal/TransactionRoutedOutputs", { defaultValue: () => void 0 });
|
|
413
|
-
const routedDefinition = (route) => ({
|
|
414
|
-
matches: route.match,
|
|
415
|
-
restore: (id) => {
|
|
416
|
-
const parsed = route.parse(id);
|
|
417
|
-
if (Option.isNone(parsed)) return void 0;
|
|
418
|
-
const address = route.at(parsed.value);
|
|
419
|
-
return address.id === id ? address : void 0;
|
|
420
|
-
}
|
|
421
|
-
});
|
|
422
|
-
const routedHandle = (name, route, names, params, key, occupied, routed) => ({ open: (values) => Effect.gen(function* () {
|
|
423
|
-
const unit = yield* TransactionRoutedOutputs;
|
|
424
|
-
if (unit === void 0 || unit.key !== recordKey(key)) return yield* processFault("unsupported-composition", `Routed output ${name} requires its binding's process transaction`);
|
|
425
|
-
const address = yield* Effect.try({
|
|
426
|
-
try: () => {
|
|
427
|
-
if (Record.keys(values).length !== names.length || !Array.every(names, (param) => Record.has(values, param))) throw new RangeError(`Expected route parameters ${Array.join(names, ", ")}`);
|
|
428
|
-
return route.at({
|
|
429
|
-
...params,
|
|
430
|
-
...values
|
|
431
|
-
});
|
|
432
|
-
},
|
|
433
|
-
catch: (cause) => processFault("invalid-output", `Cannot resolve routed output ${name}: ${cause instanceof RangeError ? cause.message : String(cause)}`, cause)
|
|
434
|
-
});
|
|
435
|
-
if (occupied.has(address.id)) return yield* processFault("invalid-output", `Routed output ${name} overlaps an input or output at ${address.id}`);
|
|
436
|
-
if (!Predicate.isTagged(address, "Json")) return yield* processFault("invalid-output", "Projection outputs require JSON or state routes");
|
|
437
|
-
const service = yield* address.stream;
|
|
438
|
-
const owner = yield* CurrentOwner;
|
|
439
|
-
if (service.owner !== owner) return yield* processFault("unsupported-composition", `Output ${address.id} does not share the transaction owner`);
|
|
440
|
-
return yield* unit.lock.withPermits(1)(Effect.gen(function* () {
|
|
441
|
-
const opened = unit.opened.get(address.id);
|
|
442
|
-
if (opened === name) return address;
|
|
443
|
-
if (opened !== void 0) return yield* processFault("invalid-output", `Routed outputs ${opened} and ${name} both name ${address.id}`);
|
|
444
|
-
const records = yield* requireRouteRecords(unit.store, "process");
|
|
445
|
-
if ((yield* records.state(key, name, address.id)) !== "live") {
|
|
446
|
-
for (const [other, definition] of routed) if (other !== name && definition.matches(address.id) && (yield* records.has(key, other, address.id))) return yield* processFault("invalid-output", `Routed outputs ${other} and ${name} both name ${address.id}`);
|
|
447
|
-
const created = yield* createOutput(address, service.wire);
|
|
448
|
-
if (created.closed || created.nextOffset !== ZERO_OFFSET) return yield* processFault("invalid-output", `Generation-bound output ${address.id} must start empty and open`);
|
|
449
|
-
yield* records.add(key, name, address.id);
|
|
450
|
-
}
|
|
451
|
-
unit.opened.set(address.id, name);
|
|
452
|
-
return address;
|
|
453
|
-
}));
|
|
454
|
-
}) });
|
|
455
469
|
// src/commit/transaction.ts
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
});
|
|
470
|
+
const ownerTransaction = Effect.map(StorageOwner, (owner) => ({
|
|
471
|
+
id: owner.id,
|
|
472
|
+
store: ownerCheckpoints(owner),
|
|
473
|
+
withTransaction: inOwnerTransaction(owner)
|
|
474
|
+
}));
|
|
461
475
|
/** Run the body for the owner, and fail when it writes to a stream on another owner. */
|
|
462
|
-
const withOwner = (tx, phase) => (body) => body.pipe(Effect.provideService(CurrentOwner, tx.
|
|
476
|
+
const withOwner = (tx, phase) => (body) => body.pipe(Effect.provideService(CurrentOwner, tx.id), Effect.catchDefect((defect) => isForeignOwner(defect) ? Effect.fail(new ProjectionFault({
|
|
463
477
|
phase,
|
|
464
|
-
reason:
|
|
465
|
-
message: defect.message
|
|
478
|
+
reason: new UnsupportedComposition({ message: defect.message })
|
|
466
479
|
})) : Effect.die(defect)));
|
|
467
|
-
const checkpointState = (loaded) => loaded.pipe(Effect.map(({ record }) => Option.isSome(record) ? "present" : "absent"), Effect.
|
|
480
|
+
const checkpointState = (loaded) => loaded.pipe(Effect.map(({ record }) => Option.isSome(record) ? "present" : "absent"), Effect.catchReasons("ProjectionFault", {
|
|
481
|
+
RetiredGeneration: () => Effect.succeed("retired"),
|
|
482
|
+
InvalidRecord: () => Effect.succeed("present")
|
|
483
|
+
}), Effect.mapError(({ reason }) => new ProjectionFault({
|
|
468
484
|
phase: "checkpoint",
|
|
469
|
-
reason
|
|
470
|
-
message,
|
|
471
|
-
cause
|
|
485
|
+
reason
|
|
472
486
|
})));
|
|
473
487
|
const removeWithRoutes = (store, key, checkpoint) => Effect.gen(function* () {
|
|
474
488
|
const records = yield* requireRouteRecords(store, "checkpoint");
|
|
@@ -479,23 +493,17 @@ const removeWithRoutes = (store, key, checkpoint) => Effect.gen(function* () {
|
|
|
479
493
|
}
|
|
480
494
|
return yield* Effect.void;
|
|
481
495
|
});
|
|
482
|
-
const retireInTransaction = (tx, request) =>
|
|
483
|
-
const store = yield* CheckpointStore;
|
|
484
|
-
if (ownerOf(store.load) !== tx.owner) return yield* checkpointOwnerFault(request.key);
|
|
485
|
-
return yield* tx.withTransaction(retire$1(request).pipe(withOwner(tx, "checkpoint")));
|
|
486
|
-
});
|
|
496
|
+
const retireInTransaction = (tx, request) => tx.withTransaction(retireIn(tx.store, request).pipe(withOwner(tx, "checkpoint")));
|
|
487
497
|
const TransactionCommitTypeId = Symbol("@streamsy/projection/TransactionCommit");
|
|
488
498
|
const removeInTransaction = (tx, key, cleanup) => tx.withTransaction(Effect.gen(function* () {
|
|
489
|
-
const store =
|
|
490
|
-
if (ownerOf(store.load) !== tx.owner) return yield* checkpointOwnerFault(key);
|
|
499
|
+
const store = tx.store;
|
|
491
500
|
const checkpoint = yield* checkpointState(store.load(key));
|
|
492
501
|
if (RoutedOutputs in key) yield* removeWithRoutes(store, key, checkpoint);
|
|
493
502
|
else yield* store.remove(key);
|
|
494
503
|
yield* cleanup.pipe(withOwner(tx, "checkpoint"));
|
|
495
504
|
if ((yield* checkpointState(checkpoint === "absent" ? loadLatest(store, key) : store.load(key))) !== (checkpoint === "retired" ? "retired" : "absent")) return yield* new ProjectionFault({
|
|
496
505
|
phase: "checkpoint",
|
|
497
|
-
reason:
|
|
498
|
-
message: `Record of ${key.id} changed while it was being forgotten. A second writer on the same key is the likely cause. Stop its runners, then forget again.`
|
|
506
|
+
reason: new TokenConflict({ message: `Record of ${key.id} changed while it was being forgotten. A second writer on the same key is the likely cause. Stop its runners, then forget again.` })
|
|
499
507
|
});
|
|
500
508
|
return yield* Effect.void;
|
|
501
509
|
}));
|
|
@@ -519,54 +527,42 @@ const removeInTransaction = (tx, key, cleanup) => tx.withTransaction(Effect.gen(
|
|
|
519
527
|
const transaction = Object.assign(withPrepare(make$1({
|
|
520
528
|
name: "transaction",
|
|
521
529
|
guarantee: "exactly-once",
|
|
522
|
-
load,
|
|
523
|
-
|
|
524
|
-
|
|
530
|
+
load: (key) => Effect.flatMap(ownerTransaction, (tx) => tx.store.load(key)),
|
|
531
|
+
list: (id) => Effect.flatMap(ownerTransaction, (tx) => listIn(tx.store, id)),
|
|
532
|
+
remove: (key) => Effect.flatMap(ownerTransaction, (tx) => removeInTransaction(tx, key, Effect.void)),
|
|
533
|
+
retire: (request) => Effect.flatMap(ownerTransaction, (tx) => retireInTransaction(tx, request)),
|
|
525
534
|
apply: (pending) => Effect.gen(function* () {
|
|
526
|
-
const tx = yield*
|
|
527
|
-
const store =
|
|
535
|
+
const tx = yield* ownerTransaction;
|
|
536
|
+
const store = tx.store;
|
|
528
537
|
const { outputs, prepare } = detailsOf(pending);
|
|
529
538
|
const hasRoutes = RoutedOutputs in pending.key;
|
|
530
|
-
for (const { address, service } of Record.values(outputs)) if (service.owner !== tx.
|
|
531
|
-
phase: "load",
|
|
532
|
-
reason: "unsupported-composition",
|
|
533
|
-
message: `Output ${address.id} does not share the transaction owner`
|
|
534
|
-
});
|
|
535
|
-
if (ownerOf(store.load) !== tx.owner) return yield* checkpointOwnerFault(pending.key);
|
|
539
|
+
for (const { address, service } of Record.values(outputs)) if (service.owner !== tx.id) return yield* Effect.die(foreignOutput(pending.key.id, address.id, tx.id, service.owner));
|
|
536
540
|
if (prepare !== void 0) yield* prepare;
|
|
537
541
|
yield* tx.withTransaction(Effect.gen(function* () {
|
|
538
542
|
const again = yield* store.load(pending.key);
|
|
539
543
|
if (again.token !== pending.loaded.token) return yield* new ProjectionFault({
|
|
540
544
|
phase: "checkpoint",
|
|
541
|
-
reason:
|
|
542
|
-
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.`
|
|
545
|
+
reason: new TokenConflict({ 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.` })
|
|
543
546
|
});
|
|
544
547
|
if (Option.isNone(again.record)) for (const { address, service, generation } of Record.values(outputs)) {
|
|
545
548
|
if (generation === void 0) continue;
|
|
546
549
|
const created = yield* createOutput(address, service.wire);
|
|
547
|
-
if (!generation.shared && (created.closed || created.
|
|
550
|
+
if (!generation.shared && (created.closed || created.offset !== ZERO_OFFSET)) return yield* new ProjectionFault({
|
|
548
551
|
phase: "process",
|
|
549
|
-
reason:
|
|
550
|
-
message: `Generation-bound output ${address.id} must start empty and open`
|
|
552
|
+
reason: new OutputRejected({ message: `Generation-bound output ${address.id} must start empty and open` })
|
|
551
553
|
});
|
|
552
554
|
}
|
|
553
555
|
const result = yield* pending.run.pipe(withOwner(tx, "process"), Effect.provideService(TransactionGenerationOutputs, pending.generationOutputs), Effect.provideService(TransactionRoutedOutputs, hasRoutes ? routedUnit(pending.key, store) : void 0));
|
|
554
556
|
if (result !== void 0 && "outputs" in result) for (const [name, output] of Record.toEntries(result.outputs)) {
|
|
555
557
|
if (!Array.isReadonlyArrayNonEmpty(output.items)) continue;
|
|
556
558
|
const resolved = outputs[name];
|
|
557
|
-
if (resolved === void 0) return yield* new
|
|
558
|
-
phase: "process",
|
|
559
|
-
reason: "invalid-output",
|
|
560
|
-
message: `Undeclared output ${name}`
|
|
561
|
-
});
|
|
559
|
+
if (resolved === void 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection handler returned an undeclared output: ${name}`));
|
|
562
560
|
yield* Streams.append(output.address, output.items).pipe(Effect.provideService(StreamsWriter, resolved.service.wire), Effect.mapError((cause) => new ProjectionFault({
|
|
563
561
|
phase: "process",
|
|
564
|
-
reason:
|
|
565
|
-
message: `Cannot append to ${output.address.id}`,
|
|
566
|
-
cause
|
|
562
|
+
reason: outputReason(`Cannot append to ${output.address.id}`, cause)
|
|
567
563
|
})));
|
|
568
564
|
}
|
|
569
|
-
yield*
|
|
565
|
+
yield* settleIn(store, pending, result);
|
|
570
566
|
return yield* Effect.void;
|
|
571
567
|
}));
|
|
572
568
|
return yield* Effect.void;
|
|
@@ -578,8 +574,8 @@ const transaction = Object.assign(withPrepare(make$1({
|
|
|
578
574
|
*/
|
|
579
575
|
const transactionWithCleanup = (cleanup) => inherit(transaction, {
|
|
580
576
|
...transaction,
|
|
581
|
-
remove: (key) =>
|
|
582
|
-
retire: (request) =>
|
|
577
|
+
remove: (key) => Effect.flatMap(ownerTransaction, (tx) => removeInTransaction(tx, key, Effect.suspend(() => cleanup(key)))),
|
|
578
|
+
retire: (request) => Effect.flatMap(ownerTransaction, (tx) => retireInTransaction(tx, {
|
|
583
579
|
...request,
|
|
584
580
|
cleanup: request.cleanup.pipe(Effect.andThen(() => cleanup(request.key)))
|
|
585
581
|
}))
|
|
@@ -596,36 +592,32 @@ const producerId = (id, params) => fitKey(`${id}${PRODUCER_ID_SUFFIX}${Record.ke
|
|
|
596
592
|
/** The head of one output. A missing output on the checkpoint's owner is created here. */
|
|
597
593
|
const prepareOutput = (output, store, beforeCreate) => {
|
|
598
594
|
const { wire, owner: outputOwner } = output.service;
|
|
599
|
-
return wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !==
|
|
595
|
+
return wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== store.owner ? Effect.fail(cause) : beforeCreate.pipe(Effect.andThen(Streams.create(output.address)), Effect.provideService(StreamsWriter, wire), Effect.andThen(wire.head(output.address.id)))), Effect.mapError((cause) => Predicate.isTagged(cause, "ProjectionFault") ? cause : new ProjectionFault({
|
|
600
596
|
phase: "pin",
|
|
601
|
-
reason:
|
|
602
|
-
message: `Cannot prepare output ${output.address.id}`,
|
|
603
|
-
cause
|
|
597
|
+
reason: outputReason(`Cannot prepare output ${output.address.id}`, cause)
|
|
604
598
|
})));
|
|
605
599
|
};
|
|
606
600
|
/** The pin write is the last save before the append, so its conflict is a pin failure. */
|
|
607
|
-
const asPin = (fault) => fault.phase === "checkpoint" && fault.reason
|
|
601
|
+
const asPin = (fault) => fault.phase === "checkpoint" && Predicate.isTagged(fault.reason, "TokenConflict") ? new ProjectionFault({
|
|
608
602
|
phase: "pin",
|
|
609
|
-
reason: fault.reason
|
|
610
|
-
message: fault.message
|
|
603
|
+
reason: fault.reason
|
|
611
604
|
}) : fault;
|
|
612
605
|
const producer = pin$1(make$1({
|
|
613
606
|
name: "producer",
|
|
614
607
|
guarantee: "effectively-once",
|
|
615
608
|
remove: remove$1,
|
|
616
609
|
retire: retire$1,
|
|
610
|
+
list,
|
|
617
611
|
load: (key) => Effect.gen(function* () {
|
|
618
612
|
const loaded = yield* load(key);
|
|
619
613
|
if (Option.isSome(loaded.record)) {
|
|
620
614
|
if (loaded.record.value.pending !== void 0 && loaded.record.value.pending.seqs === void 0) return yield* new ProjectionFault({
|
|
621
615
|
phase: "load",
|
|
622
|
-
reason: "
|
|
623
|
-
message: "A producer pin must include output sequences"
|
|
616
|
+
reason: new InvalidRecord({ message: "A producer pin must include output sequences" })
|
|
624
617
|
});
|
|
625
618
|
for (const [name, position] of Record.toEntries(loaded.record.value.adapters.outputs ?? {})) if (position.epoch !== key.generation) return yield* new ProjectionFault({
|
|
626
619
|
phase: "load",
|
|
627
|
-
reason:
|
|
628
|
-
message: `Stored epoch ${position.epoch} of ${key.id}/${name} is not generation ${key.generation}`
|
|
620
|
+
reason: new SupersededGeneration({ message: `Stored epoch ${position.epoch} of ${key.id}/${name} is not generation ${key.generation}` })
|
|
629
621
|
});
|
|
630
622
|
}
|
|
631
623
|
return loaded;
|
|
@@ -642,8 +634,7 @@ const producer = pin$1(make$1({
|
|
|
642
634
|
const positions = { ...adapters.outputs };
|
|
643
635
|
for (const [name, position] of Record.toEntries(positions)) if (position.epoch !== projection.generation) return yield* new ProjectionFault({
|
|
644
636
|
phase: "load",
|
|
645
|
-
reason:
|
|
646
|
-
message: `Stored epoch ${position.epoch} of ${projection.id}/${name} is not generation ${projection.generation}`
|
|
637
|
+
reason: new SupersededGeneration({ message: `Stored epoch ${position.epoch} of ${projection.id}/${name} is not generation ${projection.generation}` })
|
|
647
638
|
});
|
|
648
639
|
const pending = before.record.pending;
|
|
649
640
|
const result = yield* request.run;
|
|
@@ -651,14 +642,12 @@ const producer = pin$1(make$1({
|
|
|
651
642
|
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 ?? {};
|
|
652
643
|
for (const name of Record.keys(seqs)) if (streams[name] === void 0 || (processed.items[name]?.length ?? 0) === 0) return yield* new ProjectionFault({
|
|
653
644
|
phase: "process",
|
|
654
|
-
reason:
|
|
655
|
-
message: `Cannot reproduce pinned output ${name}`
|
|
645
|
+
reason: new OutputRejected({ message: `Cannot reproduce pinned output ${name}` })
|
|
656
646
|
});
|
|
657
647
|
if (pending !== void 0) {
|
|
658
648
|
for (const name of Record.keys(streams)) if ((processed.items[name]?.length ?? 0) > 0 && seqs[name] === void 0) return yield* new ProjectionFault({
|
|
659
649
|
phase: "process",
|
|
660
|
-
reason:
|
|
661
|
-
message: `Cannot reproduce pinned unit: output ${name} has items that were not pinned`
|
|
650
|
+
reason: new OutputRejected({ message: `Cannot reproduce pinned unit: output ${name} has items that were not pinned` })
|
|
662
651
|
});
|
|
663
652
|
}
|
|
664
653
|
let token = before.token;
|
|
@@ -666,8 +655,7 @@ const producer = pin$1(make$1({
|
|
|
666
655
|
const checkBeforeCreate = Effect.gen(function* () {
|
|
667
656
|
if ((yield* owner.load(projection)).token !== before.token) return yield* new ProjectionFault({
|
|
668
657
|
phase: "pin",
|
|
669
|
-
reason:
|
|
670
|
-
message: `Record for ${projection.id} changed before creating an output`
|
|
658
|
+
reason: new TokenConflict({ message: `Record for ${projection.id} changed before creating an output` })
|
|
671
659
|
});
|
|
672
660
|
return yield* Effect.void;
|
|
673
661
|
});
|
|
@@ -676,13 +664,11 @@ const producer = pin$1(make$1({
|
|
|
676
664
|
const head = yield* prepareOutput(output, owner, output.generation === void 0 ? Effect.void : checkBeforeCreate);
|
|
677
665
|
if (head.closed) return yield* new ProjectionFault({
|
|
678
666
|
phase: "pin",
|
|
679
|
-
reason:
|
|
680
|
-
message: `Output ${output.address.id} is closed`
|
|
667
|
+
reason: new OutputRejected({ message: `Output ${output.address.id} is closed` })
|
|
681
668
|
});
|
|
682
|
-
if (output.generation?.shared === false && positions[name] === void 0 && head.
|
|
669
|
+
if (output.generation?.shared === false && positions[name] === void 0 && head.offset !== ZERO_OFFSET) return yield* new ProjectionFault({
|
|
683
670
|
phase: "pin",
|
|
684
|
-
reason:
|
|
685
|
-
message: `Generation-bound output ${output.address.id} must start empty and open`
|
|
671
|
+
reason: new OutputRejected({ message: `Generation-bound output ${output.address.id} must start empty and open` })
|
|
686
672
|
});
|
|
687
673
|
positions[name] = positions[name] ?? {
|
|
688
674
|
epoch: projection.generation,
|
|
@@ -734,6 +720,7 @@ const atLeastOnce = pin$1(make$1({
|
|
|
734
720
|
name: "atLeastOnce",
|
|
735
721
|
guarantee: "at-least-once",
|
|
736
722
|
load,
|
|
723
|
+
list,
|
|
737
724
|
remove: remove$1,
|
|
738
725
|
retire: retire$1,
|
|
739
726
|
apply: (pending) => Effect.gen(function* () {
|
|
@@ -969,12 +956,12 @@ const resolveOutputs = (outputs, frontierStream, params, key, inputs) => {
|
|
|
969
956
|
if (isPerGeneration(output)) {
|
|
970
957
|
const { route, param, shared } = generationBinding(output);
|
|
971
958
|
generationOutputs.set(name, { shared });
|
|
972
|
-
return route
|
|
959
|
+
return bindDeclaration(route, {
|
|
973
960
|
...params,
|
|
974
961
|
[param]: key.generation
|
|
975
962
|
});
|
|
976
963
|
}
|
|
977
|
-
return isDeclaration(output) ? output
|
|
964
|
+
return isDeclaration(output) ? bindDeclaration(output, params) : output;
|
|
978
965
|
};
|
|
979
966
|
const routed = /* @__PURE__ */ new Map();
|
|
980
967
|
const streams = Record.fromEntries(Array.flatMap(Record.toEntries(outputs), ([name, output]) => {
|
|
@@ -1013,9 +1000,10 @@ const resolveOutputs = (outputs, frontierStream, params, key, inputs) => {
|
|
|
1013
1000
|
};
|
|
1014
1001
|
const createOutput = (address, wire) => Streams.create(address).pipe(Effect.provideService(StreamsWriter, wire), Effect.mapError((cause) => new ProjectionFault({
|
|
1015
1002
|
phase: "process",
|
|
1016
|
-
reason: isStreamsFault(cause) ?
|
|
1017
|
-
|
|
1018
|
-
|
|
1003
|
+
reason: isStreamsFault(cause) ? cause : new OutputRejected({
|
|
1004
|
+
message: `Cannot create output ${address.id}`,
|
|
1005
|
+
cause
|
|
1006
|
+
})
|
|
1019
1007
|
})));
|
|
1020
1008
|
const boundOutputs = (bound) => bound.accepted === void 0 ? bound.streams ?? {} : {
|
|
1021
1009
|
...bound.streams,
|
|
@@ -1034,48 +1022,49 @@ const createOutputs = (bound) => Effect.gen(function* () {
|
|
|
1034
1022
|
const collect = (outputs, buffers, emitted) => Effect.gen(function* () {
|
|
1035
1023
|
for (const [name, entries] of Record.toEntries(emitted)) {
|
|
1036
1024
|
const output = outputs[name];
|
|
1037
|
-
if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* new
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
catch: (cause) => new ProjectionFault({
|
|
1045
|
-
phase: "process",
|
|
1046
|
-
reason: "invalid-output",
|
|
1047
|
-
message: `Invalid row change for ${name}`,
|
|
1048
|
-
cause
|
|
1049
|
-
})
|
|
1025
|
+
if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection handler returned an invalid output array: ${name}`));
|
|
1026
|
+
const values = yield* Effect.suspend(() => {
|
|
1027
|
+
try {
|
|
1028
|
+
return Effect.succeed("collections" in output ? DurableState.changes(output, entries) : entries);
|
|
1029
|
+
} catch (cause) {
|
|
1030
|
+
return Effect.die(new RangeError(`Projection handler returned an invalid row change for output ${name}`, { cause }));
|
|
1031
|
+
}
|
|
1050
1032
|
});
|
|
1051
1033
|
(buffers[name] ??= []).push(...values);
|
|
1052
1034
|
}
|
|
1053
1035
|
return yield* Effect.void;
|
|
1054
1036
|
});
|
|
1055
|
-
const pin = (reason
|
|
1037
|
+
const pin = (reason) => new ProjectionFault({
|
|
1056
1038
|
phase: "pin",
|
|
1057
|
-
reason
|
|
1058
|
-
message,
|
|
1059
|
-
cause
|
|
1039
|
+
reason
|
|
1060
1040
|
});
|
|
1041
|
+
const rejected = (message) => pin(new OutputRejected({ message }));
|
|
1061
1042
|
/** Append one unit under its pinned tuple; appended and duplicate are one outcome. */
|
|
1062
1043
|
const appendPinned = Effect.fn("Projection.appendPinned")(function* (output, wire, items, position) {
|
|
1063
1044
|
return yield* Streams.append(output, items, { producer: position }).pipe(Effect.provideService(StreamsWriter, wire), Effect.catchTags({
|
|
1064
|
-
EncodeFault: () => new ProjectionFault({
|
|
1045
|
+
EncodeFault: (cause) => new ProjectionFault({
|
|
1065
1046
|
phase: "process",
|
|
1066
|
-
reason:
|
|
1067
|
-
message: `Cannot encode output for ${output.id}`
|
|
1047
|
+
reason: cause
|
|
1068
1048
|
}),
|
|
1069
|
-
StaleEpoch: (error) => pin(
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1049
|
+
StaleEpoch: (error) => pin(new SupersededGeneration({
|
|
1050
|
+
message: `Epoch ${position.producerEpoch} of ${output.id} is behind ${error.currentEpoch}`,
|
|
1051
|
+
cause: error
|
|
1052
|
+
})),
|
|
1053
|
+
ProducerGap: (error) => pin(new InvalidRecord({
|
|
1054
|
+
message: `Sequence ${error.receivedSeq} of ${output.id} does not follow ${error.expectedSeq}`,
|
|
1055
|
+
cause: error
|
|
1056
|
+
})),
|
|
1057
|
+
NotSupported: (error) => pin(new UnsupportedComposition({
|
|
1058
|
+
message: `${output.id} does not support ${error.feature}`,
|
|
1059
|
+
cause: error
|
|
1060
|
+
})),
|
|
1061
|
+
StorageFault: pin,
|
|
1062
|
+
TransportFault: pin,
|
|
1063
|
+
StreamNotFound: () => rejected(`Output ${output.id} does not exist`),
|
|
1064
|
+
StreamGone: () => rejected(`Output ${output.id} is gone`),
|
|
1065
|
+
StreamClosed: () => rejected(`Output ${output.id} is closed`),
|
|
1066
|
+
AppendConflict: () => rejected(`Output ${output.id} refused the append`),
|
|
1067
|
+
StreamBusy: pin
|
|
1079
1068
|
}));
|
|
1080
1069
|
});
|
|
1081
1070
|
// src/state.ts
|
|
@@ -1089,9 +1078,10 @@ const bindState = (definition, params) => {
|
|
|
1089
1078
|
/** Decodes the state field. `None` means no state is stored. */
|
|
1090
1079
|
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({
|
|
1091
1080
|
phase: "load",
|
|
1092
|
-
reason:
|
|
1093
|
-
|
|
1094
|
-
|
|
1081
|
+
reason: new InvalidRecord({
|
|
1082
|
+
message: `Invalid stored state for ${key.id}`,
|
|
1083
|
+
cause
|
|
1084
|
+
})
|
|
1095
1085
|
})));
|
|
1096
1086
|
/** The stored state, or the initial value when stored state is absent. */
|
|
1097
1087
|
const currentState = (key, state, encoded) => Effect.gen(function* () {
|
|
@@ -1100,28 +1090,37 @@ const currentState = (key, state, encoded) => Effect.gen(function* () {
|
|
|
1100
1090
|
});
|
|
1101
1091
|
const encodeState = (key, schema, value) => Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(Effect.mapError((cause) => new ProjectionFault({
|
|
1102
1092
|
phase: "process",
|
|
1103
|
-
reason:
|
|
1104
|
-
|
|
1105
|
-
|
|
1093
|
+
reason: new EncodeFault({
|
|
1094
|
+
message: `Cannot encode state for ${key.id}`,
|
|
1095
|
+
cause
|
|
1096
|
+
})
|
|
1106
1097
|
})));
|
|
1107
1098
|
// src/wake-at.ts
|
|
1108
1099
|
const request = Data.taggedEnum().WakeAt;
|
|
1109
|
-
/**
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
};
|
|
1100
|
+
/**
|
|
1101
|
+
* Return this request from process; returning void clears the previous deadline. It never throws.
|
|
1102
|
+
* A time that is not a non-negative safe integer in epoch milliseconds fails the unit with a
|
|
1103
|
+
* `ProjectionFault` whose reason is `InvalidWakeTime`, before anything is committed.
|
|
1104
|
+
*/
|
|
1105
|
+
const wakeAt = (time) => request({ wakeAt: Predicate.isNumber(time) ? time : DateTime.toEpochMillis(time) });
|
|
1115
1106
|
/** Internal: discard ordinary process return values while keeping wake requests. */
|
|
1116
1107
|
const isWakeAt = (value) => Predicate.isTagged(value, "WakeAt");
|
|
1117
1108
|
// src/step.ts
|
|
1109
|
+
/**
|
|
1110
|
+
* Every process result passes here before any Commit writes, so an invalid wake time fails the
|
|
1111
|
+
* unit on every commit path.
|
|
1112
|
+
*/
|
|
1113
|
+
const checkWakeAt = (request) => isValidWakeTime(request.wakeAt) ? Effect.succeed(request) : Effect.fail(new ProjectionFault({
|
|
1114
|
+
phase: "process",
|
|
1115
|
+
reason: invalidWakeTime(request.wakeAt)
|
|
1116
|
+
}));
|
|
1118
1117
|
/** One adapter invocation is one unit. Per-entry variants thread state and preserve order. */
|
|
1119
1118
|
const adapt = (kind, key, state, streams, outputs, handler, batch, unit, encoded, prepared, attempt = 1) => Effect.gen(function* () {
|
|
1120
|
-
if (kind === "process") return yield* Effect.
|
|
1119
|
+
if (kind === "process") return yield* Effect.flatMap(handler(batch, unit, {
|
|
1121
1120
|
prepared,
|
|
1122
1121
|
outputs,
|
|
1123
1122
|
attempt
|
|
1124
|
-
}), (result) => isWakeAt(result) ? result :
|
|
1123
|
+
}), (result) => isWakeAt(result) ? checkWakeAt(result) : Effect.undefined);
|
|
1125
1124
|
let value = state === void 0 ? void 0 : yield* currentState(key, state, encoded);
|
|
1126
1125
|
const buffers = Record.fromEntries(Array.map(Record.keys(streams), (name) => [name, []]));
|
|
1127
1126
|
const steps = kind === "mapAccumBatch" ? [batch] : items(batch);
|
|
@@ -1153,34 +1152,66 @@ const adapt = (kind, key, state, streams, outputs, handler, batch, unit, encoded
|
|
|
1153
1152
|
// src/declaration.ts
|
|
1154
1153
|
/** Internal access to the same binding at a chosen generation. */
|
|
1155
1154
|
const BindGeneration = Symbol.for("@streamsy/projection/internal/BindGeneration");
|
|
1155
|
+
const DeclaredKey = Symbol.for("@streamsy/projection/internal/Declared");
|
|
1156
|
+
/** The commit and owned outputs that `declare` recorded, if it built this declaration. */
|
|
1157
|
+
const declaredOf = (declaration) => DeclaredKey in declaration ? declaration[DeclaredKey] : void 0;
|
|
1158
|
+
/** The stream service of a declared output, a stream class, an address or a per-generation route. */
|
|
1159
|
+
const outputService = (output) => isPerGeneration(output) ? generationBinding(output).route : isDeclaration(output) ? output : output.stream;
|
|
1156
1160
|
const bindAtGeneration = (declaration, params, generation) => declaration[BindGeneration]?.(params, generation);
|
|
1157
|
-
|
|
1161
|
+
/** A stream declaration, with or without params, as opposed to a fixed address. */
|
|
1162
|
+
const isDeclaration = (input) => "singleton" in input || "at" in input;
|
|
1158
1163
|
const encodeParams = (id, codecs, params) => {
|
|
1159
1164
|
const values = params;
|
|
1160
1165
|
return Record.fromEntries(Array.map(Record.toEntries(codecs), ([name, codec]) => {
|
|
1161
1166
|
const encoded = Schema.encodeOption(codec)(values[name]);
|
|
1162
|
-
if (Option.isNone(encoded))
|
|
1167
|
+
if (Option.isNone(encoded)) return throwInvalidStreamParams(new InvalidStreamParams({
|
|
1168
|
+
stream: id,
|
|
1169
|
+
parameter: name,
|
|
1170
|
+
message: `Cannot encode projection ${id} parameter ${name}`
|
|
1171
|
+
}));
|
|
1163
1172
|
return [name, encoded.value];
|
|
1164
1173
|
}));
|
|
1165
1174
|
};
|
|
1166
1175
|
const addressesOf = (inputs, params) => {
|
|
1167
|
-
return Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, input]) => [name, isDeclaration(input) ? input
|
|
1176
|
+
return Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, input]) => [name, isDeclaration(input) ? bindDeclaration(input, params) : input]));
|
|
1177
|
+
};
|
|
1178
|
+
/**
|
|
1179
|
+
* Add `singleton` to a declaration without params. It binds on first read, so a binding that
|
|
1180
|
+
* throws still throws where the value is used, and then returns the same object every time.
|
|
1181
|
+
*/
|
|
1182
|
+
const withSingleton = (target, bind) => {
|
|
1183
|
+
let cached;
|
|
1184
|
+
return Object.defineProperty(target, "singleton", {
|
|
1185
|
+
enumerable: true,
|
|
1186
|
+
get: () => (cached ??= { value: bind() }).value
|
|
1187
|
+
});
|
|
1168
1188
|
};
|
|
1169
|
-
|
|
1189
|
+
/**
|
|
1190
|
+
* Add non-enumerable `at` and `resolve` to a singleton. Both ignore their argument and give the
|
|
1191
|
+
* `singleton` value. A codec record typed wider than its value, such as one annotated
|
|
1192
|
+
* `StreamRoute.ParamCodecs`, gives a declaration whose type has `at` but whose empty record makes
|
|
1193
|
+
* it a singleton at run time. Non-enumerable, so spreads and key lists see only `singleton`, and
|
|
1194
|
+
* every discriminator still tests `"singleton" in x` first.
|
|
1195
|
+
*/
|
|
1196
|
+
const withSingletonBindings = (target) => Object.defineProperties(target, {
|
|
1197
|
+
at: { value: () => target.singleton },
|
|
1198
|
+
resolve: { value: () => resolveParams(() => target.singleton) }
|
|
1199
|
+
});
|
|
1200
|
+
const declare = (definition, bind, declared) => {
|
|
1170
1201
|
const generation = definition.generation ?? 1;
|
|
1202
|
+
const codecs = definition.params ?? {};
|
|
1171
1203
|
const atGeneration = (params, selected) => bind({
|
|
1172
1204
|
id: definition.id,
|
|
1173
1205
|
generation: selected,
|
|
1174
|
-
params: encodeParams(definition.id,
|
|
1206
|
+
params: encodeParams(definition.id, codecs, params),
|
|
1175
1207
|
decoded: params
|
|
1176
1208
|
});
|
|
1177
|
-
const
|
|
1209
|
+
const core = {
|
|
1178
1210
|
retry: definition.retry,
|
|
1179
1211
|
id: definition.id,
|
|
1180
1212
|
generation,
|
|
1181
|
-
params:
|
|
1213
|
+
params: codecs,
|
|
1182
1214
|
inputs: definition.inputs,
|
|
1183
|
-
at: (params) => atGeneration(params, generation),
|
|
1184
1215
|
parse: (id) => {
|
|
1185
1216
|
for (const input of Record.values(definition.inputs)) {
|
|
1186
1217
|
if (!isDeclaration(input)) continue;
|
|
@@ -1190,6 +1221,11 @@ const declare = (definition, bind) => {
|
|
|
1190
1221
|
return Option.none();
|
|
1191
1222
|
}
|
|
1192
1223
|
};
|
|
1224
|
+
const declaration = Record.isEmptyRecord(codecs) ? withSingletonBindings(withSingleton(core, () => atGeneration({}, generation))) : Object.assign(core, {
|
|
1225
|
+
at: (params) => atGeneration(params, generation),
|
|
1226
|
+
resolve: (params) => resolveParams(() => atGeneration(params, generation))
|
|
1227
|
+
});
|
|
1228
|
+
if (declared !== void 0) Object.defineProperty(declaration, DeclaredKey, { value: declared });
|
|
1193
1229
|
return Object.defineProperty(declaration, BindGeneration, { value: atGeneration });
|
|
1194
1230
|
};
|
|
1195
1231
|
/** @internal Reject legacy definitions passed from JavaScript or unchecked TypeScript. */
|
|
@@ -1204,15 +1240,16 @@ const build = (kind, definition) => {
|
|
|
1204
1240
|
const commit = definition.commit ?? checkpoint;
|
|
1205
1241
|
const outputs = definition.outputs ?? {};
|
|
1206
1242
|
const stream = definition.frontier === true ? void 0 : definition.frontier;
|
|
1243
|
+
const params = definition.params ?? {};
|
|
1207
1244
|
const frontier = validateFrontier(definition.frontier, {
|
|
1208
1245
|
commit,
|
|
1209
|
-
params
|
|
1246
|
+
params,
|
|
1210
1247
|
outputs,
|
|
1211
1248
|
inputTemplates: Array.map(Array.filter(Record.values(definition.inputs), isDeclaration), (input) => input.template)
|
|
1212
1249
|
});
|
|
1213
1250
|
if (frontier !== void 0 && (kind === "fold" || kind === "process")) throw new RangeError("frontier requires Projection.emit, Projection.mapAccum or Projection.mapAccumBatch");
|
|
1214
1251
|
for (const output of Record.values(outputs)) {
|
|
1215
|
-
validateGenerationParam(output,
|
|
1252
|
+
validateGenerationParam(output, params);
|
|
1216
1253
|
if (isPerGeneration(output) && generationBinding(output).routeBy !== void 0) {
|
|
1217
1254
|
if (kind !== "process") throw new RangeError("Routed outputs require Projection.process");
|
|
1218
1255
|
if (!supportsPrepare(commit)) throw new RangeError("Routed outputs require Commit.transaction");
|
|
@@ -1237,6 +1274,15 @@ const build = (kind, definition) => {
|
|
|
1237
1274
|
if (routed.size > 0) Object.assign(bound, { [RoutedOutputs]: routed });
|
|
1238
1275
|
if (frontier !== void 0) Object.assign(bound, { [FrontierOutputs]: frontier });
|
|
1239
1276
|
return bound;
|
|
1277
|
+
}, {
|
|
1278
|
+
commit,
|
|
1279
|
+
ownedOutputs: supportsPrepare(commit) ? [...Array.map(Record.toEntries(outputs), ([name, output]) => ({
|
|
1280
|
+
name,
|
|
1281
|
+
stream: outputService(output)
|
|
1282
|
+
})), ...stream === void 0 ? [] : [{
|
|
1283
|
+
name: "frontier",
|
|
1284
|
+
stream: outputService(stream)
|
|
1285
|
+
}]] : []
|
|
1240
1286
|
});
|
|
1241
1287
|
};
|
|
1242
1288
|
// src/fold.ts
|
|
@@ -1263,16 +1309,15 @@ function mapAccumBatch(definition) {
|
|
|
1263
1309
|
* Deletes a live checkpoint and marks its routed outputs as forgotten so retirement
|
|
1264
1310
|
* can still find them. Preserves retirement tombstones. Stop the follower first,
|
|
1265
1311
|
* or use a new generation.
|
|
1266
|
-
* Pass the binding from `declaration.at(params)` for a
|
|
1267
|
-
* key deletes the checkpoint and leaves the route records live.
|
|
1312
|
+
* Pass the binding from `declaration.at(params)`, or `declaration.singleton`, for a
|
|
1313
|
+
* routed projection. A bare key deletes the checkpoint and leaves the route records live.
|
|
1268
1314
|
* Delete stream outputs first, because forgetting restarts their producer sequences.
|
|
1269
1315
|
*/
|
|
1270
1316
|
const forget = (projection) => Effect.gen(function* () {
|
|
1271
1317
|
assertCheckpointKeyVersion(projection);
|
|
1272
1318
|
if (projection.commit.remove === void 0) return yield* new ProjectionFault({
|
|
1273
1319
|
phase: "checkpoint",
|
|
1274
|
-
reason: "
|
|
1275
|
-
message: "This Commit does not support forgetting"
|
|
1320
|
+
reason: new UnsupportedComposition({ message: "This Commit does not support forgetting" })
|
|
1276
1321
|
});
|
|
1277
1322
|
yield* projection.commit.remove(projection);
|
|
1278
1323
|
return yield* Effect.void;
|
|
@@ -1323,8 +1368,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
|
|
|
1323
1368
|
const pending = before.record.pending;
|
|
1324
1369
|
if (pending !== void 0 && !isPinned(projection.commit)) return yield* new ProjectionFault({
|
|
1325
1370
|
phase: "load",
|
|
1326
|
-
reason:
|
|
1327
|
-
message: `Commit ${projection.commit.name} cannot resume a pinned unit`
|
|
1371
|
+
reason: new InvalidRecord({ message: `Commit ${projection.commit.name} cannot resume a pinned unit` })
|
|
1328
1372
|
});
|
|
1329
1373
|
let batch;
|
|
1330
1374
|
let counts;
|
|
@@ -1512,13 +1556,16 @@ const hint = Effect.fn("Projection.hint")(function* (input, address, offset, int
|
|
|
1512
1556
|
const { wire: reader } = yield* address.stream;
|
|
1513
1557
|
const storageFailure = (cause) => new ProjectionFault({
|
|
1514
1558
|
phase: "read",
|
|
1515
|
-
reason: "storage-failure",
|
|
1516
1559
|
input,
|
|
1517
|
-
|
|
1518
|
-
|
|
1560
|
+
reason: cause
|
|
1561
|
+
});
|
|
1562
|
+
const from = yield* storedOffset(offset, {
|
|
1563
|
+
phase: "read",
|
|
1564
|
+
input,
|
|
1565
|
+
what: `The offset of ${input}`
|
|
1519
1566
|
});
|
|
1520
1567
|
return yield* reader.readNext(address.id, {
|
|
1521
|
-
offset,
|
|
1568
|
+
offset: from,
|
|
1522
1569
|
cursor
|
|
1523
1570
|
}).pipe(Effect.tap((result) => Ref.update(cursors, (current) => ({
|
|
1524
1571
|
...current,
|
|
@@ -1526,18 +1573,18 @@ const hint = Effect.fn("Projection.hint")(function* (input, address, offset, int
|
|
|
1526
1573
|
}))), Effect.flatMap((result) => result.closed && result.messages.length === 0 ? Effect.never : Effect.void), Effect.catchTags({
|
|
1527
1574
|
InvalidReadRequest: (cause) => new ProjectionFault({
|
|
1528
1575
|
phase: "read",
|
|
1529
|
-
reason: "invalid-source",
|
|
1530
1576
|
input,
|
|
1531
|
-
|
|
1532
|
-
|
|
1577
|
+
reason: new InvalidSource({
|
|
1578
|
+
message: cause.message,
|
|
1579
|
+
cause
|
|
1580
|
+
})
|
|
1533
1581
|
}),
|
|
1534
1582
|
StreamNotFound: () => Effect.void,
|
|
1535
1583
|
StreamGone: () => Effect.void,
|
|
1536
1584
|
NotSupported: (error) => new ProjectionFault({
|
|
1537
1585
|
phase: "read",
|
|
1538
|
-
reason: "unsupported-composition",
|
|
1539
1586
|
input,
|
|
1540
|
-
message: `${address.id} does not support ${error.feature}`
|
|
1587
|
+
reason: new UnsupportedComposition({ message: `${address.id} does not support ${error.feature}` })
|
|
1541
1588
|
}),
|
|
1542
1589
|
StorageFault: storageFailure,
|
|
1543
1590
|
TransportFault: storageFailure
|
|
@@ -1562,15 +1609,11 @@ const hint = Effect.fn("Projection.hint")(function* (input, address, offset, int
|
|
|
1562
1609
|
const follow = (projection, options = {}) => Stream.unwrap(Effect.gen(function* () {
|
|
1563
1610
|
yield* validateOptions(options);
|
|
1564
1611
|
const interval = options.repairIntervalMs ?? 3e4;
|
|
1565
|
-
if (!Number.isSafeInteger(interval) || interval <= 0) return yield* new
|
|
1566
|
-
phase: "load",
|
|
1567
|
-
reason: "invalid-options",
|
|
1568
|
-
message: "repairIntervalMs must be a positive safe integer"
|
|
1569
|
-
});
|
|
1612
|
+
if (!Number.isSafeInteger(interval) || interval <= 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection.follow option repairIntervalMs must be a positive safe integer, got ${String(interval)}`));
|
|
1570
1613
|
const cursors = yield* Ref.make({});
|
|
1571
|
-
const schedule = (options.retry ?? (yield* ProjectionRetry)).pipe(Schedule.tap(({ input }) => Schema.is(ProjectionFault)(input) && input.
|
|
1614
|
+
const schedule = (options.retry ?? (yield* ProjectionRetry)).pipe(Schedule.tap(({ input }) => Schema.is(ProjectionFault)(input) && input.isRetryable ? Effect.logWarning("Projection.follow retry", input) : Effect.void));
|
|
1572
1615
|
const retrying = (effect) => Effect.retry(effect, {
|
|
1573
|
-
while: (fault) => Schema.is(ProjectionFault)(fault) && fault.
|
|
1616
|
+
while: (fault) => Schema.is(ProjectionFault)(fault) && fault.isRetryable,
|
|
1574
1617
|
schedule
|
|
1575
1618
|
});
|
|
1576
1619
|
const wake = (offsets) => Effect.raceAllFirst(Array.map(inputEntries(projection.inputs), ([name, address]) => hint(name, address, offsets[name] ?? ZERO_OFFSET, interval, cursors)));
|
|
@@ -1612,28 +1655,38 @@ const bindingDelay = (schedule, attempts) => Effect.gen(function* () {
|
|
|
1612
1655
|
return Option.some(delay);
|
|
1613
1656
|
}).pipe(Pull.catchDone(() => Effect.succeedNone), Effect.catchCause((cause) => Effect.logError("Projection binding retry schedule failed", cause).pipe(Effect.as(Option.none()))));
|
|
1614
1657
|
// src/registry.ts
|
|
1658
|
+
/** A declaration, as opposed to one of its bindings. */
|
|
1659
|
+
const isDeclarationTarget = (target) => "singleton" in target || "at" in target;
|
|
1615
1660
|
const RunnerEvent = Data.taggedEnum();
|
|
1616
|
-
const registrations = /* @__PURE__ */ new WeakMap();
|
|
1617
1661
|
/** Optional in-process view of Projection.attach runners. */
|
|
1618
|
-
var Registry = class
|
|
1662
|
+
var Registry = class extends Context.Service()("@streamsy/projection/Registry") {
|
|
1619
1663
|
/** Match a binding's projection id and encoded params, independent of key order. */
|
|
1620
1664
|
static isFor = (binding) => (event) => event.projection === binding.id && Record.size(event.params) === Record.size(binding.params) && Array.every(Record.toEntries(binding.params), ([key, value]) => event.params[key] === value);
|
|
1621
|
-
/**
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1665
|
+
/**
|
|
1666
|
+
* The runners attached to the storage owner. The state lives on the owner, so this
|
|
1667
|
+
* layer can sit anywhere beside the attach layers, and building it twice is harmless.
|
|
1668
|
+
*/
|
|
1669
|
+
static layer = Layer.effect(this, Effect.map(StorageOwner, (owner) => registrationOf(owner).registry));
|
|
1670
|
+
};
|
|
1671
|
+
/**
|
|
1672
|
+
* The runners attached to one storage owner and their observations. Every
|
|
1673
|
+
* `Registry.layer` over the owner is a view of this one state.
|
|
1674
|
+
*/
|
|
1675
|
+
const RegistrySlot = new OwnerSlot(() => {
|
|
1676
|
+
const runners = /* @__PURE__ */ new Map();
|
|
1677
|
+
const updates = Effect.runSync(PubSub.sliding(1));
|
|
1678
|
+
const events = Effect.runSync(PubSub.unbounded());
|
|
1679
|
+
const status = Effect.suspend(() => Effect.forEach(runners.values(), (runner) => runner.status));
|
|
1680
|
+
const find = (target) => Effect.suspend(() => {
|
|
1681
|
+
const id = Predicate.isString(target) ? target : target.id;
|
|
1682
|
+
const found = Option.fromUndefinedOr(runners.get(id));
|
|
1683
|
+
return Effect.fromOption(found).pipe(Effect.mapError(() => new NotAttached({ projection: id })));
|
|
1684
|
+
});
|
|
1685
|
+
const publish = PubSub.publish(updates, void 0).pipe(Effect.asVoid);
|
|
1686
|
+
const snapshot = status.pipe(Effect.asSome, Effect.catch((fault) => Effect.logWarning("Projection.Registry changes snapshot failed", fault).pipe(Effect.as(Option.none()))));
|
|
1687
|
+
const observations = Stream.fromPull(Effect.map(PubSub.subscribe(events), PubSub.takeAll)).pipe(Stream.scoped);
|
|
1688
|
+
return {
|
|
1689
|
+
registry: Registry.of({
|
|
1637
1690
|
status,
|
|
1638
1691
|
events: observations,
|
|
1639
1692
|
awaitOffset: Effect.fn("Projection.Registry.awaitOffset")(function* (binding, input, offset) {
|
|
@@ -1642,8 +1695,7 @@ var Registry = class Registry extends Context.Service()("@streamsy/projection/Re
|
|
|
1642
1695
|
const runner = yield* find(binding);
|
|
1643
1696
|
if (runner.generation !== binding.generation) return yield* new ProjectionFault({
|
|
1644
1697
|
phase: "load",
|
|
1645
|
-
reason:
|
|
1646
|
-
message: `Attached generation of ${binding.id} is ${runner.generation}, but the binding uses generation ${binding.generation}`
|
|
1698
|
+
reason: new GenerationMismatch({ message: `Attached generation of ${binding.id} is ${runner.generation}, but the binding uses generation ${binding.generation}` })
|
|
1647
1699
|
});
|
|
1648
1700
|
const pull = yield* Stream.toPull(observations);
|
|
1649
1701
|
const checkpoint = yield* read(binding);
|
|
@@ -1668,40 +1720,39 @@ var Registry = class Registry extends Context.Service()("@streamsy/projection/Re
|
|
|
1668
1720
|
failed: Effect.fn("Projection.Registry.failed")(function* (target, options = {}) {
|
|
1669
1721
|
const limit = options.limit ?? 100;
|
|
1670
1722
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) return yield* Effect.die(/* @__PURE__ */ new RangeError("failed limit must be an integer from 1 to 1,000"));
|
|
1671
|
-
return yield* (yield* find(target)).failed(limit, Predicate.isString(target) ||
|
|
1723
|
+
return yield* (yield* find(target)).failed(limit, Predicate.isString(target) || isDeclarationTarget(target) ? void 0 : target);
|
|
1672
1724
|
}),
|
|
1673
1725
|
retry: Effect.fn("Projection.Registry.retry")(function* (target) {
|
|
1674
|
-
return yield* (yield* find(target)).retry(Predicate.isString(target) ||
|
|
1726
|
+
return yield* (yield* find(target)).retry(Predicate.isString(target) || isDeclarationTarget(target) ? void 0 : target);
|
|
1675
1727
|
}),
|
|
1676
1728
|
changes: Stream.unwrap(Effect.gen(function* () {
|
|
1677
1729
|
const subscription = yield* PubSub.subscribe(updates);
|
|
1678
1730
|
return Stream.concat(Stream.fromEffect(snapshot), Stream.fromSubscription(subscription).pipe(Stream.mapEffect(() => snapshot))).pipe(Stream.filterMap((value) => Result.fromOption(value, () => void 0)));
|
|
1679
1731
|
}))
|
|
1680
|
-
})
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
return registry;
|
|
1694
|
-
}));
|
|
1695
|
-
};
|
|
1696
|
-
/** @internal The event publisher installed by Registry.layer. */
|
|
1697
|
-
const eventPublisher = (registry) => registrations.get(registry)?.event;
|
|
1732
|
+
}),
|
|
1733
|
+
publish,
|
|
1734
|
+
event: (event) => PubSub.publish(events, event).pipe(Effect.asVoid),
|
|
1735
|
+
register: (runner) => Effect.acquireRelease(Effect.sync(() => {
|
|
1736
|
+
if (runners.has(runner.id)) throw new RangeError(`Projection ${runner.id} is already attached to this registry`);
|
|
1737
|
+
runners.set(runner.id, runner);
|
|
1738
|
+
}).pipe(Effect.andThen(publish)), () => Effect.sync(() => {
|
|
1739
|
+
runners.delete(runner.id);
|
|
1740
|
+
}).pipe(Effect.andThen(publish))).pipe(Effect.asVoid)
|
|
1741
|
+
};
|
|
1742
|
+
});
|
|
1743
|
+
/** @internal The registry state of a storage owner. */
|
|
1744
|
+
const registrationOf = (owner) => ownerParts(owner).slot(RegistrySlot);
|
|
1698
1745
|
/** @internal Register in the attach scope and return its pass notification. */
|
|
1699
|
-
const registerRunner = (
|
|
1700
|
-
const registration =
|
|
1701
|
-
return registration
|
|
1746
|
+
const registerRunner = (owner, runner) => {
|
|
1747
|
+
const registration = registrationOf(owner);
|
|
1748
|
+
return registration.register(runner).pipe(Effect.as(registration.publish));
|
|
1702
1749
|
};
|
|
1703
1750
|
// src/failure.ts
|
|
1704
|
-
|
|
1751
|
+
/** The stored mark reason of a binding that a non-retryable handler error stopped. */
|
|
1752
|
+
const nonRetryableHandlerReason = "NonRetryableHandler";
|
|
1753
|
+
const isMarkReason = Schema.is(Schema.Union([ProjectionFaultReasonTag, Schema.Literal(nonRetryableHandlerReason)]));
|
|
1754
|
+
/** A stored reason from an older release, such as `token-conflict`, reads as no reason. */
|
|
1755
|
+
const knownMarkReason = (reason) => Option.filter(reason, isMarkReason);
|
|
1705
1756
|
const marked = (reason) => Cause.isFailReason(reason) && Predicate.hasProperty(reason.error, NonRetryable) && reason.error[NonRetryable] === true;
|
|
1706
1757
|
const hasNonRetryableHandler = (cause) => Array.some(cause.reasons, marked);
|
|
1707
1758
|
/** Unknown handler errors and defects retry; only a known non-retryable fault stops work. */
|
|
@@ -1709,57 +1760,48 @@ const retryable = (cause) => !Array.some(cause.reasons, (reason) => {
|
|
|
1709
1760
|
if (!Cause.isFailReason(reason)) return false;
|
|
1710
1761
|
const { error } = reason;
|
|
1711
1762
|
if (marked(reason)) return true;
|
|
1712
|
-
return (Schema.is(ProjectionFault)(error) || Schema.is(StorageFault)(error)) && !error.
|
|
1763
|
+
return (Schema.is(ProjectionFault)(error) || Schema.is(StorageFault)(error)) && !error.isRetryable;
|
|
1713
1764
|
});
|
|
1714
1765
|
const runnerFailure = (cause, at) => ({
|
|
1715
1766
|
at,
|
|
1716
|
-
|
|
1717
|
-
reason: Cause.findErrorOption(cause).pipe(Option.filter(Schema.is(ProjectionFault)), Option.map((fault) => fault.reason)),
|
|
1767
|
+
isRetryable: retryable(cause),
|
|
1768
|
+
reason: Cause.findErrorOption(cause).pipe(Option.filter(Schema.is(ProjectionFault)), Option.map((fault) => fault.reason._tag)),
|
|
1718
1769
|
message: Cause.pretty(cause).slice(0, 1e3)
|
|
1719
1770
|
});
|
|
1720
|
-
// src/storage-fault.ts
|
|
1721
|
-
/** Preserve SQL retryability at the runner's storage boundary. */
|
|
1722
|
-
const storageFault = (operation) => (cause) => new StorageFault({
|
|
1723
|
-
operation,
|
|
1724
|
-
message: cause.message,
|
|
1725
|
-
retryable: cause.isRetryable,
|
|
1726
|
-
cause
|
|
1727
|
-
});
|
|
1728
1771
|
// src/triggers.ts
|
|
1729
1772
|
const DEFAULT_LIMIT$1 = 1e3;
|
|
1730
1773
|
const decodeFrontierMessage = Schema.decodeEffect(Schema.fromJsonString(Streamsy.FrontierMessage));
|
|
1731
1774
|
const decoder = new TextDecoder();
|
|
1732
1775
|
const invalid = (id, message, cause) => new ProjectionFault({
|
|
1733
1776
|
phase: "read",
|
|
1734
|
-
reason:
|
|
1735
|
-
|
|
1736
|
-
|
|
1777
|
+
reason: new InvalidSource({
|
|
1778
|
+
message: `${message}: ${id}`,
|
|
1779
|
+
cause
|
|
1780
|
+
})
|
|
1781
|
+
});
|
|
1782
|
+
const undecodable = (id, message, cause) => new ProjectionFault({
|
|
1783
|
+
phase: "read",
|
|
1784
|
+
reason: new DecodeFault({
|
|
1785
|
+
message: `${message}: ${id}`,
|
|
1786
|
+
cause
|
|
1787
|
+
})
|
|
1737
1788
|
});
|
|
1738
1789
|
/** Persistent local ingestion on both hosts; process hosts also ingest and follow other owners. */
|
|
1739
1790
|
const triggersOf = (projection, generation, declarations, match, marks, host = "process") => Effect.gen(function* () {
|
|
1740
|
-
const
|
|
1741
|
-
const records =
|
|
1742
|
-
const boundary = yield* Effect.serviceOption(CommitBoundary);
|
|
1743
|
-
if (Option.isNone(records) || Option.isNone(boundary)) return yield* Effect.die(/* @__PURE__ */ new Error(`Projection ${projection} cannot attach triggers: use a local memory or SQL storage layer.`));
|
|
1744
|
-
const owner = records.value;
|
|
1745
|
-
const transaction = boundary.value;
|
|
1791
|
+
const transaction = yield* StorageOwner;
|
|
1792
|
+
const { storage, records: owner } = ownerParts(transaction);
|
|
1746
1793
|
const permit = yield* Semaphore.make(1);
|
|
1747
1794
|
const cursors = /* @__PURE__ */ new Map();
|
|
1748
1795
|
const stopped = /* @__PURE__ */ new Map();
|
|
1749
1796
|
const streams = /* @__PURE__ */ new Map();
|
|
1750
1797
|
const remote = /* @__PURE__ */ new Map();
|
|
1751
|
-
const isRemote = (service) => Option.isSome(service) && !Array.some([
|
|
1752
|
-
storage,
|
|
1753
|
-
owner,
|
|
1754
|
-
transaction
|
|
1755
|
-
], (local) => service.value.owner === ownerOf(local));
|
|
1756
1798
|
for (const declaration of declarations) {
|
|
1757
1799
|
const { id } = declaration.address({});
|
|
1758
|
-
const service = yield* Effect.
|
|
1759
|
-
if (
|
|
1800
|
+
const service = yield* Effect.service(declaration);
|
|
1801
|
+
if (service.owner !== transaction.id) {
|
|
1760
1802
|
if (host === "wakeup") return yield* Effect.die(/* @__PURE__ */ new RangeError(`Trigger ${id}: ProjectionWakeup.attach accepts only triggers on its own storage owner`));
|
|
1761
1803
|
remote.set(id, {
|
|
1762
|
-
wire: service.
|
|
1804
|
+
wire: service.wire,
|
|
1763
1805
|
ahead: true,
|
|
1764
1806
|
changed: yield* Deferred.make()
|
|
1765
1807
|
});
|
|
@@ -1780,9 +1822,9 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
|
|
|
1780
1822
|
const cached = cursors.get(key);
|
|
1781
1823
|
if (cached !== void 0) return cached;
|
|
1782
1824
|
const saved = yield* owner.read(key);
|
|
1783
|
-
const from = Option.isNone(saved) ?
|
|
1825
|
+
const from = Option.isNone(saved) ? StreamsyOffset.make(ZERO_OFFSET) : yield* Schema.decodeEffect(StreamsyOffset)(saved.value).pipe(Effect.mapError((cause) => new StorageFault({
|
|
1784
1826
|
operation: "projection.trigger.cursor",
|
|
1785
|
-
|
|
1827
|
+
isRetryable: false,
|
|
1786
1828
|
message: `Invalid trigger cursor for ${projection}`,
|
|
1787
1829
|
cause
|
|
1788
1830
|
})));
|
|
@@ -1816,12 +1858,13 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
|
|
|
1816
1858
|
for (const message of messages) {
|
|
1817
1859
|
const event = yield* decodeFrontierMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => new ProjectionFault({
|
|
1818
1860
|
phase: "read",
|
|
1819
|
-
reason:
|
|
1820
|
-
|
|
1821
|
-
|
|
1861
|
+
reason: new DecodeFault({
|
|
1862
|
+
message: `Cannot decode trigger ${id} at offset ${message.offset}`,
|
|
1863
|
+
cause
|
|
1864
|
+
})
|
|
1822
1865
|
})));
|
|
1823
|
-
if (!
|
|
1824
|
-
const binding = match(StreamId.make(
|
|
1866
|
+
if (!DurableState.isChange(event)) continue;
|
|
1867
|
+
const binding = match(StreamId.make(DurableState.isUpsert(event) ? event.value.stream : event.key));
|
|
1825
1868
|
if (Option.isSome(binding)) found.add(binding.value[0]);
|
|
1826
1869
|
else yield* Effect.logWarning(`Projection ${projection} skipped unmatched trigger source ${event.key} from ${id}`);
|
|
1827
1870
|
}
|
|
@@ -1852,13 +1895,13 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
|
|
|
1852
1895
|
InvalidReadRequest: (cause) => Effect.fail(invalid(id, "Invalid trigger read", cause)),
|
|
1853
1896
|
TransportFault: (cause) => Effect.fail(new StorageFault({
|
|
1854
1897
|
operation: "projection.triggers.remote",
|
|
1855
|
-
|
|
1898
|
+
isRetryable: true,
|
|
1856
1899
|
message: `Cannot read remote trigger ${id}`,
|
|
1857
1900
|
cause
|
|
1858
1901
|
})),
|
|
1859
1902
|
StorageFault: (cause) => Effect.fail(new StorageFault({
|
|
1860
1903
|
operation: "projection.triggers.remote",
|
|
1861
|
-
|
|
1904
|
+
isRetryable: true,
|
|
1862
1905
|
message: `Cannot read remote trigger ${id}`,
|
|
1863
1906
|
cause
|
|
1864
1907
|
}))
|
|
@@ -1868,12 +1911,12 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
|
|
|
1868
1911
|
return;
|
|
1869
1912
|
}
|
|
1870
1913
|
const result = page.value;
|
|
1871
|
-
const offset = yield* Schema.decodeEffect(
|
|
1914
|
+
const offset = yield* Schema.decodeEffect(StreamsyOffset)(result.nextOffset).pipe(Effect.mapError((cause) => undecodable(id, "Invalid trigger page cursor", cause)));
|
|
1872
1915
|
const found = /* @__PURE__ */ new Set();
|
|
1873
1916
|
for (const message of result.messages) {
|
|
1874
|
-
const event = yield* decodeFrontierMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) =>
|
|
1875
|
-
if (!
|
|
1876
|
-
const binding = match(StreamId.make(
|
|
1917
|
+
const event = yield* decodeFrontierMessage(decoder.decode(message.data)).pipe(Effect.mapError((cause) => undecodable(id, `Cannot decode trigger page after ${from}`, cause)));
|
|
1918
|
+
if (!DurableState.isChange(event)) continue;
|
|
1919
|
+
const binding = match(StreamId.make(DurableState.isUpsert(event) ? event.value.stream : event.key));
|
|
1877
1920
|
if (Option.isSome(binding)) found.add(binding.value[0]);
|
|
1878
1921
|
else yield* Effect.logWarning(`Projection ${projection} skipped unmatched trigger source ${event.key} from ${id}`);
|
|
1879
1922
|
}
|
|
@@ -1950,8 +1993,8 @@ const triggersOf = (projection, generation, declarations, match, marks, host = "
|
|
|
1950
1993
|
const rescan = (id) => permit.withPermit(Effect.gen(function* () {
|
|
1951
1994
|
const key = streams.get(StreamId.make(id));
|
|
1952
1995
|
if (key === void 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Projection ${projection} has no trigger ${id}`));
|
|
1953
|
-
yield* transaction.withTransaction(owner.write(key, ZERO_OFFSET)).pipe(Effect.
|
|
1954
|
-
cursors.set(key,
|
|
1996
|
+
yield* transaction.withTransaction(owner.write(key, ZERO_OFFSET)).pipe(Effect.tap(() => Effect.sync(() => {
|
|
1997
|
+
cursors.set(key, StreamsyOffset.make(ZERO_OFFSET));
|
|
1955
1998
|
stopped.delete(id);
|
|
1956
1999
|
const state = remote.get(StreamId.make(id));
|
|
1957
2000
|
if (state !== void 0) state.ahead = true;
|
|
@@ -1988,38 +2031,40 @@ const Tail = Schema.Struct({
|
|
|
1988
2031
|
});
|
|
1989
2032
|
/** A serializable vector of fixed source tails, keyed by input name. */
|
|
1990
2033
|
const Tails = Schema.Record(Schema.String, Tail);
|
|
1991
|
-
const isOffset = Schema.is(
|
|
2034
|
+
const isOffset = Schema.is(StreamsyOffset);
|
|
1992
2035
|
const historyUnavailable = (input, message, cause) => new ProjectionFault({
|
|
1993
2036
|
phase: "read",
|
|
1994
|
-
reason: "history-unavailable",
|
|
1995
2037
|
input,
|
|
1996
|
-
|
|
1997
|
-
|
|
2038
|
+
reason: new HistoryUnavailable({
|
|
2039
|
+
message,
|
|
2040
|
+
cause
|
|
2041
|
+
})
|
|
1998
2042
|
});
|
|
1999
2043
|
const head = Effect.fn("Projection.catchUp.head")(function* (name, address) {
|
|
2000
2044
|
const { wire } = yield* address.stream;
|
|
2001
2045
|
const storageFailure = (cause) => new ProjectionFault({
|
|
2002
2046
|
phase: "read",
|
|
2003
|
-
reason: "storage-failure",
|
|
2004
2047
|
input: name,
|
|
2005
|
-
|
|
2006
|
-
cause
|
|
2048
|
+
reason: cause
|
|
2007
2049
|
});
|
|
2008
2050
|
const result = yield* wire.head(address.id).pipe(Effect.catchTags({
|
|
2009
|
-
StreamNotFound: (cause) =>
|
|
2051
|
+
StreamNotFound: (cause) => new ProjectionFault({
|
|
2052
|
+
phase: "read",
|
|
2053
|
+
input: name,
|
|
2054
|
+
reason: inputNotFound(address.id, cause)
|
|
2055
|
+
}),
|
|
2010
2056
|
StreamGone: (cause) => historyUnavailable(name, `Input stream ${address.id} is gone`, cause),
|
|
2011
2057
|
StorageFault: storageFailure,
|
|
2012
2058
|
TransportFault: storageFailure
|
|
2013
2059
|
}));
|
|
2014
|
-
if (!isOffset(result.
|
|
2060
|
+
if (!isOffset(result.offset)) return yield* new ProjectionFault({
|
|
2015
2061
|
phase: "read",
|
|
2016
|
-
reason: "invalid-source",
|
|
2017
2062
|
input: name,
|
|
2018
|
-
message: `Head of ${address.id} has an invalid offset`
|
|
2063
|
+
reason: new InvalidSource({ message: `Head of ${address.id} has an invalid offset` })
|
|
2019
2064
|
});
|
|
2020
2065
|
return {
|
|
2021
2066
|
stream: address.id,
|
|
2022
|
-
offset: result.
|
|
2067
|
+
offset: result.offset,
|
|
2023
2068
|
closed: result.closed
|
|
2024
2069
|
};
|
|
2025
2070
|
});
|
|
@@ -2034,20 +2079,19 @@ const validateTails = Effect.fnUntraced(function* (projection, targets) {
|
|
|
2034
2079
|
reportInput: true
|
|
2035
2080
|
})(targets).pipe(Effect.mapError((cause) => new ProjectionFault({
|
|
2036
2081
|
phase: "load",
|
|
2037
|
-
reason:
|
|
2038
|
-
|
|
2039
|
-
|
|
2082
|
+
reason: new DecodeFault({
|
|
2083
|
+
message: `Invalid tails for ${projection.id}: ${cause.message}`,
|
|
2084
|
+
cause
|
|
2085
|
+
})
|
|
2040
2086
|
})));
|
|
2041
2087
|
for (const [name, address] of inputEntries(projection.inputs)) if (decoded[name]?.stream !== address.id) return yield* new ProjectionFault({
|
|
2042
2088
|
phase: "load",
|
|
2043
|
-
reason: "identity-mismatch",
|
|
2044
2089
|
input: name,
|
|
2045
|
-
message: `Tail for ${name} must name stream ${address.id}`
|
|
2090
|
+
reason: new IdentityMismatch({ message: `Tail for ${name} must name stream ${address.id}` })
|
|
2046
2091
|
});
|
|
2047
2092
|
if (Record.size(decoded) !== Record.size(projection.inputs)) return yield* new ProjectionFault({
|
|
2048
2093
|
phase: "load",
|
|
2049
|
-
reason:
|
|
2050
|
-
message: `Tail input names differ from the declaration of ${projection.id}`
|
|
2094
|
+
reason: new IdentityMismatch({ message: `Tail input names differ from the declaration of ${projection.id}` })
|
|
2051
2095
|
});
|
|
2052
2096
|
return decoded;
|
|
2053
2097
|
});
|
|
@@ -2055,17 +2099,15 @@ const measure = Effect.fnUntraced(function* (projection, targets, verifyHeads) {
|
|
|
2055
2099
|
const { record } = yield* restore(projection, projection.commit);
|
|
2056
2100
|
if (record.ended) return yield* new ProjectionFault({
|
|
2057
2101
|
phase: "load",
|
|
2058
|
-
reason:
|
|
2059
|
-
message: `Binding of ${projection.id} ended after an input was lost`
|
|
2102
|
+
reason: new HistoryUnavailable({ message: `Binding of ${projection.id} ended after an input was lost` })
|
|
2060
2103
|
});
|
|
2061
2104
|
const entries = yield* Effect.forEach(inputEntries(projection.inputs), Effect.fnUntraced(function* ([name, address]) {
|
|
2062
2105
|
const committed = record.inputs[name];
|
|
2063
2106
|
const target = targets[name];
|
|
2064
2107
|
if (!isOffset(committed)) return yield* new ProjectionFault({
|
|
2065
2108
|
phase: "load",
|
|
2066
|
-
reason: "invalid-record",
|
|
2067
2109
|
input: name,
|
|
2068
|
-
message: `Stored offset for ${name} is not a valid offset`
|
|
2110
|
+
reason: new InvalidRecord({ message: `Stored offset for ${name} is not a valid offset` })
|
|
2069
2111
|
});
|
|
2070
2112
|
if (verifyHeads) {
|
|
2071
2113
|
const current = yield* head(name, address);
|
|
@@ -2119,7 +2161,7 @@ const matcher = (declaration) => {
|
|
|
2119
2161
|
if (missing.length > 0) throw new RangeError(`Projection ${declaration.id} cannot attach: input ${name} does not give param ${Array.join(missing, ", ")}`);
|
|
2120
2162
|
}
|
|
2121
2163
|
const bound = (params) => {
|
|
2122
|
-
const binding = declaration
|
|
2164
|
+
const binding = bindDeclaration(declaration, params);
|
|
2123
2165
|
return Option.some([canonicalParams(binding.params), binding]);
|
|
2124
2166
|
};
|
|
2125
2167
|
return (id) => {
|
|
@@ -2151,15 +2193,14 @@ const bindingOf = (declaration, key) => Option.flatMap(Schema.decodeOption(Param
|
|
|
2151
2193
|
decoded[name] = result.value;
|
|
2152
2194
|
}
|
|
2153
2195
|
try {
|
|
2154
|
-
const binding = declaration
|
|
2196
|
+
const binding = bindDeclaration(declaration, decoded);
|
|
2155
2197
|
return canonicalParams(binding.params) === key ? Option.some(binding) : Option.none();
|
|
2156
2198
|
} catch {
|
|
2157
2199
|
return Option.none();
|
|
2158
2200
|
}
|
|
2159
2201
|
});
|
|
2160
2202
|
const startupInventory = Effect.fn("Projection.startupInventory")(function* (declaration) {
|
|
2161
|
-
const
|
|
2162
|
-
const list = Option.getOrUndefined(store)?.list;
|
|
2203
|
+
const list = declaredOf(declaration)?.commit.list;
|
|
2163
2204
|
const id = declaration.id;
|
|
2164
2205
|
return yield* Effect.gen(function* () {
|
|
2165
2206
|
if (list === void 0) return [];
|
|
@@ -2175,7 +2216,7 @@ const startupInventory = Effect.fn("Projection.startupInventory")(function* (dec
|
|
|
2175
2216
|
else yield* Effect.logWarning(`Projection ${id} skipped startup params ${key}: they no longer decode`);
|
|
2176
2217
|
}
|
|
2177
2218
|
return candidates;
|
|
2178
|
-
}).pipe(Effect.catchIf((fault) => fault.reason
|
|
2219
|
+
}).pipe(Effect.catchIf((fault) => Predicate.isTagged(fault.reason, "UnsupportedComposition") || Predicate.isTagged(fault.reason, "InvalidRecord"), (fault) => Effect.logWarning(`Projection ${id} skipped startup inventory: ${fault.message}. Supply attach bindings explicitly.`).pipe(Effect.as([]))));
|
|
2179
2220
|
});
|
|
2180
2221
|
/**
|
|
2181
2222
|
* A binding that faults with `history-unavailable` on an input whose head is
|
|
@@ -2184,7 +2225,7 @@ const startupInventory = Effect.fn("Projection.startupInventory")(function* (dec
|
|
|
2184
2225
|
* with no checkpoint reaches here. Any other head answer keeps the fault.
|
|
2185
2226
|
*/
|
|
2186
2227
|
const sourceGone = (inputs, cause) => Effect.gen(function* () {
|
|
2187
|
-
const fault = Cause.findErrorOption(cause).pipe(Option.filter((error) => Schema.is(ProjectionFault)(error) && error
|
|
2228
|
+
const fault = Cause.findErrorOption(cause).pipe(Option.filter((error) => Schema.is(ProjectionFault)(error) && isInputLoss(error)));
|
|
2188
2229
|
if (Option.isNone(fault) || fault.value.input === void 0) return false;
|
|
2189
2230
|
const input = fault.value.input;
|
|
2190
2231
|
const address = Array.findFirst(inputEntries(inputs), ([name]) => name === input);
|
|
@@ -2195,25 +2236,24 @@ const sourceGone = (inputs, cause) => Effect.gen(function* () {
|
|
|
2195
2236
|
StreamGone: () => Effect.succeed(true)
|
|
2196
2237
|
}), Effect.orElseSucceed(() => false));
|
|
2197
2238
|
});
|
|
2198
|
-
/**
|
|
2199
|
-
|
|
2200
|
-
*
|
|
2201
|
-
* over remote storage.
|
|
2202
|
-
*/
|
|
2203
|
-
const durableMarks = (projection, match, marks) => Effect.gen(function* () {
|
|
2204
|
-
const hooks = yield* Effect.serviceOption(CommitHooks);
|
|
2205
|
-
if (Option.isNone(hooks) || Option.isNone(marks)) return yield* Effect.die(/* @__PURE__ */ new Error(`Projection ${projection} cannot attach durably: the storage layer keeps no projection marks. Use a local memory or SQL storage layer, or pass durable: false.`));
|
|
2206
|
-
yield* hooks.value.beforeCommit((ids) => {
|
|
2239
|
+
/** Register the commit hook that marks each binding a transaction writes, in that transaction. */
|
|
2240
|
+
const durableMarks = (projection, match, owner) => Effect.gen(function* () {
|
|
2241
|
+
yield* owner.hooks.beforeCommit((ids) => {
|
|
2207
2242
|
const keys = /* @__PURE__ */ new Set();
|
|
2208
2243
|
for (const id of ids) {
|
|
2209
2244
|
const found = match(id);
|
|
2210
2245
|
if (Option.isSome(found)) keys.add(found.value[0]);
|
|
2211
2246
|
}
|
|
2212
|
-
return keys.size === 0 ? Effect.void : marks.
|
|
2247
|
+
return keys.size === 0 ? Effect.void : owner.marks.mark(projection, [...keys]);
|
|
2213
2248
|
});
|
|
2214
|
-
return marks
|
|
2249
|
+
return owner.marks;
|
|
2215
2250
|
});
|
|
2216
2251
|
/**
|
|
2252
|
+
* A transactional output on another storage owner can never commit. Check each declared
|
|
2253
|
+
* output once at layer build, so the app does not start with that wiring.
|
|
2254
|
+
*/
|
|
2255
|
+
const checkOwnedOutputs = (projection, owner, outputs) => Effect.forEach(outputs, ({ name, stream }) => Effect.flatMap(stream, (service) => service.owner === owner ? Effect.void : Effect.die(foreignOutput(projection, name, owner, service.owner))), { discard: true });
|
|
2256
|
+
/**
|
|
2217
2257
|
* One scoped commit subscription and pending set, shared by the two host
|
|
2218
2258
|
* adapters. The subscription exists when this effect returns, so a commit
|
|
2219
2259
|
* after that point always marks its binding.
|
|
@@ -2237,16 +2277,15 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
2237
2277
|
if (!Number.isSafeInteger(concurrency) || concurrency <= 0) throw new RangeError("Projection.attach concurrency must be a positive safe integer");
|
|
2238
2278
|
const match = matcher(declaration);
|
|
2239
2279
|
return Effect.gen(function* () {
|
|
2240
|
-
const storage = yield*
|
|
2241
|
-
const
|
|
2242
|
-
const maxIdLength =
|
|
2280
|
+
const storage = yield* StorageOwner;
|
|
2281
|
+
const parts = ownerParts(storage);
|
|
2282
|
+
const maxIdLength = durable ? parts.marks.maxProjectionIdLength : void 0;
|
|
2243
2283
|
if (maxIdLength !== void 0 && Array.fromIterable(declaration.id).length > maxIdLength) return yield* Effect.die(new StorageFault({
|
|
2244
2284
|
operation: "projection.attach",
|
|
2245
2285
|
message: `MySQL projection id must be at most ${maxIdLength} characters`,
|
|
2246
|
-
|
|
2286
|
+
isRetryable: false
|
|
2247
2287
|
}));
|
|
2248
|
-
const
|
|
2249
|
-
const publish = Option.isSome(registry) ? eventPublisher(registry.value) : void 0;
|
|
2288
|
+
const publish = registrationOf(storage).event;
|
|
2250
2289
|
const committed = yield* storage.committed;
|
|
2251
2290
|
const pending = /* @__PURE__ */ new Map();
|
|
2252
2291
|
const working = /* @__PURE__ */ new Set();
|
|
@@ -2258,8 +2297,7 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
2258
2297
|
const runActive = (binding, context) => Effect.acquireUseRelease(Effect.sync(() => {
|
|
2259
2298
|
active += 1;
|
|
2260
2299
|
}), () => {
|
|
2261
|
-
|
|
2262
|
-
return publish === void 0 ? running : running.pipe(Effect.tap((progress) => publish(RunnerEvent.Ran({
|
|
2300
|
+
return catchUp(binding, { limit }, context).pipe(Effect.flatMap((cycle) => progressOf(binding, cycle))).pipe(Effect.tap((progress) => publish(RunnerEvent.Ran({
|
|
2263
2301
|
projection: declaration.id,
|
|
2264
2302
|
params: binding.params,
|
|
2265
2303
|
status: progress.status,
|
|
@@ -2270,7 +2308,8 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
2270
2308
|
}, () => Effect.sync(() => {
|
|
2271
2309
|
active -= 1;
|
|
2272
2310
|
}));
|
|
2273
|
-
|
|
2311
|
+
yield* checkOwnedOutputs(declaration.id, storage.id, declaredOf(declaration)?.ownedOutputs ?? []);
|
|
2312
|
+
const marks = durable ? yield* durableMarks(declaration.id, match, parts) : memoryProjectionMarks();
|
|
2274
2313
|
let failure = Option.none();
|
|
2275
2314
|
let started = false;
|
|
2276
2315
|
const startPermit = yield* Semaphore.make(1);
|
|
@@ -2284,17 +2323,21 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
2284
2323
|
return true;
|
|
2285
2324
|
});
|
|
2286
2325
|
const seed = Effect.gen(function* () {
|
|
2287
|
-
const candidates = options.bindings === void 0 ? yield* startupInventory(declaration) : yield* options.bindings.pipe(Effect.map(Array.map((params) => declaration
|
|
2326
|
+
const candidates = options.bindings === void 0 ? yield* startupInventory(declaration) : yield* options.bindings.pipe(Effect.map(Array.map((params) => bindDeclaration(declaration, params))), Effect.catch((error) => Effect.logError(`Projection ${declaration.id} skipped startup replay: the bindings option failed`, error).pipe(Effect.as([]))));
|
|
2288
2327
|
const byKey = new Map(Array.map(candidates, (binding) => [canonicalParams(binding.params), binding]));
|
|
2289
2328
|
for (const chunk of Array.chunksOf([...byKey], SCHEDULE_CHUNK)) {
|
|
2290
2329
|
const keys = [];
|
|
2291
|
-
for (const [key, binding] of chunk) if (yield* prepare(binding).pipe(Effect.
|
|
2330
|
+
for (const [key, binding] of chunk) if (yield* prepare(binding).pipe(Effect.catchReasons("ProjectionFault", {
|
|
2331
|
+
RetiredGeneration: () => Effect.succeed(false),
|
|
2332
|
+
HistoryUnavailable: () => Effect.succeed(false),
|
|
2333
|
+
InputNotFound: () => Effect.succeed(false)
|
|
2334
|
+
}))) keys.push(key);
|
|
2292
2335
|
if (keys.length > 0) yield* marks.mark(declaration.id, keys).pipe(Effect.mapError(storageFault("marks.mark")));
|
|
2293
2336
|
}
|
|
2294
2337
|
}).pipe(Effect.mapError((cause) => new StorageFault({
|
|
2295
2338
|
operation: "projection.startup",
|
|
2296
2339
|
message: `Cannot queue startup replay for ${declaration.id}`,
|
|
2297
|
-
|
|
2340
|
+
isRetryable: retryable(Cause.fail(cause)),
|
|
2298
2341
|
cause
|
|
2299
2342
|
})));
|
|
2300
2343
|
const start = startPermit.withPermit(Effect.gen(function* () {
|
|
@@ -2341,7 +2384,7 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
2341
2384
|
if (pending.size > 0 || triggers !== void 0 && (triggers.retrying() || (yield* triggers.next))) return void 0;
|
|
2342
2385
|
return yield* waitDue;
|
|
2343
2386
|
});
|
|
2344
|
-
const dropped = (key, binding) => Effect.logWarning(`Projection ${declaration.id} dropped binding ${key}: its source was removed before its first run`).pipe(Effect.andThen(publish
|
|
2387
|
+
const dropped = (key, binding) => Effect.logWarning(`Projection ${declaration.id} dropped binding ${key}: its source was removed before its first run`).pipe(Effect.andThen(publish(RunnerEvent.Dropped({
|
|
2345
2388
|
projection: declaration.id,
|
|
2346
2389
|
params: binding.params
|
|
2347
2390
|
}))));
|
|
@@ -2395,8 +2438,8 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
2395
2438
|
const attempts = (state?.attempts ?? 0) + 1;
|
|
2396
2439
|
const failed = runnerFailure(exit.cause, yield* Clock.currentTimeMillis);
|
|
2397
2440
|
const budgetEnded = attempts >= (declaration.retry?.maxAttempts ?? Number.POSITIVE_INFINITY);
|
|
2398
|
-
const delay = !failed.
|
|
2399
|
-
if (failed.
|
|
2441
|
+
const delay = !failed.isRetryable || budgetEnded ? Option.none() : yield* bindingDelay(declaration.retry?.schedule, attempts);
|
|
2442
|
+
if (failed.isRetryable && Option.isNone(delay) && declaration.retry?.onExhausted !== void 0) {
|
|
2400
2443
|
const hook = declaration.retry.onExhausted;
|
|
2401
2444
|
const failedUnit = unit;
|
|
2402
2445
|
if (failedUnit === void 0) yield* Effect.logWarning(`Projection ${id} binding ${key} exhausted; skipped onExhausted because no unit formed`);
|
|
@@ -2415,7 +2458,7 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
2415
2458
|
reason
|
|
2416
2459
|
}
|
|
2417
2460
|
});
|
|
2418
|
-
|
|
2461
|
+
yield* publish(RunnerEvent.Failed({
|
|
2419
2462
|
projection: id,
|
|
2420
2463
|
params: binding.params,
|
|
2421
2464
|
attempts,
|
|
@@ -2490,15 +2533,18 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
2490
2533
|
return {
|
|
2491
2534
|
params: yield* Schema.decodeEffect(ParamsJson)(row.params).pipe(Effect.mapError((cause) => new StorageFault({
|
|
2492
2535
|
operation: "marks.failed",
|
|
2493
|
-
|
|
2536
|
+
isRetryable: false,
|
|
2494
2537
|
message: "Invalid stored binding params",
|
|
2495
2538
|
cause
|
|
2496
2539
|
}))),
|
|
2497
2540
|
attempts: row.attempts,
|
|
2498
2541
|
dueAt: row.stopped ? Option.none() : Option.some(row.dueAt),
|
|
2499
2542
|
stopped: row.stopped,
|
|
2500
|
-
exhausted: row.stopped && !Option.contains(Option.flatMap(row.failure, (failed) => failed.reason), "
|
|
2501
|
-
failure: row.failure
|
|
2543
|
+
exhausted: row.stopped && !Option.contains(Option.flatMap(row.failure, (failed) => knownMarkReason(failed.reason)), "NonRetryableHandler") && (row.attempts >= (declaration.retry?.maxAttempts ?? Number.POSITIVE_INFINITY) || Option.isNone(yield* bindingDelay(declaration.retry?.schedule, row.attempts))),
|
|
2544
|
+
failure: Option.map(row.failure, (stored) => ({
|
|
2545
|
+
...stored,
|
|
2546
|
+
reason: knownMarkReason(stored.reason)
|
|
2547
|
+
}))
|
|
2502
2548
|
};
|
|
2503
2549
|
}));
|
|
2504
2550
|
}),
|
|
@@ -2522,13 +2568,16 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
2522
2568
|
});
|
|
2523
2569
|
};
|
|
2524
2570
|
// src/attach.ts
|
|
2571
|
+
/** Look up each trigger class's service, with each class in the requirements. */
|
|
2572
|
+
const requireTriggers = (triggers) => Effect.forEach(triggers ?? [], (trigger) => Effect.service(trigger), { discard: true });
|
|
2525
2573
|
/** A defect of one drain pass, captured for logging with typed failures. */
|
|
2526
2574
|
var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Schema.Defect() }) {};
|
|
2527
2575
|
/**
|
|
2528
2576
|
* Run a projection whenever a local commit writes one of its inputs. The layer
|
|
2529
|
-
* subscribes to `
|
|
2577
|
+
* subscribes to `StorageOwner.committed` when it is built, so build it with the
|
|
2530
2578
|
* storage layer and before the app writes. For each written id, the input's
|
|
2531
|
-
* `parse` gives the params, and the runner runs `projection.at(params)
|
|
2579
|
+
* `parse` gives the params, and the runner runs `projection.at(params)`, or
|
|
2580
|
+
* `projection.singleton` for a projection without params.
|
|
2532
2581
|
* The background runner also queues startup replays from the checkpoint
|
|
2533
2582
|
* inventory or `options.bindings`.
|
|
2534
2583
|
*
|
|
@@ -2569,8 +2618,7 @@ const attach$1 = (projection, options = {}) => {
|
|
|
2569
2618
|
lastPassAt: Option.none(),
|
|
2570
2619
|
step
|
|
2571
2620
|
};
|
|
2572
|
-
const
|
|
2573
|
-
const changed = Option.isNone(registry) ? Effect.void : yield* registerRunner(registry.value, {
|
|
2621
|
+
const changed = yield* registerRunner(yield* StorageOwner, {
|
|
2574
2622
|
id: projection.id,
|
|
2575
2623
|
generation: projection.generation,
|
|
2576
2624
|
schedule,
|
|
@@ -2684,7 +2732,11 @@ const decide = Effect.fn("Projection.decide")(function* (projection, spec) {
|
|
|
2684
2732
|
const address = projection.inputs[spec.input];
|
|
2685
2733
|
const attempt = Effect.gen(function* () {
|
|
2686
2734
|
const snapshot = yield* current(projection);
|
|
2687
|
-
const offset = snapshot.offsets[spec.input]
|
|
2735
|
+
const offset = yield* storedOffset(snapshot.offsets[spec.input], {
|
|
2736
|
+
phase: "load",
|
|
2737
|
+
input: spec.input,
|
|
2738
|
+
what: `The snapshot offset of ${spec.input}`
|
|
2739
|
+
});
|
|
2688
2740
|
const { value, items } = yield* spec.decide(snapshot);
|
|
2689
2741
|
if (!Array.isReadonlyArrayNonEmpty(items)) return {
|
|
2690
2742
|
value,
|
|
@@ -2737,20 +2789,22 @@ const cleanStream = (address, wire, mode) => {
|
|
|
2737
2789
|
StreamGone: () => Effect.succeed("absent")
|
|
2738
2790
|
}), Effect.mapError((cause) => new ProjectionFault({
|
|
2739
2791
|
phase: "checkpoint",
|
|
2740
|
-
reason:
|
|
2741
|
-
message: `Cannot ${mode} output ${id}`,
|
|
2742
|
-
cause
|
|
2792
|
+
reason: outputReason(`Cannot ${mode} output ${id}`, cause)
|
|
2743
2793
|
})));
|
|
2744
2794
|
};
|
|
2745
|
-
|
|
2746
|
-
|
|
2795
|
+
const paramsAndOptions = (args) => args.length === 2 ? args : [{}, args[0]];
|
|
2796
|
+
/**
|
|
2797
|
+
* Retire one binding and clean up its exclusively owned generation outputs. A declaration
|
|
2798
|
+
* without params takes no params argument: `retire(declaration, { generation })`.
|
|
2799
|
+
*/
|
|
2800
|
+
const retire = (declaration, ...args) => {
|
|
2801
|
+
const [params, options] = paramsAndOptions(args);
|
|
2747
2802
|
const bound = bindAtGeneration(declaration, params, options.generation);
|
|
2748
2803
|
const mode = options.streams ?? "remove";
|
|
2749
2804
|
return Effect.gen(function* () {
|
|
2750
2805
|
if (bound?.commit.retire === void 0) return yield* new ProjectionFault({
|
|
2751
2806
|
phase: "checkpoint",
|
|
2752
|
-
reason: "
|
|
2753
|
-
message: "Retirement requires a projection declaration with a Commit that supports it"
|
|
2807
|
+
reason: new UnsupportedComposition({ message: "Retirement requires a projection declaration with a Commit that supports it" })
|
|
2754
2808
|
});
|
|
2755
2809
|
const shared = [];
|
|
2756
2810
|
const owned = [];
|
|
@@ -2783,11 +2837,7 @@ const retire = (declaration, params, options) => {
|
|
|
2783
2837
|
const owner = yield* CurrentOwner;
|
|
2784
2838
|
const results = [...shared];
|
|
2785
2839
|
const clean = (output, address, service) => {
|
|
2786
|
-
if (owner !== void 0 && service.owner !== owner) return Effect.
|
|
2787
|
-
phase: "checkpoint",
|
|
2788
|
-
reason: "unsupported-composition",
|
|
2789
|
-
message: `Output ${address.id} does not share the transaction owner`
|
|
2790
|
-
}));
|
|
2840
|
+
if (owner !== void 0 && service.owner !== owner) return Effect.die(foreignOutput(bound.id, address.id, owner, service.owner));
|
|
2791
2841
|
return cleanStream(address, service.wire, mode).pipe(Effect.map((result) => ({
|
|
2792
2842
|
output,
|
|
2793
2843
|
id: address.id,
|
|
@@ -2805,9 +2855,10 @@ const retire = (declaration, params, options) => {
|
|
|
2805
2855
|
const definition = routes.get(output);
|
|
2806
2856
|
const invalid = (cause) => new ProjectionFault({
|
|
2807
2857
|
phase: "checkpoint",
|
|
2808
|
-
reason:
|
|
2809
|
-
|
|
2810
|
-
|
|
2858
|
+
reason: new InvalidRecord({
|
|
2859
|
+
message: `Cannot restore routed output ${output} at ${id}`,
|
|
2860
|
+
cause
|
|
2861
|
+
})
|
|
2811
2862
|
});
|
|
2812
2863
|
const address = yield* Effect.try({
|
|
2813
2864
|
try: () => definition?.restore(id),
|
|
@@ -2865,7 +2916,7 @@ function frontier(definition) {
|
|
|
2865
2916
|
initial: null
|
|
2866
2917
|
},
|
|
2867
2918
|
mapAccumBatch: (_state, batch, unit) => {
|
|
2868
|
-
const source = isDeclaration(input) ? input
|
|
2919
|
+
const source = isDeclaration(input) ? bindDeclaration(input, unit.params) : input;
|
|
2869
2920
|
const stream = StreamId.make(source.id);
|
|
2870
2921
|
if (batch.source.gone === true) return [null, { wake: [DurableState.remove("stream", stream)] }];
|
|
2871
2922
|
const range = unit.ranges.source;
|
|
@@ -2986,8 +3037,7 @@ const upperBound = (keys, after) => {
|
|
|
2986
3037
|
};
|
|
2987
3038
|
const unwritable = (id) => new ProjectionFault({
|
|
2988
3039
|
phase: "process",
|
|
2989
|
-
reason:
|
|
2990
|
-
message: `The rows of ${id} have no open memory owner transaction on this fiber. Write them inside the storage owner's transaction.`
|
|
3040
|
+
reason: new UnsupportedComposition({ message: `The rows of ${id} have no open memory owner transaction on this fiber. Write them inside the storage owner's transaction.` })
|
|
2991
3041
|
});
|
|
2992
3042
|
const page = (keys, rows, options) => {
|
|
2993
3043
|
const first = options.after === void 0 ? 0 : upperBound(keys, options.after);
|
|
@@ -3003,14 +3053,14 @@ const page = (keys, rows, options) => {
|
|
|
3003
3053
|
* the unit sees committed rows only. A read inside the transaction but on a forked
|
|
3004
3054
|
* fiber cannot enlist either, so it also sees committed rows only.
|
|
3005
3055
|
*/
|
|
3006
|
-
const
|
|
3056
|
+
const memoryStore = (enlist) => {
|
|
3007
3057
|
const committed = /* @__PURE__ */ new Map();
|
|
3008
3058
|
/** Sorted keys of committed rows, by stream and collection, dropped when a commit changes them. */
|
|
3009
3059
|
const sorted = /* @__PURE__ */ new Map();
|
|
3010
3060
|
/** The open unit's writes. The owner runs one transaction at a time. */
|
|
3011
3061
|
let written;
|
|
3012
3062
|
/** True on the owner fiber inside its transaction, which then commits or drops `written`. */
|
|
3013
|
-
const inUnit = Effect.match(enlist(
|
|
3063
|
+
const inUnit = Effect.match(enlist({
|
|
3014
3064
|
onCommit: () => {
|
|
3015
3065
|
const writes = written;
|
|
3016
3066
|
written = void 0;
|
|
@@ -3170,21 +3220,10 @@ const makeStore = (owner) => {
|
|
|
3170
3220
|
})
|
|
3171
3221
|
};
|
|
3172
3222
|
};
|
|
3173
|
-
const stores = /* @__PURE__ */ new WeakMap();
|
|
3174
|
-
/** The one store of `owner`, so that every layer built over the owner shares its rows. */
|
|
3175
|
-
const memoryStore = (owner) => {
|
|
3176
|
-
let store = stores.get(owner);
|
|
3177
|
-
if (store === void 0) {
|
|
3178
|
-
store = makeStore(owner);
|
|
3179
|
-
stores.set(owner, store);
|
|
3180
|
-
}
|
|
3181
|
-
return store;
|
|
3182
|
-
};
|
|
3183
3223
|
const MYSQL_TEXT_KEY = "CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin";
|
|
3184
3224
|
const unsupported = () => Effect.fail(new ProjectionFault({
|
|
3185
3225
|
phase: "load",
|
|
3186
|
-
reason: "
|
|
3187
|
-
message: "Unsupported SQL dialect; StateTable supports sqlite, pg and mysql"
|
|
3226
|
+
reason: new UnsupportedComposition({ message: "Unsupported SQL dialect; StateTable supports sqlite, pg and mysql" })
|
|
3188
3227
|
}));
|
|
3189
3228
|
/** Create both tables. The SQLite DDL is unchanged since StateTable was added. */
|
|
3190
3229
|
const createTables = (sql) => sql.onDialectOrElse({
|
|
@@ -3286,8 +3325,7 @@ const unstorable = (sql, collection, key) => sql.onDialectOrElse({
|
|
|
3286
3325
|
const sqlStore = (sql) => ({
|
|
3287
3326
|
writer: (id) => Effect.flatMap(Effect.serviceOption(sql.transactionService), (transaction) => Option.isSome(transaction) ? Effect.void : Effect.fail(new ProjectionFault({
|
|
3288
3327
|
phase: "process",
|
|
3289
|
-
reason:
|
|
3290
|
-
message: `The SqlClient for the rows of ${id} has no open transaction. Use the storage owner's client inside its transaction.`
|
|
3328
|
+
reason: new UnsupportedComposition({ message: `The rows of ${id} have no open transaction on the storage owner's SQL client. Write them inside the storage owner's transaction.` })
|
|
3291
3329
|
}))),
|
|
3292
3330
|
head: (id, locked) => Effect.map(sql`SELECT applied_offset, epoch, snapshot_open FROM streamsy_state_heads WHERE stream_id = ${id} ${locked ? lockHead(sql) : sql``}`, Array.head),
|
|
3293
3331
|
saveHead: (id, head) => Effect.asVoid(saveHead(sql, id, head)),
|
|
@@ -3312,30 +3350,19 @@ const sqlStore = (sql) => ({
|
|
|
3312
3350
|
ORDER BY row_key ${options.limit === void 0 ? sql`` : sql`LIMIT ${options.limit}`}`,
|
|
3313
3351
|
unstorable: (collection, key) => unstorable(sql, collection, key)
|
|
3314
3352
|
});
|
|
3315
|
-
// src/state-table-
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
|
|
3326
|
-
/**
|
|
3327
|
-
|
|
3328
|
-
/** Keep rows in the host database. Run StateTable.migrate with the same client. */
|
|
3329
|
-
static layerSql = Layer.effect(this, Effect.map(SqlClient.SqlClient, (sql) => new BackendService(sqlStore(sql))));
|
|
3330
|
-
/**
|
|
3331
|
-
* Keep rows in the heap and join the memory owner's transaction. Every layer over one
|
|
3332
|
-
* owner shares its rows. A read outside a unit, or on a fiber that the unit forked,
|
|
3333
|
-
* sees committed rows only.
|
|
3334
|
-
*/
|
|
3335
|
-
static layerMemory = Layer.effect(this, Effect.map(CommitBoundary, (boundary) => new BackendService(memoryStore(ownerOf(boundary)))));
|
|
3336
|
-
};
|
|
3337
|
-
/** The store of the host's backend. */
|
|
3338
|
-
const currentStore = Effect.flatMap(StateTableBackend, (service) => service instanceof BackendService ? Effect.succeed(service[BackendStore]) : Effect.die(/* @__PURE__ */ new TypeError("Expected a StateTable backend service")));
|
|
3353
|
+
// src/state-table-owner.ts
|
|
3354
|
+
/**
|
|
3355
|
+
* The one row store of each owner, so that every StateTable and FoldByKey over the owner
|
|
3356
|
+
* shares its rows. A SQL owner keeps them on its client, a memory owner in the heap.
|
|
3357
|
+
*/
|
|
3358
|
+
const storeSlot = new OwnerSlot(({ backend }) => OwnerBackend.$match(backend, {
|
|
3359
|
+
Sql: ({ client }) => sqlStore(client),
|
|
3360
|
+
Memory: ({ enlist }) => memoryStore(enlist)
|
|
3361
|
+
}));
|
|
3362
|
+
/** The row store of `owner`. */
|
|
3363
|
+
const ownerStore = (owner) => ownerParts(owner).slot(storeSlot);
|
|
3364
|
+
/** The row store of the storage owner in context. */
|
|
3365
|
+
const currentStore = Effect.map(StorageOwner, ownerStore);
|
|
3339
3366
|
// src/state-table.ts
|
|
3340
3367
|
var state_table_exports = /* @__PURE__ */ __exportAll({
|
|
3341
3368
|
clear: () => clear,
|
|
@@ -3354,9 +3381,12 @@ const empty = {
|
|
|
3354
3381
|
const appliedOffset = (store, id) => Effect.map(store.head(id, false), (stored) => Option.getOrElse(stored, () => empty).applied_offset);
|
|
3355
3382
|
const sqlFault = (id) => (cause) => new ProjectionFault({
|
|
3356
3383
|
phase: "process",
|
|
3357
|
-
reason:
|
|
3358
|
-
|
|
3359
|
-
|
|
3384
|
+
reason: storageFault(`stateTable.update ${id}`)(cause)
|
|
3385
|
+
});
|
|
3386
|
+
/** A storage or transport fault of a read is the reason of the fault. */
|
|
3387
|
+
const readFault = (cause) => new ProjectionFault({
|
|
3388
|
+
phase: "read",
|
|
3389
|
+
reason: cause
|
|
3360
3390
|
});
|
|
3361
3391
|
/** Writes outside the storage owner's transaction would outlive a rolled-back unit. */
|
|
3362
3392
|
const writer = (id) => Effect.gen(function* () {
|
|
@@ -3386,8 +3416,7 @@ const apply = Effect.fn("StateTable.apply")(function* (store, id, before, items)
|
|
|
3386
3416
|
onNone: () => store.upsertRow(id, row, epoch),
|
|
3387
3417
|
onSome: (reason) => Effect.fail(new ProjectionFault({
|
|
3388
3418
|
phase: "process",
|
|
3389
|
-
reason:
|
|
3390
|
-
message: `A stored message of ${id} has a row that the table cannot store. ${reason}`
|
|
3419
|
+
reason: new InvalidRecord({ message: `A stored message of ${id} has a row that the table cannot store. ${reason}` })
|
|
3391
3420
|
}))
|
|
3392
3421
|
}),
|
|
3393
3422
|
Delete: ({ collection, key }) => Option.isSome(store.unstorable(collection, key)) ? Effect.void : store.deleteRow(id, collection, key)
|
|
@@ -3398,55 +3427,59 @@ const apply = Effect.fn("StateTable.apply")(function* (store, id, before, items)
|
|
|
3398
3427
|
};
|
|
3399
3428
|
}, (effect, _store, id) => Effect.catchTag(effect, "SchemaError", (cause) => new ProjectionFault({
|
|
3400
3429
|
phase: "process",
|
|
3401
|
-
reason:
|
|
3402
|
-
|
|
3403
|
-
|
|
3430
|
+
reason: new InvalidRecord({
|
|
3431
|
+
message: `A stored message of ${id} is not a State message`,
|
|
3432
|
+
cause
|
|
3433
|
+
})
|
|
3404
3434
|
})));
|
|
3405
3435
|
/**
|
|
3406
|
-
* Create the row index on SQLite, Postgres or MySQL at host
|
|
3407
|
-
* migrations. A
|
|
3436
|
+
* Create the row index on a SQL storage owner (SQLite, Postgres or MySQL) at host
|
|
3437
|
+
* startup, outside storage migrations. A memory owner needs none, so it does nothing.
|
|
3408
3438
|
*/
|
|
3409
|
-
const migrate = Effect.
|
|
3410
|
-
yield*
|
|
3411
|
-
|
|
3439
|
+
const migrate = Effect.gen(function* () {
|
|
3440
|
+
const { backend } = ownerParts(yield* StorageOwner);
|
|
3441
|
+
if (OwnerBackend.$is("Sql")(backend)) yield* createTables(backend.client);
|
|
3442
|
+
}).pipe(Effect.withSpan("StateTable.migrate"));
|
|
3412
3443
|
const synchronize = (address) => Effect.gen(function* () {
|
|
3413
3444
|
const store = yield* writer(address.id);
|
|
3414
3445
|
const { wire } = yield* address.stream;
|
|
3415
3446
|
const unavailable = () => new ProjectionFault({
|
|
3416
3447
|
phase: "read",
|
|
3417
|
-
reason:
|
|
3418
|
-
message: `Required history of ${address.id} is unavailable`
|
|
3448
|
+
reason: new HistoryUnavailable({ message: `Required history of ${address.id} is unavailable` })
|
|
3419
3449
|
});
|
|
3420
|
-
const
|
|
3450
|
+
const notFound = (cause) => new ProjectionFault({
|
|
3421
3451
|
phase: "read",
|
|
3422
|
-
reason:
|
|
3423
|
-
message: `Cannot read ${address.id}`,
|
|
3424
|
-
cause
|
|
3452
|
+
reason: inputNotFound(address.id, cause)
|
|
3425
3453
|
});
|
|
3426
3454
|
const stored = yield* store.head(address.id, true);
|
|
3427
3455
|
const tail = yield* wire.head(address.id).pipe(Effect.catchTags({
|
|
3428
|
-
StreamNotFound:
|
|
3456
|
+
StreamNotFound: notFound,
|
|
3429
3457
|
StreamGone: unavailable,
|
|
3430
|
-
StorageFault:
|
|
3431
|
-
TransportFault:
|
|
3458
|
+
StorageFault: readFault,
|
|
3459
|
+
TransportFault: readFault
|
|
3432
3460
|
}));
|
|
3433
3461
|
let state = Option.getOrElse(stored, () => empty);
|
|
3434
|
-
if (Option.isNone(stored) || compare(state.applied_offset, tail.
|
|
3462
|
+
if (Option.isNone(stored) || compare(state.applied_offset, tail.offset) > 0) {
|
|
3435
3463
|
yield* store.clearRows(address.id);
|
|
3436
3464
|
state = empty;
|
|
3437
3465
|
}
|
|
3438
|
-
while (compare(state.applied_offset, tail.
|
|
3439
|
-
const
|
|
3466
|
+
while (compare(state.applied_offset, tail.offset) < 0) {
|
|
3467
|
+
const start = yield* storedOffset(state.applied_offset, {
|
|
3468
|
+
phase: "read",
|
|
3469
|
+
what: `The applied offset of ${address.id}`
|
|
3470
|
+
});
|
|
3471
|
+
const page = yield* wire.read(address.id, { offset: start }).pipe(Effect.catchTags({
|
|
3440
3472
|
InvalidReadRequest: (cause) => new ProjectionFault({
|
|
3441
3473
|
phase: "read",
|
|
3442
|
-
reason:
|
|
3443
|
-
|
|
3444
|
-
|
|
3474
|
+
reason: new InvalidSource({
|
|
3475
|
+
message: cause.message,
|
|
3476
|
+
cause
|
|
3477
|
+
})
|
|
3445
3478
|
}),
|
|
3446
|
-
StreamNotFound:
|
|
3479
|
+
StreamNotFound: notFound,
|
|
3447
3480
|
StreamGone: unavailable,
|
|
3448
|
-
StorageFault:
|
|
3449
|
-
TransportFault:
|
|
3481
|
+
StorageFault: readFault,
|
|
3482
|
+
TransportFault: readFault
|
|
3450
3483
|
}));
|
|
3451
3484
|
if (compare(page.nextOffset, state.applied_offset) <= 0) return yield* unavailable();
|
|
3452
3485
|
state = {
|
|
@@ -3498,11 +3531,7 @@ const reads = (id, collections) => {
|
|
|
3498
3531
|
};
|
|
3499
3532
|
}),
|
|
3500
3533
|
list: Effect.fn("StateTable.list")(function* (collection, options = {}) {
|
|
3501
|
-
if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit <= 0)) return yield* new
|
|
3502
|
-
phase: "load",
|
|
3503
|
-
reason: "invalid-options",
|
|
3504
|
-
message: "StateTable list limit must be a positive safe integer"
|
|
3505
|
-
});
|
|
3534
|
+
if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit <= 0)) return yield* Effect.die(/* @__PURE__ */ new RangeError(`StateTable list option limit must be a positive safe integer, got ${String(options.limit)}`));
|
|
3506
3535
|
const store = yield* currentStore;
|
|
3507
3536
|
const offset = yield* appliedOffset(store, id);
|
|
3508
3537
|
const found = yield* store.list(id, collection, options);
|
|
@@ -3520,6 +3549,8 @@ const reads = (id, collections) => {
|
|
|
3520
3549
|
};
|
|
3521
3550
|
/** The collections of a bound table, for `unit`. */
|
|
3522
3551
|
const TableCollections = Symbol.for("@streamsy/projection/internal/StateTableCollections");
|
|
3552
|
+
/** Private: tests read a memory store's committed rows through the owner's row store. */
|
|
3553
|
+
const TableStore = Symbol.for("@streamsy/projection/internal/StateTableStore");
|
|
3523
3554
|
/** A State stream's declaration, kept current by the ordinary projection runners. */
|
|
3524
3555
|
function define(state, options = {}) {
|
|
3525
3556
|
const id = `state-table/${state.key}`;
|
|
@@ -3535,13 +3566,13 @@ function define(state, options = {}) {
|
|
|
3535
3566
|
params: state.paramCodecs,
|
|
3536
3567
|
inputs: {}
|
|
3537
3568
|
}, ({ decoded, ...key }) => {
|
|
3538
|
-
const address = state
|
|
3569
|
+
const address = bindDeclaration(state, decoded);
|
|
3539
3570
|
const raw = Object.assign(StreamAddress.json(address.id, { schema: Schema.String }), {
|
|
3540
3571
|
stream: address.stream,
|
|
3541
3572
|
codec: Schema.String
|
|
3542
3573
|
});
|
|
3543
3574
|
Object.defineProperty(raw, RawCollections, { value: state.collections });
|
|
3544
|
-
const accepted = options.frontier
|
|
3575
|
+
const accepted = options.frontier === void 0 ? void 0 : bindDeclaration(options.frontier, decoded);
|
|
3545
3576
|
if (accepted?.id === address.id) throw new RangeError("A frontier stream may not name an input stream");
|
|
3546
3577
|
const bound = {
|
|
3547
3578
|
...key,
|
|
@@ -3552,7 +3583,16 @@ function define(state, options = {}) {
|
|
|
3552
3583
|
...reads(address.id, state.collections),
|
|
3553
3584
|
sync: () => synchronize(raw)
|
|
3554
3585
|
};
|
|
3555
|
-
return Object.
|
|
3586
|
+
return Object.defineProperties(bound, {
|
|
3587
|
+
[TableCollections]: { value: state.collections },
|
|
3588
|
+
[TableStore]: { value: ownerStore }
|
|
3589
|
+
});
|
|
3590
|
+
}, {
|
|
3591
|
+
commit: transaction,
|
|
3592
|
+
ownedOutputs: options.frontier === void 0 ? [] : [{
|
|
3593
|
+
name: "frontier",
|
|
3594
|
+
stream: outputService(options.frontier)
|
|
3595
|
+
}]
|
|
3556
3596
|
});
|
|
3557
3597
|
return Object.assign(declaration, {
|
|
3558
3598
|
inputs: { state },
|
|
@@ -3566,24 +3606,24 @@ const clearIndex = (id) => Effect.gen(function* () {
|
|
|
3566
3606
|
}).pipe(Effect.catchTag("SqlError", sqlFault(id)));
|
|
3567
3607
|
/** Delete cached rows and their applied offset, even if the State stream has been removed. */
|
|
3568
3608
|
const clear = Effect.fn("StateTable.clear")(function* (table) {
|
|
3569
|
-
|
|
3609
|
+
const owner = yield* StorageOwner;
|
|
3610
|
+
yield* inOwnerTransaction(owner)(clearIndex(table.inputs.state.id));
|
|
3570
3611
|
});
|
|
3571
3612
|
/** Discard the index and replay the State stream atomically, retaining the binding checkpoint. */
|
|
3572
3613
|
const rebuild = Effect.fn("StateTable.rebuild")(function* (table) {
|
|
3573
|
-
|
|
3614
|
+
const owner = yield* StorageOwner;
|
|
3615
|
+
yield* inOwnerTransaction(owner)(clearIndex(table.inputs.state.id).pipe(Effect.andThen(table.sync())));
|
|
3574
3616
|
});
|
|
3575
3617
|
/** Append a reset to the State stream. The next table run applies it. */
|
|
3576
3618
|
const reset = Effect.fn("StateTable.reset")(function* (table) {
|
|
3577
3619
|
const address = table.inputs.state;
|
|
3578
3620
|
const { wire } = yield* address.stream;
|
|
3579
3621
|
const state = StreamAddress.state(address.id, { collections: {} });
|
|
3580
|
-
return yield* Streams.append(state, [
|
|
3622
|
+
return yield* Streams.append(state, [DurableState.reset()]).pipe(Effect.provideService(StreamsWriter, wire));
|
|
3581
3623
|
});
|
|
3582
|
-
const unitFault = (reason
|
|
3624
|
+
const unitFault = (reason) => new ProjectionFault({
|
|
3583
3625
|
phase: "process",
|
|
3584
|
-
reason
|
|
3585
|
-
message: text,
|
|
3586
|
-
cause
|
|
3626
|
+
reason
|
|
3587
3627
|
});
|
|
3588
3628
|
/** The unit's map key for one row. */
|
|
3589
3629
|
const rowId = (collection, key) => `${collection}\u0000${key}`;
|
|
@@ -3601,8 +3641,11 @@ const unit = Effect.fn("StateTable.unit")(function* (table) {
|
|
|
3601
3641
|
const { wire } = yield* address.stream;
|
|
3602
3642
|
const managed = yield* TransactionGenerationOutputs;
|
|
3603
3643
|
const generationBound = managed !== void 0 && Array.some([...managed.values()], (output) => output.address.id === id);
|
|
3604
|
-
if (!generationBound) yield* wire.create(id, { contentType: address.contentType }).pipe(Effect.mapError((cause) => unitFault(
|
|
3605
|
-
yield* table.sync().pipe(Effect.mapError((cause) => generationBound && cause
|
|
3644
|
+
if (!generationBound) yield* wire.create(id, { contentType: address.contentType }).pipe(Effect.mapError((cause) => unitFault(outputReason(`Cannot write output ${id}`, cause))));
|
|
3645
|
+
yield* table.sync().pipe(Effect.mapError((cause) => generationBound && isInputLoss(cause) ? unitFault(new OutputRejected({
|
|
3646
|
+
message: `Cannot write output ${id}`,
|
|
3647
|
+
cause
|
|
3648
|
+
})) : cause));
|
|
3606
3649
|
const known = /* @__PURE__ */ new Map();
|
|
3607
3650
|
const entries = [];
|
|
3608
3651
|
const collectionOf = (collection) => {
|
|
@@ -3610,7 +3653,7 @@ const unit = Effect.fn("StateTable.unit")(function* (table) {
|
|
|
3610
3653
|
if (entry === void 0) throw new RangeError(`Unknown State collection ${collection}`);
|
|
3611
3654
|
return entry;
|
|
3612
3655
|
};
|
|
3613
|
-
const read = (collection, keys) => storedValues(store, id, collection, keys).pipe(Effect.mapError(unitFault("
|
|
3656
|
+
const read = (collection, keys) => storedValues(store, id, collection, keys).pipe(Effect.mapError((cause) => unitFault(storageFault("stateTable.values")(cause))), Effect.map((found) => {
|
|
3614
3657
|
for (const key of keys) known.set(rowId(collection, key), { json: found.get(key) });
|
|
3615
3658
|
}));
|
|
3616
3659
|
const current = (collection, key) => Effect.gen(function* () {
|
|
@@ -3628,7 +3671,10 @@ const unit = Effect.fn("StateTable.unit")(function* (table) {
|
|
|
3628
3671
|
const schema = collectionOf(collection).schema;
|
|
3629
3672
|
const found = yield* current(collection, key);
|
|
3630
3673
|
if (found.json === void 0) return void 0;
|
|
3631
|
-
if (!("value" in found)) found.value = yield* decodeRow(schema, found.json).pipe(Effect.mapError(
|
|
3674
|
+
if (!("value" in found)) found.value = yield* decodeRow(schema, found.json).pipe(Effect.mapError((cause) => unitFault(new InvalidRecord({
|
|
3675
|
+
message: `Row ${key} of ${id} does not decode`,
|
|
3676
|
+
cause
|
|
3677
|
+
}))));
|
|
3632
3678
|
return found.value;
|
|
3633
3679
|
}),
|
|
3634
3680
|
upsert: (collection, row, options = {}) => Effect.gen(function* () {
|
|
@@ -3637,7 +3683,10 @@ const unit = Effect.fn("StateTable.unit")(function* (table) {
|
|
|
3637
3683
|
const field = entry.key;
|
|
3638
3684
|
const key = Predicate.hasProperty(row, field) ? String(row[field]) : "undefined";
|
|
3639
3685
|
const before = yield* current(collection, key);
|
|
3640
|
-
const after = yield* encodeRow(schema, row).pipe(Effect.mapError(
|
|
3686
|
+
const after = yield* encodeRow(schema, row).pipe(Effect.mapError((cause) => unitFault(new EncodeFault({
|
|
3687
|
+
message: `Cannot encode row ${key} of ${id}`,
|
|
3688
|
+
cause
|
|
3689
|
+
}))));
|
|
3641
3690
|
if (after === before.json) return false;
|
|
3642
3691
|
known.set(rowId(collection, key), {
|
|
3643
3692
|
json: after,
|
|
@@ -3666,13 +3715,11 @@ var fold_by_key_exports = /* @__PURE__ */ __exportAll({
|
|
|
3666
3715
|
/** Return this from a fold to delete its row. The next record receives undefined. */
|
|
3667
3716
|
const remove = Symbol("@streamsy/projection/FoldByKey.remove");
|
|
3668
3717
|
const isEffect = (step) => Effect.isEffect(step);
|
|
3669
|
-
const
|
|
3718
|
+
const processFault = (reason) => new ProjectionFault({
|
|
3670
3719
|
phase: "process",
|
|
3671
|
-
reason
|
|
3672
|
-
message,
|
|
3673
|
-
cause
|
|
3720
|
+
reason
|
|
3674
3721
|
});
|
|
3675
|
-
const writeFault = (id) => (cause) =>
|
|
3722
|
+
const writeFault = (id) => (cause) => processFault(outputReason(`Cannot write output ${id}`, cause));
|
|
3676
3723
|
const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function* () {
|
|
3677
3724
|
const output = outputs[spec.output];
|
|
3678
3725
|
const collection = output.collections[spec.collection];
|
|
@@ -3681,7 +3728,10 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
|
|
|
3681
3728
|
const { wire } = yield* output.stream;
|
|
3682
3729
|
const generationBound = (yield* TransactionGenerationOutputs)?.get(spec.output)?.address.id === output.id;
|
|
3683
3730
|
if (!generationBound) yield* wire.create(output.id, { contentType: output.contentType }).pipe(Effect.mapError(writeFault(output.id)));
|
|
3684
|
-
yield* table
|
|
3731
|
+
yield* bindDeclaration(table, params.value).sync().pipe(Effect.mapError((cause) => generationBound && isInputLoss(cause) ? processFault(new OutputRejected({
|
|
3732
|
+
message: `Cannot write output ${output.id}`,
|
|
3733
|
+
cause
|
|
3734
|
+
})) : cause));
|
|
3685
3735
|
const groups = /* @__PURE__ */ new Map();
|
|
3686
3736
|
for (const { item } of items(batch)) for (const record of spec.records(item, unit)) {
|
|
3687
3737
|
const key = spec.key(record, unit);
|
|
@@ -3691,12 +3741,15 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
|
|
|
3691
3741
|
else group.push(record);
|
|
3692
3742
|
}
|
|
3693
3743
|
const store = yield* currentStore;
|
|
3694
|
-
const stored = yield* storedValues(store, output.id, spec.collection, [...groups.keys()]).pipe(Effect.mapError(
|
|
3744
|
+
const stored = yield* storedValues(store, output.id, spec.collection, [...groups.keys()]).pipe(Effect.mapError((cause) => processFault(storageFault("stateTable.values")(cause))));
|
|
3695
3745
|
const schema = collection.schema;
|
|
3696
3746
|
const changes = [];
|
|
3697
3747
|
for (const [key, records] of groups) {
|
|
3698
3748
|
const before = stored.get(key);
|
|
3699
|
-
let value = before === void 0 ? void 0 : yield* decodeRow(schema, before).pipe(Effect.mapError(
|
|
3749
|
+
let value = before === void 0 ? void 0 : yield* decodeRow(schema, before).pipe(Effect.mapError((cause) => processFault(new InvalidRecord({
|
|
3750
|
+
message: `Row ${key} of ${output.id} does not decode`,
|
|
3751
|
+
cause
|
|
3752
|
+
}))));
|
|
3700
3753
|
for (const record of records) {
|
|
3701
3754
|
const step = spec.fold(value, record, unit);
|
|
3702
3755
|
const next = isEffect(step) ? yield* step : step;
|
|
@@ -3710,12 +3763,11 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
|
|
|
3710
3763
|
const actual = Predicate.hasProperty(value, field) ? String(value[field]) : "undefined";
|
|
3711
3764
|
if (actual !== key) return yield* new FoldByKeyError({ message: `FoldByKey key "${key}" differs from folded row key "${actual}"` });
|
|
3712
3765
|
const rejected = store.unstorable(spec.collection, key);
|
|
3713
|
-
if (Option.isSome(rejected)) return yield* new
|
|
3714
|
-
|
|
3715
|
-
|
|
3716
|
-
|
|
3717
|
-
});
|
|
3718
|
-
const after = yield* encodeRow(schema, value).pipe(Effect.mapError(fault("invalid-output", `Cannot encode row ${key} of ${output.id}`)));
|
|
3766
|
+
if (Option.isSome(rejected)) return yield* processFault(new OutputRejected({ message: `Cannot write a row of ${output.id}. ${rejected.value}` }));
|
|
3767
|
+
const after = yield* encodeRow(schema, value).pipe(Effect.mapError((cause) => processFault(new EncodeFault({
|
|
3768
|
+
message: `Cannot encode row ${key} of ${output.id}`,
|
|
3769
|
+
cause
|
|
3770
|
+
}))));
|
|
3719
3771
|
if (after !== before) changes.push(upsertJson(spec.collection, key, after));
|
|
3720
3772
|
}
|
|
3721
3773
|
if (Array.isReadonlyArrayNonEmpty(changes)) yield* wire.append(output.id, {
|
|
@@ -3752,12 +3804,12 @@ function process(table, spec) {
|
|
|
3752
3804
|
const attach = (projection, options = {}) => {
|
|
3753
3805
|
const runner = runnerOf(projection, options, true, "wakeup");
|
|
3754
3806
|
return Effect.gen(function* () {
|
|
3807
|
+
yield* requireTriggers(options.triggers);
|
|
3755
3808
|
const { next, drain, deferred, status, schedule, rescan, retry, failed } = yield* runner;
|
|
3756
3809
|
let host;
|
|
3757
3810
|
let running = false;
|
|
3758
3811
|
let lastPassAt = Option.none();
|
|
3759
|
-
const
|
|
3760
|
-
const changed = Option.isNone(registry) ? Effect.void : yield* registerRunner(registry.value, {
|
|
3812
|
+
const changed = yield* registerRunner(yield* StorageOwner, {
|
|
3761
3813
|
id: projection.id,
|
|
3762
3814
|
generation: projection.generation,
|
|
3763
3815
|
status: Effect.gen(function* () {
|
|
@@ -3806,4 +3858,4 @@ const attach = (projection, options = {}) => {
|
|
|
3806
3858
|
});
|
|
3807
3859
|
};
|
|
3808
3860
|
const ProjectionWakeup = { attach };
|
|
3809
|
-
export { CheckpointRecord, CheckpointStore, commit_exports as Commit, fold_by_key_exports as FoldByKey, FoldByKeyError, HandlerFailed, InvalidBinding, NonRetryable, NotAttached, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, RunnerEvent, state_table_exports as StateTable,
|
|
3861
|
+
export { CheckpointRecord, CheckpointStore, commit_exports as Commit, fold_by_key_exports as FoldByKey, FoldByKeyError, GenerationMismatch, HandlerFailed, HistoryUnavailable, IdentityMismatch, InputNotFound, InvalidBinding, InvalidRecord, InvalidSource, InvalidWakeTime, NonRetryable, NotAttached, OutputRejected, projection_exports as Projection, ProjectionFault, ProjectionFaultReason, ProjectionRetry, ProjectionWakeup, RangeUnreproducible, RetiredGeneration, RunnerEvent, state_table_exports as StateTable, SupersededGeneration, TokenConflict, UnsupportedComposition, isFrontierCollection, unitFrontiers, validateFrontier };
|