@streamsy/projection 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -0
- package/dist/{checkpoint-store-DCfrS4Fd.d.ts → checkpoint-store-B1199nDD.d.ts} +34 -3
- package/dist/{checkpoint-store--bWf1qeP.js → checkpoint-store-ViVETLzZ.js} +169 -31
- package/dist/checkpoint.d.ts +2 -2
- package/dist/checkpoint.js +1 -1
- package/dist/index.d.ts +233 -46
- package/dist/index.js +718 -142
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
-
import { a as rangesOf, c as
|
|
2
|
+
import { _ as ProjectionFault, a as rangesOf, c as unsupportedBindingList, d as terminalOf, f as unitOf, g as NotAttached, h as NonRetryable, l as canonicalParams, m as InvalidBinding, n as CheckpointStore, o as recordKey, p as withParams, r as advance, s as restore, t as CheckpointRecord, u as encodeKey } from "./checkpoint-store-ViVETLzZ.js";
|
|
3
3
|
import { Array, Cause, Clock, Context, Data, DateTime, Deferred, Duration, Effect, Exit, Function, Layer, Option, Pipeable, Predicate, PubSub, Pull, Queue, Record, Ref, Result, Schedule, Schema, Semaphore, Stream } from "effect";
|
|
4
4
|
import { CommitBoundary, DurableState, Offset, Storage, StorageFault, StreamAddress, StreamId, Streamsy, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
|
|
5
5
|
import { CommitHooks, CurrentOwner, MAX_PRODUCER_ID_LENGTH, OwnerRecords, ProjectionMarks, compileSegments, fitKey, isForeignOwner, memoryProjectionMarks, offsetsOf, ownerOf } from "@streamsy/core/internal";
|
|
@@ -231,71 +231,13 @@ const items = (batch) => {
|
|
|
231
231
|
}
|
|
232
232
|
return out;
|
|
233
233
|
};
|
|
234
|
-
// src/outputs.ts
|
|
235
|
-
/** Resolve routes just like inputs, retaining the route codec and collection names. */
|
|
236
|
-
const resolveOutputs = (outputs, params, inputs) => {
|
|
237
|
-
const streams = addressesOf(outputs, params);
|
|
238
|
-
const ids = Array.map(Record.values(streams), (address) => address.id);
|
|
239
|
-
if (new Set(ids).size !== ids.length) throw new RangeError("Two outputs may not name the same stream");
|
|
240
|
-
const inputIds = new Set(Array.map(Record.values(inputs), (address) => address.id));
|
|
241
|
-
if (Array.some(ids, (id) => inputIds.has(id))) throw new RangeError("An output may not name an input stream");
|
|
242
|
-
if (Array.some(Record.values(streams), (address) => !Predicate.isTagged(address, "Json"))) throw new RangeError("Projection outputs require JSON or state routes");
|
|
243
|
-
return streams;
|
|
244
|
-
};
|
|
245
|
-
const collect = (outputs, buffers, emitted) => Effect.gen(function* () {
|
|
246
|
-
for (const [name, entries] of Record.toEntries(emitted)) {
|
|
247
|
-
const output = outputs[name];
|
|
248
|
-
if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* new ProjectionFault({
|
|
249
|
-
phase: "process",
|
|
250
|
-
reason: "invalid-output",
|
|
251
|
-
message: `Invalid output array ${name}`
|
|
252
|
-
});
|
|
253
|
-
const values = yield* Effect.try({
|
|
254
|
-
try: () => "collections" in output ? DurableState.changes(output, {}, entries) : entries,
|
|
255
|
-
catch: (cause) => new ProjectionFault({
|
|
256
|
-
phase: "process",
|
|
257
|
-
reason: "invalid-output",
|
|
258
|
-
message: `Invalid row change for ${name}`,
|
|
259
|
-
cause
|
|
260
|
-
})
|
|
261
|
-
});
|
|
262
|
-
(buffers[name] ??= []).push(...values);
|
|
263
|
-
}
|
|
264
|
-
return yield* Effect.void;
|
|
265
|
-
});
|
|
266
|
-
const pin$1 = (reason, message, cause) => new ProjectionFault({
|
|
267
|
-
phase: "pin",
|
|
268
|
-
reason,
|
|
269
|
-
message,
|
|
270
|
-
cause
|
|
271
|
-
});
|
|
272
|
-
/** Append one unit under its pinned tuple; appended and duplicate are one outcome. */
|
|
273
|
-
const appendPinned = Effect.fn("Projection.appendPinned")(function* (output, wire, items, position) {
|
|
274
|
-
return yield* Streams.append(output, items, { producer: position }).pipe(Effect.provideService(StreamsWriter, wire), Effect.catchTags({
|
|
275
|
-
EncodeFault: () => new ProjectionFault({
|
|
276
|
-
phase: "process",
|
|
277
|
-
reason: "invalid-output",
|
|
278
|
-
message: `Cannot encode output for ${output.id}`
|
|
279
|
-
}),
|
|
280
|
-
StaleEpoch: (error) => pin$1("stale-epoch", `Epoch ${position.producerEpoch} of ${output.id} is behind ${error.currentEpoch}`),
|
|
281
|
-
ProducerGap: (error) => pin$1("invalid-record", `Sequence ${error.receivedSeq} of ${output.id} does not follow ${error.expectedSeq}`),
|
|
282
|
-
NotSupported: (error) => pin$1("unsupported-composition", `${output.id} does not support ${error.feature}`),
|
|
283
|
-
StorageFault: (cause) => pin$1("storage-failure", `Cannot append to ${output.id}`, cause),
|
|
284
|
-
TransportFault: (cause) => pin$1("storage-failure", `Cannot append to ${output.id}`, cause),
|
|
285
|
-
StreamNotFound: () => pin$1("invalid-output", `Output ${output.id} does not exist`),
|
|
286
|
-
StreamGone: () => pin$1("invalid-output", `Output ${output.id} is gone`),
|
|
287
|
-
StreamClosed: () => pin$1("invalid-output", `Output ${output.id} is closed`),
|
|
288
|
-
AppendConflict: () => pin$1("invalid-output", `Output ${output.id} refused the append`),
|
|
289
|
-
StreamBusy: () => pin$1("output-busy", `Output ${output.id} is busy`)
|
|
290
|
-
}));
|
|
291
|
-
});
|
|
292
234
|
// src/commit/range.ts
|
|
293
235
|
const RangeKey = Symbol.for("@streamsy/projection/internal/Range");
|
|
294
236
|
const extend = (commit) => Object.defineProperty(commit, RangeKey, {
|
|
295
237
|
value: "extend",
|
|
296
238
|
configurable: true
|
|
297
239
|
});
|
|
298
|
-
const pin = (commit) => Object.defineProperty(commit, RangeKey, {
|
|
240
|
+
const pin$1 = (commit) => Object.defineProperty(commit, RangeKey, {
|
|
299
241
|
value: "pin",
|
|
300
242
|
configurable: true
|
|
301
243
|
});
|
|
@@ -303,7 +245,7 @@ const isPinned = (commit) => RangeKey in commit && commit[RangeKey] === "pin";
|
|
|
303
245
|
const inherit = (source, target) => {
|
|
304
246
|
if (supportsPrepare(source)) withPrepare(target);
|
|
305
247
|
if (supportsAccepted(source)) withAccepted(target);
|
|
306
|
-
return isPinned(source) ? pin(target) : extend(target);
|
|
248
|
+
return isPinned(source) ? pin$1(target) : extend(target);
|
|
307
249
|
};
|
|
308
250
|
const PrepareKey = Symbol.for("@streamsy/projection/internal/Prepare");
|
|
309
251
|
const withPrepare = (commit) => Object.defineProperty(commit, PrepareKey, { value: true });
|
|
@@ -312,7 +254,7 @@ const AcceptedKey = Symbol.for("@streamsy/projection/internal/Accepted");
|
|
|
312
254
|
const withAccepted = (commit) => Object.defineProperty(commit, AcceptedKey, { value: true });
|
|
313
255
|
const supportsAccepted = (commit) => AcceptedKey in commit && commit[AcceptedKey] === true;
|
|
314
256
|
// src/commit/model.ts
|
|
315
|
-
const TypeId = "~@streamsy/projection/Commit";
|
|
257
|
+
const TypeId$1 = "~@streamsy/projection/Commit";
|
|
316
258
|
/** Opaque to Commit authors; the kernel restores the original typed handler error. */
|
|
317
259
|
var HandlerFailed = class extends Schema.TaggedError()("HandlerFailed", { error: Schema.Unknown }) {};
|
|
318
260
|
const { Folded, Emitted, Accumulated } = Data.taggedEnum();
|
|
@@ -324,7 +266,7 @@ const { Folded, Emitted, Accumulated } = Data.taggedEnum();
|
|
|
324
266
|
* declare at-least-once. The guarantee must describe the actual write. */
|
|
325
267
|
const make$1 = (options) => extend({
|
|
326
268
|
...options,
|
|
327
|
-
[TypeId]: {
|
|
269
|
+
[TypeId$1]: {
|
|
328
270
|
result: () => {},
|
|
329
271
|
provides: () => {},
|
|
330
272
|
requires: () => {
|
|
@@ -346,6 +288,11 @@ const detailsOf = (pending) => {
|
|
|
346
288
|
};
|
|
347
289
|
const load = (key) => CheckpointStore.use((store) => store.load(key));
|
|
348
290
|
const remove$1 = (key) => CheckpointStore.use((store) => store.remove(key));
|
|
291
|
+
const retire$1 = ({ key, cleanup }) => CheckpointStore.use((store) => store.retire === void 0 ? Effect.fail(new ProjectionFault({
|
|
292
|
+
phase: "checkpoint",
|
|
293
|
+
reason: "unsupported-composition",
|
|
294
|
+
message: `The checkpoint store cannot retire ${key.id}`
|
|
295
|
+
})) : store.retire(key).pipe(Effect.tap(() => cleanup)));
|
|
349
296
|
/** Merge the handler's state and timer into the same checkpoint write. */
|
|
350
297
|
const withState = (next, result) => {
|
|
351
298
|
const stored = result !== void 0 && "encoded" in result ? {
|
|
@@ -368,6 +315,7 @@ const checkpoint = make$1({
|
|
|
368
315
|
guarantee: "exactly-once",
|
|
369
316
|
load,
|
|
370
317
|
remove: remove$1,
|
|
318
|
+
retire: retire$1,
|
|
371
319
|
apply: (pending) => Effect.flatMap(pending.run, (result) => settle(pending, result))
|
|
372
320
|
});
|
|
373
321
|
// src/transaction.ts
|
|
@@ -392,30 +340,170 @@ var Transaction = class extends Context.Service()("@streamsy/projection/Transact
|
|
|
392
340
|
};
|
|
393
341
|
}));
|
|
394
342
|
};
|
|
343
|
+
// src/per-generation.ts
|
|
344
|
+
const TypeId = Symbol.for("@streamsy/projection/PerGeneration");
|
|
345
|
+
function perGeneration(route, param, options) {
|
|
346
|
+
const shared = options?.shared ?? false;
|
|
347
|
+
const routeBy = options?.routeBy;
|
|
348
|
+
return { [TypeId]: routeBy === void 0 ? {
|
|
349
|
+
route,
|
|
350
|
+
param,
|
|
351
|
+
shared
|
|
352
|
+
} : {
|
|
353
|
+
route,
|
|
354
|
+
param,
|
|
355
|
+
shared,
|
|
356
|
+
routeBy: Object.freeze([...routeBy])
|
|
357
|
+
} };
|
|
358
|
+
}
|
|
359
|
+
const isPerGeneration = (value) => TypeId in value;
|
|
360
|
+
const generationBinding = (binding) => binding[TypeId];
|
|
361
|
+
const validateGenerationParam = (output, params) => {
|
|
362
|
+
if (!isPerGeneration(output)) return;
|
|
363
|
+
const { route, param, routeBy, shared } = generationBinding(output);
|
|
364
|
+
if (Record.has(params, param)) throw new RangeError(`Generation-bound parameter ${param} must not be a projection parameter`);
|
|
365
|
+
if (routeBy === void 0) return;
|
|
366
|
+
if (shared) throw new RangeError("Routed outputs cannot be shared");
|
|
367
|
+
if (routeBy.length === 0 || new Set(routeBy).size !== routeBy.length) throw new RangeError("routeBy requires one or more distinct route parameters");
|
|
368
|
+
const names = Array.filterMap(route.template.split("/"), (part) => part.startsWith(":") ? Result.succeed(part.slice(1)) : Result.fail(void 0));
|
|
369
|
+
for (const name of routeBy) {
|
|
370
|
+
if (!names.includes(name)) throw new RangeError(`Routed parameter ${name} must be a route parameter`);
|
|
371
|
+
if (name === param || Record.has(params, name)) throw new RangeError(`Routed parameter ${name} must not be a generation or projection parameter`);
|
|
372
|
+
}
|
|
373
|
+
for (const name of names) if (name !== param && !routeBy.includes(name) && !Record.has(params, name)) throw new RangeError(`Missing projection parameter ${name} for routed output`);
|
|
374
|
+
};
|
|
375
|
+
/** Private metadata on the bound value. */
|
|
376
|
+
const GenerationOutputs = Symbol.for("@streamsy/projection/internal/GenerationOutputs");
|
|
377
|
+
/** Outputs whose creation is managed by the current transaction. */
|
|
378
|
+
const TransactionGenerationOutputs = Context.Reference("@streamsy/projection/internal/TransactionGenerationOutputs", { defaultValue: () => void 0 });
|
|
379
|
+
// src/routed-outputs.ts
|
|
380
|
+
const RoutedOutputs = Symbol.for("@streamsy/projection/internal/RoutedOutputs");
|
|
381
|
+
const processFault = (reason, message, cause) => new ProjectionFault({
|
|
382
|
+
phase: "process",
|
|
383
|
+
reason,
|
|
384
|
+
message,
|
|
385
|
+
cause
|
|
386
|
+
});
|
|
387
|
+
const requireRouteRecords = (store, phase) => store?.routes === void 0 ? Effect.fail(new ProjectionFault({
|
|
388
|
+
phase,
|
|
389
|
+
reason: "unsupported-composition",
|
|
390
|
+
message: "This CheckpointStore does not support routed outputs"
|
|
391
|
+
})) : Effect.succeed(store.routes);
|
|
392
|
+
const currentRouteRecords = Effect.serviceOption(CheckpointStore).pipe(Effect.flatMap((store) => requireRouteRecords(Option.getOrUndefined(store), "checkpoint")));
|
|
393
|
+
const routedUnit = (key, store) => ({
|
|
394
|
+
key: recordKey(key),
|
|
395
|
+
store,
|
|
396
|
+
opened: /* @__PURE__ */ new Map(),
|
|
397
|
+
lock: Semaphore.makeUnsafe(1)
|
|
398
|
+
});
|
|
399
|
+
const TransactionRoutedOutputs = Context.Reference("@streamsy/projection/internal/TransactionRoutedOutputs", { defaultValue: () => void 0 });
|
|
400
|
+
const routedDefinition = (route) => ({
|
|
401
|
+
matches: route.match,
|
|
402
|
+
restore: (id) => {
|
|
403
|
+
const parsed = route.parse(id);
|
|
404
|
+
if (Option.isNone(parsed)) return void 0;
|
|
405
|
+
const address = route.at(parsed.value);
|
|
406
|
+
return address.id === id ? address : void 0;
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
const routedHandle = (name, route, names, params, key, occupied, routed) => ({ open: (values) => Effect.gen(function* () {
|
|
410
|
+
const unit = yield* TransactionRoutedOutputs;
|
|
411
|
+
if (unit === void 0 || unit.key !== recordKey(key)) return yield* processFault("unsupported-composition", `Routed output ${name} requires its binding's process transaction`);
|
|
412
|
+
const address = yield* Effect.try({
|
|
413
|
+
try: () => {
|
|
414
|
+
if (Record.keys(values).length !== names.length || !Array.every(names, (param) => Record.has(values, param))) throw new RangeError(`Expected route parameters ${Array.join(names, ", ")}`);
|
|
415
|
+
return route.at({
|
|
416
|
+
...params,
|
|
417
|
+
...values
|
|
418
|
+
});
|
|
419
|
+
},
|
|
420
|
+
catch: (cause) => processFault("invalid-output", `Cannot resolve routed output ${name}: ${cause instanceof RangeError ? cause.message : String(cause)}`, cause)
|
|
421
|
+
});
|
|
422
|
+
if (occupied.has(address.id)) return yield* processFault("invalid-output", `Routed output ${name} overlaps an input or output at ${address.id}`);
|
|
423
|
+
if (!Predicate.isTagged(address, "Json")) return yield* processFault("invalid-output", "Projection outputs require JSON or state routes");
|
|
424
|
+
const service = yield* address.stream;
|
|
425
|
+
const owner = yield* CurrentOwner;
|
|
426
|
+
if (service.owner !== owner) return yield* processFault("unsupported-composition", `Output ${address.id} does not share the transaction owner`);
|
|
427
|
+
return yield* unit.lock.withPermits(1)(Effect.gen(function* () {
|
|
428
|
+
const opened = unit.opened.get(address.id);
|
|
429
|
+
if (opened === name) return address;
|
|
430
|
+
if (opened !== void 0) return yield* processFault("invalid-output", `Routed outputs ${opened} and ${name} both name ${address.id}`);
|
|
431
|
+
const records = yield* requireRouteRecords(unit.store, "process");
|
|
432
|
+
if (!(yield* records.has(key, name, address.id))) {
|
|
433
|
+
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}`);
|
|
434
|
+
const created = yield* createOutput(address, service.wire);
|
|
435
|
+
if (created.closed || created.nextOffset !== ZERO_OFFSET) return yield* processFault("invalid-output", `Generation-bound output ${address.id} must start empty and open`);
|
|
436
|
+
yield* records.add(key, name, address.id);
|
|
437
|
+
}
|
|
438
|
+
unit.opened.set(address.id, name);
|
|
439
|
+
return address;
|
|
440
|
+
}));
|
|
441
|
+
}) });
|
|
395
442
|
// src/commit/transaction.ts
|
|
443
|
+
const removeWithRoutes = (key) => Effect.gen(function* () {
|
|
444
|
+
const store = yield* CheckpointStore;
|
|
445
|
+
const tx = yield* Transaction;
|
|
446
|
+
if (ownerOf(store.load) !== tx.owner) return yield* new ProjectionFault({
|
|
447
|
+
phase: "checkpoint",
|
|
448
|
+
reason: "unsupported-composition",
|
|
449
|
+
message: `The checkpoint store for ${key.id} does not share the transaction owner`
|
|
450
|
+
});
|
|
451
|
+
const records = yield* requireRouteRecords(store, "checkpoint");
|
|
452
|
+
if (yield* store.load(key).pipe(Effect.map(({ record }) => Option.isSome(record)), Effect.catchIf((fault) => fault.reason === "retired-generation", () => Effect.succeed(false)), Effect.catchIf((fault) => fault.reason === "invalid-record", () => Effect.succeed(true)))) {
|
|
453
|
+
yield* records.clear(key);
|
|
454
|
+
yield* store.remove(key);
|
|
455
|
+
}
|
|
456
|
+
return yield* Effect.void;
|
|
457
|
+
});
|
|
458
|
+
const retireInTransaction = (request) => Effect.gen(function* () {
|
|
459
|
+
const tx = yield* Transaction;
|
|
460
|
+
const store = yield* CheckpointStore;
|
|
461
|
+
if (ownerOf(store.load) !== tx.owner) return yield* new ProjectionFault({
|
|
462
|
+
phase: "checkpoint",
|
|
463
|
+
reason: "unsupported-composition",
|
|
464
|
+
message: `The checkpoint store for ${request.key.id} does not share the transaction owner`
|
|
465
|
+
});
|
|
466
|
+
return yield* tx.withTransaction(retire$1(request).pipe(Effect.provideService(CurrentOwner, tx.owner)));
|
|
467
|
+
});
|
|
396
468
|
const transaction = withPrepare(make$1({
|
|
397
469
|
name: "transaction",
|
|
398
470
|
guarantee: "exactly-once",
|
|
399
471
|
load,
|
|
400
|
-
remove: remove$1,
|
|
472
|
+
remove: (key) => RoutedOutputs in key ? Transaction.use((tx) => tx.withTransaction(removeWithRoutes(key))) : remove$1(key),
|
|
473
|
+
retire: retireInTransaction,
|
|
401
474
|
apply: (pending) => Effect.gen(function* () {
|
|
402
475
|
const tx = yield* Transaction;
|
|
403
476
|
const store = yield* CheckpointStore;
|
|
404
|
-
const outputs = detailsOf(pending)
|
|
477
|
+
const { outputs, prepare } = detailsOf(pending);
|
|
478
|
+
const hasRoutes = RoutedOutputs in pending.key;
|
|
479
|
+
if (hasRoutes && ownerOf(store.load) !== tx.owner) return yield* new ProjectionFault({
|
|
480
|
+
phase: "checkpoint",
|
|
481
|
+
reason: "unsupported-composition",
|
|
482
|
+
message: `The checkpoint store for ${pending.key.id} does not share the transaction owner`
|
|
483
|
+
});
|
|
405
484
|
for (const { address, service } of Record.values(outputs)) if (service.owner !== tx.owner) return yield* new ProjectionFault({
|
|
406
485
|
phase: "load",
|
|
407
486
|
reason: "unsupported-composition",
|
|
408
487
|
message: `Output ${address.id} does not share the transaction owner`
|
|
409
488
|
});
|
|
410
|
-
const prepare = detailsOf(pending).prepare;
|
|
411
489
|
if (prepare !== void 0) yield* prepare;
|
|
412
490
|
yield* tx.withTransaction(Effect.gen(function* () {
|
|
413
|
-
|
|
491
|
+
const again = yield* store.load(pending.key);
|
|
492
|
+
if (again.token !== pending.loaded.token) return yield* new ProjectionFault({
|
|
414
493
|
phase: "checkpoint",
|
|
415
494
|
reason: "token-conflict",
|
|
416
495
|
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.`
|
|
417
496
|
});
|
|
418
|
-
|
|
497
|
+
if (Option.isNone(again.record)) for (const { address, service, generation } of Record.values(outputs)) {
|
|
498
|
+
if (generation === void 0) continue;
|
|
499
|
+
const created = yield* createOutput(address, service.wire);
|
|
500
|
+
if (!generation.shared && (created.closed || created.nextOffset !== ZERO_OFFSET)) return yield* new ProjectionFault({
|
|
501
|
+
phase: "process",
|
|
502
|
+
reason: "invalid-output",
|
|
503
|
+
message: `Generation-bound output ${address.id} must start empty and open`
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
const result = yield* pending.run.pipe(Effect.provideService(SqlClient.SqlClient, tx.sql), Effect.provideService(CurrentOwner, tx.owner), Effect.provideService(TransactionGenerationOutputs, pending.generationOutputs), Effect.provideService(TransactionRoutedOutputs, hasRoutes ? routedUnit(pending.key, store) : void 0), Effect.catchDefect((defect) => isForeignOwner(defect) ? Effect.fail(new ProjectionFault({
|
|
419
507
|
phase: "process",
|
|
420
508
|
reason: "unsupported-composition",
|
|
421
509
|
message: defect.message
|
|
@@ -441,6 +529,15 @@ const transaction = withPrepare(make$1({
|
|
|
441
529
|
return yield* Effect.void;
|
|
442
530
|
})
|
|
443
531
|
})).pipe(withAccepted);
|
|
532
|
+
/** Clean up binding state in the owner transaction on both forget and retire. */
|
|
533
|
+
const transactionWithCleanup = (cleanup) => inherit(transaction, {
|
|
534
|
+
...transaction,
|
|
535
|
+
remove: (key) => Transaction.use((tx) => tx.withTransaction((RoutedOutputs in key ? removeWithRoutes(key) : remove$1(key)).pipe(Effect.andThen(() => cleanup(key, tx.sql))))),
|
|
536
|
+
retire: (request) => Transaction.use((tx) => retireInTransaction({
|
|
537
|
+
...request,
|
|
538
|
+
cleanup: request.cleanup.pipe(Effect.andThen(() => cleanup(request.key, tx.sql)))
|
|
539
|
+
}))
|
|
540
|
+
});
|
|
444
541
|
// src/commit/producer.ts
|
|
445
542
|
/**
|
|
446
543
|
* The pinned tuple identity: the params join the id so two parameterisations never share a sequence.
|
|
@@ -450,9 +547,9 @@ const transaction = withPrepare(make$1({
|
|
|
450
547
|
*/
|
|
451
548
|
const producerId = (id, version, params) => fitKey(`${id}/v${version}${Record.keys(params).length === 0 ? "" : `/${canonicalParams(params)}`}`, MAX_PRODUCER_ID_LENGTH, `${id}/v${version}/`);
|
|
452
549
|
/** The head of one output. A missing output on the checkpoint's owner is created here. */
|
|
453
|
-
const prepareOutput = (output, store) => {
|
|
550
|
+
const prepareOutput = (output, store, beforeCreate) => {
|
|
454
551
|
const { wire, owner: outputOwner } = output.service;
|
|
455
|
-
return wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== ownerOf(store.load) ? Effect.fail(cause) : Streams.create(output.address)
|
|
552
|
+
return wire.head(output.address.id).pipe(Effect.catchTag("StreamNotFound", (cause) => outputOwner !== ownerOf(store.load) ? 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({
|
|
456
553
|
phase: "pin",
|
|
457
554
|
reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
458
555
|
message: `Cannot prepare output ${output.address.id}`,
|
|
@@ -465,10 +562,11 @@ const asPin = (fault) => fault.phase === "checkpoint" && fault.reason === "token
|
|
|
465
562
|
reason: fault.reason,
|
|
466
563
|
message: fault.message
|
|
467
564
|
}) : fault;
|
|
468
|
-
const producer = pin(make$1({
|
|
565
|
+
const producer = pin$1(make$1({
|
|
469
566
|
name: "producer",
|
|
470
567
|
guarantee: "effectively-once",
|
|
471
568
|
remove: remove$1,
|
|
569
|
+
retire: retire$1,
|
|
472
570
|
load: (key) => Effect.gen(function* () {
|
|
473
571
|
const loaded = yield* load(key);
|
|
474
572
|
if (Option.isSome(loaded.record)) {
|
|
@@ -518,13 +616,27 @@ const producer = pin(make$1({
|
|
|
518
616
|
}
|
|
519
617
|
let token = before.token;
|
|
520
618
|
if (pending === void 0 && Record.keys(seqs).length > 0) {
|
|
619
|
+
const checkBeforeCreate = Effect.gen(function* () {
|
|
620
|
+
if ((yield* owner.load(projection)).token !== before.token) return yield* new ProjectionFault({
|
|
621
|
+
phase: "pin",
|
|
622
|
+
reason: "token-conflict",
|
|
623
|
+
message: `Record for ${projection.id} changed before creating an output`
|
|
624
|
+
});
|
|
625
|
+
return yield* Effect.void;
|
|
626
|
+
});
|
|
521
627
|
for (const [name, output] of Record.toEntries(streams)) {
|
|
522
628
|
if (seqs[name] === void 0) continue;
|
|
523
|
-
|
|
629
|
+
const head = yield* prepareOutput(output, owner, output.generation === void 0 ? Effect.void : checkBeforeCreate);
|
|
630
|
+
if (head.closed) return yield* new ProjectionFault({
|
|
524
631
|
phase: "pin",
|
|
525
632
|
reason: "invalid-output",
|
|
526
633
|
message: `Output ${output.address.id} is closed`
|
|
527
634
|
});
|
|
635
|
+
if (output.generation?.shared === false && positions[name] === void 0 && head.nextOffset !== ZERO_OFFSET) return yield* new ProjectionFault({
|
|
636
|
+
phase: "pin",
|
|
637
|
+
reason: "invalid-output",
|
|
638
|
+
message: `Generation-bound output ${output.address.id} must start empty and open`
|
|
639
|
+
});
|
|
528
640
|
positions[name] = positions[name] ?? {
|
|
529
641
|
epoch: projection.generation,
|
|
530
642
|
nextSeq: 0
|
|
@@ -571,11 +683,12 @@ const producer = pin(make$1({
|
|
|
571
683
|
})
|
|
572
684
|
})).pipe(withAccepted);
|
|
573
685
|
// src/commit/at-least-once.ts
|
|
574
|
-
const atLeastOnce = pin(make$1({
|
|
686
|
+
const atLeastOnce = pin$1(make$1({
|
|
575
687
|
name: "atLeastOnce",
|
|
576
688
|
guarantee: "at-least-once",
|
|
577
689
|
load,
|
|
578
690
|
remove: remove$1,
|
|
691
|
+
retire: retire$1,
|
|
579
692
|
apply: (pending) => Effect.gen(function* () {
|
|
580
693
|
const store = yield* CheckpointStore;
|
|
581
694
|
const before = beforeRecord(pending);
|
|
@@ -612,24 +725,32 @@ var commit_exports = /* @__PURE__ */ __exportAll({
|
|
|
612
725
|
Emitted: () => Emitted,
|
|
613
726
|
Folded: () => Folded,
|
|
614
727
|
HandlerFailed: () => HandlerFailed,
|
|
615
|
-
TypeId: () => TypeId,
|
|
728
|
+
TypeId: () => TypeId$1,
|
|
616
729
|
atLeastOnce: () => atLeastOnce,
|
|
617
730
|
checkpoint: () => checkpoint,
|
|
618
731
|
make: () => make$1,
|
|
619
732
|
producer: () => producer,
|
|
620
733
|
transaction: () => transaction,
|
|
734
|
+
transactionWithCleanup: () => transactionWithCleanup,
|
|
621
735
|
withCompensation: () => withCompensation
|
|
622
736
|
});
|
|
623
737
|
// src/accepted.ts
|
|
624
738
|
/** Private output name, stable across producer retries. */
|
|
625
739
|
const acceptedKey = "@streamsy/accepted";
|
|
626
|
-
const validateAccepted = (
|
|
627
|
-
if (
|
|
740
|
+
const validateAccepted = (output, params, inputTemplates, commit, outputNames = []) => {
|
|
741
|
+
if (output === void 0) return;
|
|
628
742
|
if (!supportsAccepted(commit)) throw new RangeError("accepted requires Commit.transaction or Commit.producer");
|
|
743
|
+
validateGenerationParam(output, params);
|
|
744
|
+
const { route: accepted, param, routeBy } = isPerGeneration(output) ? generationBinding(output) : {
|
|
745
|
+
route: output,
|
|
746
|
+
param: void 0,
|
|
747
|
+
routeBy: void 0
|
|
748
|
+
};
|
|
749
|
+
if (routeBy !== void 0) throw new RangeError("accepted does not support routed outputs");
|
|
629
750
|
if (accepted.collections !== Streamsy.wakeCollections) {
|
|
630
751
|
if (accepted.collections.stream?.schema !== Streamsy.WakeRow || accepted.collections.stream.key !== "stream") throw new RangeError("accepted requires a wake stream declaration");
|
|
631
752
|
}
|
|
632
|
-
for (const name of Record.keys(accepted.paramCodecs)) if (!Record.has(params, name)) throw new RangeError(`accepted parameter ${name} must be a projection parameter`);
|
|
753
|
+
for (const name of Record.keys(accepted.paramCodecs)) if (name !== param && !Record.has(params, name)) throw new RangeError(`accepted parameter ${name} must be a projection parameter`);
|
|
633
754
|
for (const template of inputTemplates) if (template === accepted.template) throw new RangeError("An accepted stream may not name an input stream");
|
|
634
755
|
if (Array.contains(outputNames, "@streamsy/accepted")) throw new RangeError(`Output name ${acceptedKey} is reserved for accepted`);
|
|
635
756
|
};
|
|
@@ -678,6 +799,122 @@ const acceptedResult = (result, output) => {
|
|
|
678
799
|
wakeAt: result.wakeAt
|
|
679
800
|
} : emitted;
|
|
680
801
|
};
|
|
802
|
+
// src/outputs.ts
|
|
803
|
+
const resolveOutputs = (outputs, acceptedOutput, params, key, inputs) => {
|
|
804
|
+
const generationOutputs = /* @__PURE__ */ new Map();
|
|
805
|
+
const resolve = (name, output) => {
|
|
806
|
+
if (isPerGeneration(output)) {
|
|
807
|
+
const { route, param, shared } = generationBinding(output);
|
|
808
|
+
generationOutputs.set(name, { shared });
|
|
809
|
+
return route.at({
|
|
810
|
+
...params,
|
|
811
|
+
[param]: key.generation
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
return isDeclaration(output) ? output.at(params) : output;
|
|
815
|
+
};
|
|
816
|
+
const routed = /* @__PURE__ */ new Map();
|
|
817
|
+
const streams = Record.fromEntries(Array.flatMap(Record.toEntries(outputs), ([name, output]) => {
|
|
818
|
+
if (isPerGeneration(output) && generationBinding(output).routeBy !== void 0) {
|
|
819
|
+
routed.set(name, routedDefinition(generationBinding(output).route));
|
|
820
|
+
return [];
|
|
821
|
+
}
|
|
822
|
+
return [[name, resolve(name, output)]];
|
|
823
|
+
}));
|
|
824
|
+
const accepted = acceptedOutput === void 0 ? void 0 : resolve(acceptedKey, acceptedOutput);
|
|
825
|
+
const addresses = accepted === void 0 ? Record.values(streams) : [...Record.values(streams), accepted];
|
|
826
|
+
const ids = Array.map(addresses, (address) => address.id);
|
|
827
|
+
if (new Set(ids).size !== ids.length) throw new RangeError("Two outputs may not name the same stream");
|
|
828
|
+
const inputIds = new Set(Array.map(Record.values(inputs), (address) => address.id));
|
|
829
|
+
if (Array.some(ids, (id) => inputIds.has(id))) throw new RangeError("An output may not name an input stream");
|
|
830
|
+
if (Array.some(addresses, (address) => !Predicate.isTagged(address, "Json"))) throw new RangeError("Projection outputs require JSON or state routes");
|
|
831
|
+
const occupied = /* @__PURE__ */ new Set([...inputIds, ...ids]);
|
|
832
|
+
const handles = Record.fromEntries(Array.flatMap(Record.toEntries(outputs), ([name, output]) => {
|
|
833
|
+
if (!isPerGeneration(output)) return [];
|
|
834
|
+
const { route, param, routeBy } = generationBinding(output);
|
|
835
|
+
return routeBy === void 0 ? [] : [[name, routedHandle(name, route, routeBy, {
|
|
836
|
+
...params,
|
|
837
|
+
[param]: key.generation
|
|
838
|
+
}, key, occupied, routed)]];
|
|
839
|
+
}));
|
|
840
|
+
return {
|
|
841
|
+
streams,
|
|
842
|
+
accepted,
|
|
843
|
+
generationOutputs,
|
|
844
|
+
routed,
|
|
845
|
+
handlerOutputs: routed.size === 0 ? streams : {
|
|
846
|
+
...streams,
|
|
847
|
+
...handles
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
};
|
|
851
|
+
const createOutput = (address, wire) => Streams.create(address).pipe(Effect.provideService(StreamsWriter, wire), Effect.mapError((cause) => new ProjectionFault({
|
|
852
|
+
phase: "process",
|
|
853
|
+
reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
854
|
+
message: `Cannot create output ${address.id}`,
|
|
855
|
+
cause
|
|
856
|
+
})));
|
|
857
|
+
const boundOutputs = (bound) => bound.accepted === void 0 ? bound.streams ?? {} : {
|
|
858
|
+
...bound.streams,
|
|
859
|
+
[acceptedKey]: bound.accepted
|
|
860
|
+
};
|
|
861
|
+
/** Create the generation-bound outputs of one binding, using each output's owner. */
|
|
862
|
+
const createOutputs = (bound) => Effect.gen(function* () {
|
|
863
|
+
const bindings = bound[GenerationOutputs];
|
|
864
|
+
if (bindings === void 0) return;
|
|
865
|
+
for (const [name, address] of Record.toEntries(boundOutputs(bound))) {
|
|
866
|
+
if (!bindings.has(name)) continue;
|
|
867
|
+
const { wire } = yield* address.stream;
|
|
868
|
+
yield* createOutput(address, wire);
|
|
869
|
+
}
|
|
870
|
+
});
|
|
871
|
+
const collect = (outputs, buffers, emitted) => Effect.gen(function* () {
|
|
872
|
+
for (const [name, entries] of Record.toEntries(emitted)) {
|
|
873
|
+
const output = outputs[name];
|
|
874
|
+
if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* new ProjectionFault({
|
|
875
|
+
phase: "process",
|
|
876
|
+
reason: "invalid-output",
|
|
877
|
+
message: `Invalid output array ${name}`
|
|
878
|
+
});
|
|
879
|
+
const values = yield* Effect.try({
|
|
880
|
+
try: () => "collections" in output ? DurableState.changes(output, {}, entries) : entries,
|
|
881
|
+
catch: (cause) => new ProjectionFault({
|
|
882
|
+
phase: "process",
|
|
883
|
+
reason: "invalid-output",
|
|
884
|
+
message: `Invalid row change for ${name}`,
|
|
885
|
+
cause
|
|
886
|
+
})
|
|
887
|
+
});
|
|
888
|
+
(buffers[name] ??= []).push(...values);
|
|
889
|
+
}
|
|
890
|
+
return yield* Effect.void;
|
|
891
|
+
});
|
|
892
|
+
const pin = (reason, message, cause) => new ProjectionFault({
|
|
893
|
+
phase: "pin",
|
|
894
|
+
reason,
|
|
895
|
+
message,
|
|
896
|
+
cause
|
|
897
|
+
});
|
|
898
|
+
/** Append one unit under its pinned tuple; appended and duplicate are one outcome. */
|
|
899
|
+
const appendPinned = Effect.fn("Projection.appendPinned")(function* (output, wire, items, position) {
|
|
900
|
+
return yield* Streams.append(output, items, { producer: position }).pipe(Effect.provideService(StreamsWriter, wire), Effect.catchTags({
|
|
901
|
+
EncodeFault: () => new ProjectionFault({
|
|
902
|
+
phase: "process",
|
|
903
|
+
reason: "invalid-output",
|
|
904
|
+
message: `Cannot encode output for ${output.id}`
|
|
905
|
+
}),
|
|
906
|
+
StaleEpoch: (error) => pin("stale-epoch", `Epoch ${position.producerEpoch} of ${output.id} is behind ${error.currentEpoch}`),
|
|
907
|
+
ProducerGap: (error) => pin("invalid-record", `Sequence ${error.receivedSeq} of ${output.id} does not follow ${error.expectedSeq}`),
|
|
908
|
+
NotSupported: (error) => pin("unsupported-composition", `${output.id} does not support ${error.feature}`),
|
|
909
|
+
StorageFault: (cause) => pin("storage-failure", `Cannot append to ${output.id}`, cause),
|
|
910
|
+
TransportFault: (cause) => pin("storage-failure", `Cannot append to ${output.id}`, cause),
|
|
911
|
+
StreamNotFound: () => pin("invalid-output", `Output ${output.id} does not exist`),
|
|
912
|
+
StreamGone: () => pin("invalid-output", `Output ${output.id} is gone`),
|
|
913
|
+
StreamClosed: () => pin("invalid-output", `Output ${output.id} is closed`),
|
|
914
|
+
AppendConflict: () => pin("invalid-output", `Output ${output.id} refused the append`),
|
|
915
|
+
StreamBusy: () => pin("output-busy", `Output ${output.id} is busy`)
|
|
916
|
+
}));
|
|
917
|
+
});
|
|
681
918
|
// src/state.ts
|
|
682
919
|
const bindState = (definition, params) => {
|
|
683
920
|
const initial = definition.initial;
|
|
@@ -716,10 +953,10 @@ const wakeAt = (time) => {
|
|
|
716
953
|
const isWakeAt = (value) => Predicate.isTagged(value, "WakeAt");
|
|
717
954
|
// src/step.ts
|
|
718
955
|
/** One adapter invocation is one unit. Per-entry variants thread state and preserve order. */
|
|
719
|
-
const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepared, attempt = 1) => Effect.gen(function* () {
|
|
956
|
+
const adapt = (kind, key, state, streams, outputs, handler, batch, unit, encoded, prepared, attempt = 1) => Effect.gen(function* () {
|
|
720
957
|
if (kind === "process") return yield* Effect.map(handler(batch, unit, {
|
|
721
958
|
prepared,
|
|
722
|
-
outputs
|
|
959
|
+
outputs,
|
|
723
960
|
attempt
|
|
724
961
|
}), (result) => isWakeAt(result) ? result : void 0);
|
|
725
962
|
let value = state === void 0 ? void 0 : yield* currentState(key, state, encoded);
|
|
@@ -751,6 +988,9 @@ const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepare
|
|
|
751
988
|
});
|
|
752
989
|
});
|
|
753
990
|
// src/declaration.ts
|
|
991
|
+
/** Internal access to the same binding at a chosen generation. */
|
|
992
|
+
const BindGeneration = Symbol.for("@streamsy/projection/internal/BindGeneration");
|
|
993
|
+
const bindAtGeneration = (declaration, params, generation) => declaration[BindGeneration]?.(params, generation);
|
|
754
994
|
const isDeclaration = (input) => "at" in input;
|
|
755
995
|
const encodeParams = (id, codecs, params) => {
|
|
756
996
|
const values = params;
|
|
@@ -766,22 +1006,21 @@ const addressesOf = (inputs, params) => {
|
|
|
766
1006
|
const declare = (definition, bind) => {
|
|
767
1007
|
const version = definition.version ?? 1;
|
|
768
1008
|
const generation = definition.generation ?? 1;
|
|
769
|
-
|
|
1009
|
+
const atGeneration = (params, selected) => bind({
|
|
1010
|
+
id: definition.id,
|
|
1011
|
+
version,
|
|
1012
|
+
generation: selected,
|
|
1013
|
+
params: encodeParams(definition.id, definition.params, params),
|
|
1014
|
+
decoded: params
|
|
1015
|
+
});
|
|
1016
|
+
const declaration = {
|
|
770
1017
|
retry: definition.retry,
|
|
771
1018
|
id: definition.id,
|
|
772
1019
|
version,
|
|
773
1020
|
generation,
|
|
774
1021
|
params: definition.params,
|
|
775
1022
|
inputs: definition.inputs,
|
|
776
|
-
at: (params) =>
|
|
777
|
-
return bind({
|
|
778
|
-
id: definition.id,
|
|
779
|
-
version,
|
|
780
|
-
generation,
|
|
781
|
-
params: encodeParams(definition.id, definition.params, params),
|
|
782
|
-
decoded: params
|
|
783
|
-
});
|
|
784
|
-
},
|
|
1023
|
+
at: (params) => atGeneration(params, generation),
|
|
785
1024
|
parse: (id) => {
|
|
786
1025
|
for (const input of Record.values(definition.inputs)) {
|
|
787
1026
|
if (!isDeclaration(input)) continue;
|
|
@@ -791,30 +1030,37 @@ const declare = (definition, bind) => {
|
|
|
791
1030
|
return Option.none();
|
|
792
1031
|
}
|
|
793
1032
|
};
|
|
1033
|
+
return Object.defineProperty(declaration, BindGeneration, { value: atGeneration });
|
|
794
1034
|
};
|
|
795
1035
|
const build = (kind, definition) => {
|
|
796
1036
|
const commit = definition.commit ?? checkpoint;
|
|
797
|
-
|
|
1037
|
+
const outputs = definition.outputs ?? {};
|
|
1038
|
+
for (const output of Record.values(outputs)) {
|
|
1039
|
+
validateGenerationParam(output, definition.params);
|
|
1040
|
+
if (isPerGeneration(output) && generationBinding(output).routeBy !== void 0) {
|
|
1041
|
+
if (kind !== "process") throw new RangeError("Routed outputs require Projection.process");
|
|
1042
|
+
if (!supportsPrepare(commit)) throw new RangeError("Routed outputs require Commit.transaction");
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
validateAccepted(definition.accepted, definition.params, Array.map(Array.filter(Record.values(definition.inputs), isDeclaration), (input) => input.template), commit, Record.keys(outputs));
|
|
798
1046
|
if (definition.prepare !== void 0 && !supportsPrepare(commit)) throw new RangeError("prepare requires Commit.transaction");
|
|
799
1047
|
return declare(definition, ({ decoded, ...key }) => {
|
|
800
1048
|
const state = definition.state === void 0 ? void 0 : bindState(definition.state, decoded);
|
|
801
1049
|
const inputs = addressesOf(definition.inputs, decoded);
|
|
802
|
-
const streams = resolveOutputs(definition.
|
|
803
|
-
const
|
|
804
|
-
if (accepted !== void 0) resolveOutputs({
|
|
805
|
-
...streams,
|
|
806
|
-
[acceptedKey]: accepted
|
|
807
|
-
}, decoded, inputs);
|
|
808
|
-
return {
|
|
1050
|
+
const { streams, accepted, generationOutputs, routed, handlerOutputs } = resolveOutputs(outputs, definition.accepted, decoded, key, inputs);
|
|
1051
|
+
const bound = {
|
|
809
1052
|
...key,
|
|
810
1053
|
inputs,
|
|
811
1054
|
state,
|
|
812
1055
|
streams,
|
|
813
1056
|
accepted,
|
|
814
1057
|
commit,
|
|
815
|
-
prepare: definition.prepare === void 0 ? void 0 : (batch, unit) => definition.prepare(batch, withParams(unit, decoded), { outputs:
|
|
816
|
-
process: (batch, unit, encoded, prepared, attempt = 1) => adapt(kind, key, state, streams, definition[kind], batch, withParams(unit, decoded), encoded, prepared, attempt)
|
|
1058
|
+
prepare: definition.prepare === void 0 ? void 0 : (batch, unit) => definition.prepare(batch, withParams(unit, decoded), { outputs: handlerOutputs }),
|
|
1059
|
+
process: (batch, unit, encoded, prepared, attempt = 1) => adapt(kind, key, state, streams, handlerOutputs, definition[kind], batch, withParams(unit, decoded), encoded, prepared, attempt)
|
|
817
1060
|
};
|
|
1061
|
+
if (generationOutputs.size > 0) Object.assign(bound, { [GenerationOutputs]: generationOutputs });
|
|
1062
|
+
if (routed.size > 0) Object.assign(bound, { [RoutedOutputs]: routed });
|
|
1063
|
+
return bound;
|
|
818
1064
|
});
|
|
819
1065
|
};
|
|
820
1066
|
// src/fold.ts
|
|
@@ -838,7 +1084,8 @@ function mapAccumBatch(definition) {
|
|
|
838
1084
|
}
|
|
839
1085
|
// src/forget.ts
|
|
840
1086
|
/**
|
|
841
|
-
* Deletes
|
|
1087
|
+
* Deletes a live record and preserves retirement tombstones. Stop the follower first,
|
|
1088
|
+
* or use a new generation.
|
|
842
1089
|
* Delete stream outputs first, because forgetting restarts their producer sequences.
|
|
843
1090
|
*/
|
|
844
1091
|
const forget = (projection) => Effect.gen(function* () {
|
|
@@ -949,16 +1196,17 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
|
|
|
949
1196
|
};
|
|
950
1197
|
if (gone) Object.assign(next, { ended: true });
|
|
951
1198
|
const outputs = {};
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
service
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
const address = projection.accepted;
|
|
958
|
-
outputs[acceptedKey] = {
|
|
1199
|
+
let generationOutputs;
|
|
1200
|
+
for (const [name, address] of Record.toEntries(boundOutputs(projection))) {
|
|
1201
|
+
const service = yield* address.stream;
|
|
1202
|
+
const generation = projection[GenerationOutputs]?.get(name);
|
|
1203
|
+
const output = {
|
|
959
1204
|
address,
|
|
960
|
-
service
|
|
1205
|
+
service,
|
|
1206
|
+
generation
|
|
961
1207
|
};
|
|
1208
|
+
outputs[name] = output;
|
|
1209
|
+
if (generation !== void 0) (generationOutputs ??= /* @__PURE__ */ new Map()).set(name, output);
|
|
962
1210
|
}
|
|
963
1211
|
let prepared;
|
|
964
1212
|
let result;
|
|
@@ -989,6 +1237,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
|
|
|
989
1237
|
upToDate: batch[name]?.upToDate ?? false
|
|
990
1238
|
}]))
|
|
991
1239
|
});
|
|
1240
|
+
if (generationOutputs !== void 0) Object.assign(request, { generationOutputs });
|
|
992
1241
|
yield* projection.commit.apply(request).pipe(Effect.catchTag("HandlerFailed", (failure) => Effect.fail(failure.error)));
|
|
993
1242
|
const stored = withState(next, result);
|
|
994
1243
|
if (gone) yield* forget(projection);
|
|
@@ -1266,8 +1515,16 @@ const registerRunner = (registry, runner) => {
|
|
|
1266
1515
|
return registration === void 0 ? Effect.die(/* @__PURE__ */ new Error("Projection runners require Registry.layer; a hand-built Registry has no registration support")) : registration.register(runner).pipe(Effect.as(registration.publish));
|
|
1267
1516
|
};
|
|
1268
1517
|
// src/failure.ts
|
|
1518
|
+
const nonRetryableHandlerReason = "non-retryable-handler";
|
|
1519
|
+
const marked = (reason) => Cause.isFailReason(reason) && Predicate.hasProperty(reason.error, NonRetryable) && reason.error[NonRetryable] === true;
|
|
1520
|
+
const hasNonRetryableHandler = (cause) => Array.some(cause.reasons, marked);
|
|
1269
1521
|
/** Unknown handler errors and defects retry; only a known non-retryable fault stops work. */
|
|
1270
|
-
const retryable = (cause) => !Array.some(cause.reasons, (reason) =>
|
|
1522
|
+
const retryable = (cause) => !Array.some(cause.reasons, (reason) => {
|
|
1523
|
+
if (!Cause.isFailReason(reason)) return false;
|
|
1524
|
+
const { error } = reason;
|
|
1525
|
+
if (marked(reason)) return true;
|
|
1526
|
+
return (Schema.is(ProjectionFault)(error) || Schema.is(StorageFault)(error)) && !error.retryable;
|
|
1527
|
+
});
|
|
1271
1528
|
const runnerFailure = (cause, at) => ({
|
|
1272
1529
|
at,
|
|
1273
1530
|
retryable: retryable(cause),
|
|
@@ -1293,7 +1550,7 @@ const invalid = (id, message, cause) => new ProjectionFault({
|
|
|
1293
1550
|
cause
|
|
1294
1551
|
});
|
|
1295
1552
|
/** Persistent local ingestion on both hosts; process hosts also ingest and follow other owners. */
|
|
1296
|
-
const triggersOf = (projection, declarations, match, marks, host = "process") => Effect.gen(function* () {
|
|
1553
|
+
const triggersOf = (projection, generation, declarations, match, marks, host = "process") => Effect.gen(function* () {
|
|
1297
1554
|
const storage = yield* Storage;
|
|
1298
1555
|
const records = yield* Effect.serviceOption(OwnerRecords);
|
|
1299
1556
|
const boundary = yield* Effect.serviceOption(CommitBoundary);
|
|
@@ -1324,6 +1581,7 @@ const triggersOf = (projection, declarations, match, marks, host = "process") =>
|
|
|
1324
1581
|
streams.set(id, encodeKey([
|
|
1325
1582
|
"streamsy.projection.trigger.v1",
|
|
1326
1583
|
projection,
|
|
1584
|
+
String(generation),
|
|
1327
1585
|
id
|
|
1328
1586
|
]));
|
|
1329
1587
|
}
|
|
@@ -1536,6 +1794,124 @@ const triggersOf = (projection, declarations, match, marks, host = "process") =>
|
|
|
1536
1794
|
}))
|
|
1537
1795
|
};
|
|
1538
1796
|
});
|
|
1797
|
+
// src/catch-up.ts
|
|
1798
|
+
const Tail = Schema.Struct({
|
|
1799
|
+
stream: StreamId,
|
|
1800
|
+
offset: Offset,
|
|
1801
|
+
closed: Schema.Boolean
|
|
1802
|
+
});
|
|
1803
|
+
/** A serializable vector of fixed source tails, keyed by input name. */
|
|
1804
|
+
const Tails = Schema.Record(Schema.String, Tail);
|
|
1805
|
+
const isOffset = Schema.is(Offset);
|
|
1806
|
+
const historyUnavailable = (input, message, cause) => new ProjectionFault({
|
|
1807
|
+
phase: "read",
|
|
1808
|
+
reason: "history-unavailable",
|
|
1809
|
+
input,
|
|
1810
|
+
message,
|
|
1811
|
+
cause
|
|
1812
|
+
});
|
|
1813
|
+
const head$1 = Effect.fn("Projection.catchUp.head")(function* (name, address) {
|
|
1814
|
+
const { wire } = yield* address.stream;
|
|
1815
|
+
const storageFailure = (cause) => new ProjectionFault({
|
|
1816
|
+
phase: "read",
|
|
1817
|
+
reason: "storage-failure",
|
|
1818
|
+
input: name,
|
|
1819
|
+
message: `Cannot read the head of ${address.id}`,
|
|
1820
|
+
cause
|
|
1821
|
+
});
|
|
1822
|
+
const result = yield* wire.head(address.id).pipe(Effect.catchTags({
|
|
1823
|
+
StreamNotFound: (cause) => historyUnavailable(name, `Input stream ${address.id} is missing`, cause),
|
|
1824
|
+
StreamGone: (cause) => historyUnavailable(name, `Input stream ${address.id} is gone`, cause),
|
|
1825
|
+
StorageFault: storageFailure,
|
|
1826
|
+
TransportFault: storageFailure
|
|
1827
|
+
}));
|
|
1828
|
+
if (!isOffset(result.nextOffset)) return yield* new ProjectionFault({
|
|
1829
|
+
phase: "read",
|
|
1830
|
+
reason: "invalid-source",
|
|
1831
|
+
input: name,
|
|
1832
|
+
message: `Head of ${address.id} has an invalid offset`
|
|
1833
|
+
});
|
|
1834
|
+
return {
|
|
1835
|
+
stream: address.id,
|
|
1836
|
+
offset: result.nextOffset,
|
|
1837
|
+
closed: result.closed
|
|
1838
|
+
};
|
|
1839
|
+
});
|
|
1840
|
+
/** Capture each resolved input head once. The vector can be reused while producers keep writing. */
|
|
1841
|
+
const tails = Effect.fn("Projection.tails")(function* (projection) {
|
|
1842
|
+
const entries = yield* Effect.forEach(inputEntries(projection.inputs), ([name, address]) => head$1(name, address).pipe(Effect.map((value) => [name, value])));
|
|
1843
|
+
return Record.fromEntries(entries);
|
|
1844
|
+
});
|
|
1845
|
+
const validateTails = Effect.fnUntraced(function* (projection, targets) {
|
|
1846
|
+
const decoded = yield* Schema.decodeEffect(Tails, {
|
|
1847
|
+
onExcessProperty: "error",
|
|
1848
|
+
reportInput: true
|
|
1849
|
+
})(targets).pipe(Effect.mapError((cause) => new ProjectionFault({
|
|
1850
|
+
phase: "load",
|
|
1851
|
+
reason: "invalid-options",
|
|
1852
|
+
message: `Invalid tails for ${projection.id}: ${cause.message}`,
|
|
1853
|
+
cause
|
|
1854
|
+
})));
|
|
1855
|
+
for (const [name, address] of inputEntries(projection.inputs)) if (decoded[name]?.stream !== address.id) return yield* new ProjectionFault({
|
|
1856
|
+
phase: "load",
|
|
1857
|
+
reason: "identity-mismatch",
|
|
1858
|
+
input: name,
|
|
1859
|
+
message: `Tail for ${name} must name stream ${address.id}`
|
|
1860
|
+
});
|
|
1861
|
+
if (Record.size(decoded) !== Record.size(projection.inputs)) return yield* new ProjectionFault({
|
|
1862
|
+
phase: "load",
|
|
1863
|
+
reason: "identity-mismatch",
|
|
1864
|
+
message: `Tail input names differ from the declaration of ${projection.id}`
|
|
1865
|
+
});
|
|
1866
|
+
return decoded;
|
|
1867
|
+
});
|
|
1868
|
+
const measure = Effect.fnUntraced(function* (projection, targets, verifyHeads) {
|
|
1869
|
+
const { record } = yield* restore(projection, projection.commit);
|
|
1870
|
+
if (record.ended) return yield* new ProjectionFault({
|
|
1871
|
+
phase: "load",
|
|
1872
|
+
reason: "history-unavailable",
|
|
1873
|
+
message: `Binding of ${projection.id} ended after an input was lost`
|
|
1874
|
+
});
|
|
1875
|
+
const entries = yield* Effect.forEach(inputEntries(projection.inputs), Effect.fnUntraced(function* ([name, address]) {
|
|
1876
|
+
const committed = record.inputs[name];
|
|
1877
|
+
const target = targets[name];
|
|
1878
|
+
if (!isOffset(committed)) return yield* new ProjectionFault({
|
|
1879
|
+
phase: "load",
|
|
1880
|
+
reason: "invalid-record",
|
|
1881
|
+
input: name,
|
|
1882
|
+
message: `Stored offset for ${name} is not a valid offset`
|
|
1883
|
+
});
|
|
1884
|
+
if (verifyHeads) {
|
|
1885
|
+
const current = yield* head$1(name, address);
|
|
1886
|
+
const order = compare(current.offset, target.offset);
|
|
1887
|
+
if (order < 0 || target.closed && (!current.closed || order !== 0)) return yield* historyUnavailable(name, `Head of ${address.id} no longer contains its tail`);
|
|
1888
|
+
}
|
|
1889
|
+
const behind = compare(committed, target.offset) < 0 || target.closed && record.closed?.[name] !== true || record.pending !== void 0 && Record.has(record.pending.ranges, name);
|
|
1890
|
+
return [name, {
|
|
1891
|
+
committed,
|
|
1892
|
+
target: target.offset,
|
|
1893
|
+
behind
|
|
1894
|
+
}];
|
|
1895
|
+
}));
|
|
1896
|
+
return {
|
|
1897
|
+
caughtUp: record.pending === void 0 && Array.every(entries, ([, input]) => !input.behind),
|
|
1898
|
+
inputs: Record.fromEntries(entries)
|
|
1899
|
+
};
|
|
1900
|
+
});
|
|
1901
|
+
/** Compare fixed source tails with one committed checkpoint, including processed closes. Checks source readiness only. */
|
|
1902
|
+
const lag = Effect.fn("Projection.lag")(function* (projection, targets) {
|
|
1903
|
+
const fixed = targets === void 0 ? yield* tails(projection) : yield* validateTails(projection, targets);
|
|
1904
|
+
return yield* measure(projection, fixed, targets !== void 0);
|
|
1905
|
+
});
|
|
1906
|
+
const pollInterval = "250 millis";
|
|
1907
|
+
/** Wait for one fixed vector of source tails. The caller controls the timeout. */
|
|
1908
|
+
const caughtUp = Effect.fn("Projection.caughtUp")(function* (projection, targets) {
|
|
1909
|
+
const fixed = targets === void 0 ? yield* tails(projection) : yield* validateTails(projection, targets);
|
|
1910
|
+
return yield* measure(projection, fixed, true).pipe(Effect.repeat({
|
|
1911
|
+
schedule: Schedule.spaced(pollInterval),
|
|
1912
|
+
while: (progress) => !progress.caughtUp
|
|
1913
|
+
}), Effect.asVoid);
|
|
1914
|
+
});
|
|
1539
1915
|
// src/runner.ts
|
|
1540
1916
|
/** Re-read wall time after a suspended host resumes, even for distant deadlines. */
|
|
1541
1917
|
const MAX_DUE_WAIT_MS = 3e4;
|
|
@@ -1595,6 +1971,26 @@ const bindingOf = (declaration, key) => Option.flatMap(Schema.decodeOption(Param
|
|
|
1595
1971
|
return Option.none();
|
|
1596
1972
|
}
|
|
1597
1973
|
});
|
|
1974
|
+
const startupInventory = Effect.fn("Projection.startupInventory")(function* (declaration) {
|
|
1975
|
+
const store = yield* Effect.serviceOption(CheckpointStore);
|
|
1976
|
+
const list = Option.getOrUndefined(store)?.list;
|
|
1977
|
+
const id = declaration.id;
|
|
1978
|
+
return yield* Effect.gen(function* () {
|
|
1979
|
+
if (list === void 0) return [];
|
|
1980
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1981
|
+
const current = /* @__PURE__ */ new Set();
|
|
1982
|
+
for (const { generation, params } of yield* list(id)) (generation === declaration.generation ? current : keys).add(canonicalParams(params));
|
|
1983
|
+
if (Record.isEmptyRecord(declaration.params)) keys.add(canonicalParams({}));
|
|
1984
|
+
for (const key of current) keys.delete(key);
|
|
1985
|
+
const candidates = [];
|
|
1986
|
+
for (const key of keys) {
|
|
1987
|
+
const bound = bindingOf(declaration, key);
|
|
1988
|
+
if (Option.isSome(bound)) candidates.push(bound.value);
|
|
1989
|
+
else yield* Effect.logWarning(`Projection ${id} skipped startup params ${key}: they no longer decode`);
|
|
1990
|
+
}
|
|
1991
|
+
return candidates;
|
|
1992
|
+
}).pipe(Effect.catchIf((fault) => fault.reason === "unsupported-composition" || fault.reason === "invalid-record", (fault) => Effect.logWarning(`Projection ${id} skipped startup inventory: ${fault.message}. Supply attach bindings explicitly.`).pipe(Effect.as([]))));
|
|
1993
|
+
});
|
|
1598
1994
|
/**
|
|
1599
1995
|
* A binding that faults with `history-unavailable` on an input whose head is
|
|
1600
1996
|
* absent can never run: its source is gone, and an id never returns. With a
|
|
@@ -1685,16 +2081,41 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
1685
2081
|
const marks = durable ? yield* durableMarks(declaration.id, match) : memoryProjectionMarks();
|
|
1686
2082
|
let failure = Option.none();
|
|
1687
2083
|
let started = false;
|
|
1688
|
-
const
|
|
2084
|
+
const startPermit = yield* Semaphore.make(1);
|
|
2085
|
+
const prepare = Effect.fnUntraced(function* (binding) {
|
|
2086
|
+
const loaded = yield* binding.commit.load(binding);
|
|
2087
|
+
if (Option.isSome(loaded.record)) return false;
|
|
2088
|
+
if ((binding[GenerationOutputs]?.size ?? 0) > 0) {
|
|
2089
|
+
yield* tails(binding);
|
|
2090
|
+
yield* createOutputs(binding);
|
|
2091
|
+
}
|
|
2092
|
+
return true;
|
|
2093
|
+
});
|
|
2094
|
+
const seed = Effect.gen(function* () {
|
|
2095
|
+
const candidates = options.bindings === void 0 ? yield* startupInventory(declaration) : yield* options.bindings.pipe(Effect.map(Array.map((params) => declaration.at(params))), Effect.catch((error) => Effect.logError(`Projection ${declaration.id} skipped startup replay: the bindings option failed`, error).pipe(Effect.as([]))));
|
|
2096
|
+
const byKey = new Map(Array.map(candidates, (binding) => [canonicalParams(binding.params), binding]));
|
|
2097
|
+
for (const chunk of Array.chunksOf([...byKey], SCHEDULE_CHUNK)) {
|
|
2098
|
+
const keys = [];
|
|
2099
|
+
for (const [key, binding] of chunk) if (yield* prepare(binding).pipe(Effect.catchIf((fault) => fault.reason === "retired-generation" || fault.reason === "history-unavailable", () => Effect.succeed(false)))) keys.push(key);
|
|
2100
|
+
if (keys.length > 0) yield* marks.mark(declaration.id, keys).pipe(Effect.mapError(storageFault("marks.mark")));
|
|
2101
|
+
}
|
|
2102
|
+
}).pipe(Effect.mapError((cause) => new StorageFault({
|
|
2103
|
+
operation: "projection.startup",
|
|
2104
|
+
message: `Cannot queue startup replay for ${declaration.id}`,
|
|
2105
|
+
retryable: retryable(Cause.fail(cause)),
|
|
2106
|
+
cause
|
|
2107
|
+
})));
|
|
2108
|
+
const start = startPermit.withPermit(Effect.gen(function* () {
|
|
1689
2109
|
if (started) return;
|
|
1690
2110
|
yield* marks.resume(declaration.id);
|
|
2111
|
+
yield* seed;
|
|
1691
2112
|
started = true;
|
|
1692
2113
|
}));
|
|
1693
2114
|
const observeFailure = (effect) => effect.pipe(Effect.catchCause((cause) => Effect.gen(function* () {
|
|
1694
2115
|
failure = Option.some(runnerFailure(cause, yield* Clock.currentTimeMillis));
|
|
1695
2116
|
return yield* Effect.failCause(cause);
|
|
1696
2117
|
})));
|
|
1697
|
-
const triggers = options.triggers === void 0 || options.triggers.length === 0 ? void 0 : yield* triggersOf(declaration.id, options.triggers, match, marks, host);
|
|
2118
|
+
const triggers = options.triggers === void 0 || options.triggers.length === 0 ? void 0 : yield* triggersOf(declaration.id, declaration.generation, options.triggers, match, marks, host);
|
|
1698
2119
|
const add = (ids) => Effect.gen(function* () {
|
|
1699
2120
|
const bindings = /* @__PURE__ */ new Map();
|
|
1700
2121
|
for (const id of ids) {
|
|
@@ -1793,10 +2214,14 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
1793
2214
|
}).pipe(Effect.catchCause((cause) => Effect.logError(`Projection ${id} binding ${key} onExhausted failed`, cause)));
|
|
1794
2215
|
}
|
|
1795
2216
|
const dueAt = Option.map(delay, (ms) => failed.at + ms);
|
|
2217
|
+
const reason = hasNonRetryableHandler(exit.cause) ? Option.some(nonRetryableHandlerReason) : failed.reason;
|
|
1796
2218
|
yield* marks.fail(id, key, {
|
|
1797
2219
|
attempts,
|
|
1798
2220
|
dueAt,
|
|
1799
|
-
failure:
|
|
2221
|
+
failure: {
|
|
2222
|
+
...failed,
|
|
2223
|
+
reason
|
|
2224
|
+
}
|
|
1800
2225
|
});
|
|
1801
2226
|
if (publish !== void 0) yield* publish(RunnerEvent.Failed({
|
|
1802
2227
|
projection: id,
|
|
@@ -1880,7 +2305,7 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
1880
2305
|
attempts: row.attempts,
|
|
1881
2306
|
dueAt: row.stopped ? Option.none() : Option.some(row.dueAt),
|
|
1882
2307
|
stopped: row.stopped,
|
|
1883
|
-
exhausted: row.stopped && (row.attempts >= (declaration.retry?.maxAttempts ?? Number.POSITIVE_INFINITY) || Option.isNone(yield* bindingDelay(declaration.retry?.schedule, row.attempts))),
|
|
2308
|
+
exhausted: row.stopped && !Option.contains(Option.flatMap(row.failure, (failed) => failed.reason), "non-retryable-handler") && (row.attempts >= (declaration.retry?.maxAttempts ?? Number.POSITIVE_INFINITY) || Option.isNone(yield* bindingDelay(declaration.retry?.schedule, row.attempts))),
|
|
1884
2309
|
failure: row.failure
|
|
1885
2310
|
};
|
|
1886
2311
|
}));
|
|
@@ -1912,6 +2337,8 @@ var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Sche
|
|
|
1912
2337
|
* subscribes to `Storage.committed` when it is built, so build it with the
|
|
1913
2338
|
* storage layer and before the app writes. For each written id, the input's
|
|
1914
2339
|
* `parse` gives the params, and the runner runs `projection.at(params)`.
|
|
2340
|
+
* The background runner also queues startup replays from the checkpoint
|
|
2341
|
+
* inventory or `options.bindings`.
|
|
1915
2342
|
*
|
|
1916
2343
|
* Use it on long-lived hosts (Bun, Node). On a Cloudflare object, use
|
|
1917
2344
|
* `ProjectionWakeup.attach(projection)`.
|
|
@@ -2025,6 +2452,35 @@ const current = Effect.fn("Projection.current")(function* (projection) {
|
|
|
2025
2452
|
offsets = advance(offsets, ranges);
|
|
2026
2453
|
}
|
|
2027
2454
|
});
|
|
2455
|
+
// src/bindings.ts
|
|
2456
|
+
/**
|
|
2457
|
+
* Lists the decoded params of bindings with live checkpoints in the selected store.
|
|
2458
|
+
* By default it includes every generation of the declaration's id, across checkpoint
|
|
2459
|
+
* versions. A generation filter still includes every version at that generation.
|
|
2460
|
+
* Each binding appears once, in unspecified order.
|
|
2461
|
+
*
|
|
2462
|
+
* Fails with `InvalidBinding` if live params cannot round-trip through the current
|
|
2463
|
+
* codecs. MySQL owner stores fail because historical hashed keys cannot be decoded.
|
|
2464
|
+
*/
|
|
2465
|
+
const bindings = Effect.fn("Projection.bindings")(function* (declaration, options) {
|
|
2466
|
+
const store = yield* CheckpointStore;
|
|
2467
|
+
if (store.list === void 0) return yield* unsupportedBindingList();
|
|
2468
|
+
const schema = Schema.Struct(declaration.params);
|
|
2469
|
+
const decode = Schema.decodeUnknownEffect(schema, { onExcessProperty: "error" });
|
|
2470
|
+
const encode = Schema.encodeEffect(schema);
|
|
2471
|
+
const stored = /* @__PURE__ */ new Map();
|
|
2472
|
+
for (const { generation, params } of yield* store.list(declaration.id)) if (options?.generation === void 0 || generation === options.generation) stored.set(canonicalParams(params), params);
|
|
2473
|
+
return yield* Effect.forEach(stored.values(), (params) => Effect.gen(function* () {
|
|
2474
|
+
const invalid = () => new InvalidBinding({
|
|
2475
|
+
projection: declaration.id,
|
|
2476
|
+
params
|
|
2477
|
+
});
|
|
2478
|
+
const decoded = yield* decode(params).pipe(Effect.mapError(invalid));
|
|
2479
|
+
const encoded = yield* encode(decoded).pipe(Effect.mapError(invalid));
|
|
2480
|
+
if (canonicalParams(encoded) !== canonicalParams(params)) return yield* invalid();
|
|
2481
|
+
return decoded;
|
|
2482
|
+
}));
|
|
2483
|
+
});
|
|
2028
2484
|
// src/decide.ts
|
|
2029
2485
|
/** Up to three retries after a lost race, so at most four appends per call. */
|
|
2030
2486
|
const defaultDecideRetry = Schedule.recurs(3);
|
|
@@ -2076,6 +2532,106 @@ const retryLostRace = Effect.fnUntraced(function* (attempt, schedule) {
|
|
|
2076
2532
|
return yield* Effect.fromResult(outcome);
|
|
2077
2533
|
});
|
|
2078
2534
|
const isOffsetMismatch = (error) => Predicate.isTagged(error, "OffsetMismatch");
|
|
2535
|
+
// src/retire.ts
|
|
2536
|
+
const cleanStream = (address, wire, mode) => {
|
|
2537
|
+
const { id, contentType } = address;
|
|
2538
|
+
return (mode === "remove" ? wire.remove(id).pipe(Effect.as("removed")) : wire.append(id, {
|
|
2539
|
+
close: true,
|
|
2540
|
+
data: /* @__PURE__ */ new Uint8Array(),
|
|
2541
|
+
contentType
|
|
2542
|
+
}).pipe(Effect.as("closed"), Effect.catchTag("StreamClosed", () => Effect.succeed("closed")))).pipe(Effect.catchTags({
|
|
2543
|
+
StreamNotFound: () => Effect.succeed("absent"),
|
|
2544
|
+
StreamGone: () => Effect.succeed("absent")
|
|
2545
|
+
}), Effect.mapError((cause) => new ProjectionFault({
|
|
2546
|
+
phase: "checkpoint",
|
|
2547
|
+
reason: Predicate.isTagged(cause, "StreamBusy") ? "output-busy" : isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
2548
|
+
message: `Cannot ${mode} output ${id}`,
|
|
2549
|
+
cause
|
|
2550
|
+
})));
|
|
2551
|
+
};
|
|
2552
|
+
/** Retire one binding and clean up its exclusively owned generation outputs. */
|
|
2553
|
+
const retire = (declaration, params, options) => {
|
|
2554
|
+
const bound = bindAtGeneration(declaration, params, options.generation);
|
|
2555
|
+
const mode = options.streams ?? "remove";
|
|
2556
|
+
return Effect.gen(function* () {
|
|
2557
|
+
if (bound?.commit.retire === void 0) return yield* new ProjectionFault({
|
|
2558
|
+
phase: "checkpoint",
|
|
2559
|
+
reason: "unsupported-composition",
|
|
2560
|
+
message: "Retirement requires a projection declaration with a Commit that supports it"
|
|
2561
|
+
});
|
|
2562
|
+
const outputs = [];
|
|
2563
|
+
const owned = [];
|
|
2564
|
+
const bindings = bound[GenerationOutputs];
|
|
2565
|
+
const routes = bound[RoutedOutputs];
|
|
2566
|
+
const routed = /* @__PURE__ */ new Map();
|
|
2567
|
+
const context = yield* Effect.context();
|
|
2568
|
+
if (routes !== void 0) for (const name of routes.keys()) routed.set(name, []);
|
|
2569
|
+
for (const [name, address] of Record.toEntries(boundOutputs(bound))) {
|
|
2570
|
+
const binding = bindings?.get(name);
|
|
2571
|
+
if (binding === void 0) continue;
|
|
2572
|
+
if (binding.shared) outputs.push([name, {
|
|
2573
|
+
id: address.id,
|
|
2574
|
+
result: "shared"
|
|
2575
|
+
}]);
|
|
2576
|
+
else owned.push({
|
|
2577
|
+
name,
|
|
2578
|
+
address,
|
|
2579
|
+
service: yield* address.stream
|
|
2580
|
+
});
|
|
2581
|
+
}
|
|
2582
|
+
const retired = {
|
|
2583
|
+
record: yield* bound.commit.retire({
|
|
2584
|
+
key: {
|
|
2585
|
+
id: bound.id,
|
|
2586
|
+
version: bound.version,
|
|
2587
|
+
generation: bound.generation,
|
|
2588
|
+
params: bound.params
|
|
2589
|
+
},
|
|
2590
|
+
cleanup: Effect.gen(function* () {
|
|
2591
|
+
const owner = yield* CurrentOwner;
|
|
2592
|
+
const clean = (address, service) => {
|
|
2593
|
+
if (owner !== void 0 && service.owner !== owner) return Effect.fail(new ProjectionFault({
|
|
2594
|
+
phase: "checkpoint",
|
|
2595
|
+
reason: "unsupported-composition",
|
|
2596
|
+
message: `Output ${address.id} does not share the transaction owner`
|
|
2597
|
+
}));
|
|
2598
|
+
return cleanStream(address, service.wire, mode).pipe(Effect.map((result) => ({
|
|
2599
|
+
id: address.id,
|
|
2600
|
+
result
|
|
2601
|
+
})));
|
|
2602
|
+
};
|
|
2603
|
+
for (const { name, address, service } of owned) outputs.push([name, yield* clean(address, service)]);
|
|
2604
|
+
if (routes !== void 0) {
|
|
2605
|
+
const records = yield* currentRouteRecords;
|
|
2606
|
+
for (const { output, streamId } of yield* records.list(bound)) {
|
|
2607
|
+
const definition = routes.get(output);
|
|
2608
|
+
const results = routed.get(output);
|
|
2609
|
+
const invalid = (cause) => new ProjectionFault({
|
|
2610
|
+
phase: "checkpoint",
|
|
2611
|
+
reason: "invalid-record",
|
|
2612
|
+
message: `Cannot restore routed output ${output} at ${streamId}`,
|
|
2613
|
+
cause
|
|
2614
|
+
});
|
|
2615
|
+
const address = yield* Effect.try({
|
|
2616
|
+
try: () => definition?.restore(streamId),
|
|
2617
|
+
catch: invalid
|
|
2618
|
+
});
|
|
2619
|
+
if (address === void 0 || results === void 0) return yield* invalid();
|
|
2620
|
+
results.push(yield* clean(address, Context.get(context, address.stream)));
|
|
2621
|
+
}
|
|
2622
|
+
if (mode === "remove") yield* records.clear(bound);
|
|
2623
|
+
}
|
|
2624
|
+
return yield* Effect.void;
|
|
2625
|
+
})
|
|
2626
|
+
}),
|
|
2627
|
+
outputs: Record.fromEntries(outputs)
|
|
2628
|
+
};
|
|
2629
|
+
return routes === void 0 ? retired : {
|
|
2630
|
+
...retired,
|
|
2631
|
+
routed: Record.fromEntries(routed)
|
|
2632
|
+
};
|
|
2633
|
+
});
|
|
2634
|
+
};
|
|
2079
2635
|
// src/wake.ts
|
|
2080
2636
|
const row = (stream, offset, closed) => DurableState.upsert("stream", closed ? {
|
|
2081
2637
|
stream,
|
|
@@ -2129,7 +2685,11 @@ function wake(definition) {
|
|
|
2129
2685
|
var projection_exports = /* @__PURE__ */ __exportAll({
|
|
2130
2686
|
Registry: () => Registry,
|
|
2131
2687
|
RunnerEvent: () => RunnerEvent,
|
|
2688
|
+
Tails: () => Tails,
|
|
2132
2689
|
attach: () => attach$1,
|
|
2690
|
+
bindings: () => bindings,
|
|
2691
|
+
caughtUp: () => caughtUp,
|
|
2692
|
+
createOutputs: () => createOutputs,
|
|
2133
2693
|
current: () => current,
|
|
2134
2694
|
decide: () => decide,
|
|
2135
2695
|
each: () => each,
|
|
@@ -2137,14 +2697,20 @@ var projection_exports = /* @__PURE__ */ __exportAll({
|
|
|
2137
2697
|
fold: () => fold,
|
|
2138
2698
|
follow: () => follow,
|
|
2139
2699
|
forget: () => forget,
|
|
2700
|
+
generationBinding: () => generationBinding,
|
|
2701
|
+
isPerGeneration: () => isPerGeneration,
|
|
2140
2702
|
items: () => items,
|
|
2141
2703
|
key: () => key,
|
|
2704
|
+
lag: () => lag,
|
|
2142
2705
|
mapAccum: () => mapAccum,
|
|
2143
2706
|
mapAccumBatch: () => mapAccumBatch,
|
|
2144
2707
|
pass: () => pass,
|
|
2708
|
+
perGeneration: () => perGeneration,
|
|
2145
2709
|
process: () => process$1,
|
|
2146
2710
|
read: () => read,
|
|
2711
|
+
retire: () => retire,
|
|
2147
2712
|
run: () => run,
|
|
2713
|
+
tails: () => tails,
|
|
2148
2714
|
wake: () => wake,
|
|
2149
2715
|
wakeAt: () => wakeAt
|
|
2150
2716
|
});
|
|
@@ -2221,6 +2787,7 @@ const storedValues = Effect.fn("StateTable.storedValues")(function* (sql, id, co
|
|
|
2221
2787
|
});
|
|
2222
2788
|
// src/state-table.ts
|
|
2223
2789
|
var state_table_exports = /* @__PURE__ */ __exportAll({
|
|
2790
|
+
clear: () => clear,
|
|
2224
2791
|
define: () => define,
|
|
2225
2792
|
migrate: () => migrate,
|
|
2226
2793
|
rebuild: () => rebuild,
|
|
@@ -2419,38 +2986,44 @@ const reads = (id, collections) => {
|
|
|
2419
2986
|
/** A State stream's declaration, kept current by the ordinary projection runners. */
|
|
2420
2987
|
function define(state, options = {}) {
|
|
2421
2988
|
validateAccepted(options.accepted, state.paramCodecs, [state.template], transaction);
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2989
|
+
const declaration = declare({
|
|
2990
|
+
id: `state-table/${state.key}`,
|
|
2991
|
+
params: state.paramCodecs,
|
|
2992
|
+
inputs: {}
|
|
2993
|
+
}, ({ decoded, ...key }) => {
|
|
2994
|
+
const address = state.at(decoded);
|
|
2995
|
+
const raw = Object.assign(StreamAddress.json(address.id, { schema: Schema.String }), {
|
|
2996
|
+
stream: address.stream,
|
|
2997
|
+
codec: Schema.String
|
|
2998
|
+
});
|
|
2999
|
+
const accepted = options.accepted?.at(decoded);
|
|
3000
|
+
if (accepted?.id === address.id) throw new RangeError("An accepted stream may not name an input stream");
|
|
3001
|
+
return {
|
|
3002
|
+
...key,
|
|
3003
|
+
accepted,
|
|
3004
|
+
inputs: { state: raw },
|
|
3005
|
+
commit: transaction,
|
|
3006
|
+
process: (batch) => applySlice(raw, batch.state),
|
|
3007
|
+
...reads(address.id, state.collections),
|
|
3008
|
+
sync: () => synchronize(raw)
|
|
3009
|
+
};
|
|
3010
|
+
});
|
|
3011
|
+
return Object.assign(declaration, {
|
|
2445
3012
|
inputs: { state },
|
|
2446
3013
|
parse: state.parse
|
|
2447
|
-
};
|
|
3014
|
+
});
|
|
2448
3015
|
}
|
|
3016
|
+
const clearIndex = (sql, id) => clearRows(sql, id).pipe(Effect.andThen(sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`), Effect.catchTag("SqlError", sqlFault(id)), Effect.asVoid);
|
|
3017
|
+
/** Delete cached rows and their applied offset, even if the State stream has been removed. */
|
|
3018
|
+
const clear = Effect.fn("StateTable.clear")(function* (table) {
|
|
3019
|
+
const tx = yield* Transaction;
|
|
3020
|
+
yield* tx.withTransaction(clearIndex(tx.sql, table.inputs.state.id));
|
|
3021
|
+
});
|
|
2449
3022
|
/** Discard the index and replay the State stream atomically, retaining the binding checkpoint. */
|
|
2450
3023
|
const rebuild = Effect.fn("StateTable.rebuild")(function* (table) {
|
|
2451
3024
|
const tx = yield* Transaction;
|
|
2452
3025
|
const id = table.inputs.state.id;
|
|
2453
|
-
yield* tx.withTransaction(
|
|
3026
|
+
yield* tx.withTransaction(clearIndex(tx.sql, id).pipe(Effect.andThen(table.sync())));
|
|
2454
3027
|
});
|
|
2455
3028
|
/** Append a reset to the State stream. The next table run applies it. */
|
|
2456
3029
|
const reset = Effect.fn("StateTable.reset")(function* (table) {
|
|
@@ -2483,8 +3056,9 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
|
|
|
2483
3056
|
const params = table.parse(output.id);
|
|
2484
3057
|
if (collection === void 0 || Option.isNone(params)) return yield* Effect.die(/* @__PURE__ */ new RangeError(`${table.id} does not index ${spec.collection} of ${output.id}`));
|
|
2485
3058
|
const { wire } = yield* output.stream;
|
|
2486
|
-
yield*
|
|
2487
|
-
yield*
|
|
3059
|
+
const generationBound = (yield* TransactionGenerationOutputs)?.get(spec.output)?.address.id === output.id;
|
|
3060
|
+
if (!generationBound) yield* wire.create(output.id, { contentType: output.contentType }).pipe(Effect.mapError(writeFault(output.id)));
|
|
3061
|
+
yield* table.at(params.value).sync().pipe(Effect.mapError((cause) => generationBound && cause.reason === "history-unavailable" ? fault("invalid-output", `Cannot write output ${output.id}`)(cause) : cause));
|
|
2488
3062
|
const groups = /* @__PURE__ */ new Map();
|
|
2489
3063
|
for (const { item } of items(batch)) for (const record of spec.records(item, unit)) {
|
|
2490
3064
|
const key = spec.key(record, unit);
|
|
@@ -2534,6 +3108,8 @@ function process(table, spec) {
|
|
|
2534
3108
|
* request writes. Triggers must belong to this storage owner. A provided trigger
|
|
2535
3109
|
* service on another owner dies at attach with a RangeError naming its stream;
|
|
2536
3110
|
* remote trigger followers require the process host, Projection.attach.
|
|
3111
|
+
* On acquire, startup replays from the checkpoint inventory or `options.bindings`
|
|
3112
|
+
* are queued for the alarm on this object.
|
|
2537
3113
|
*
|
|
2538
3114
|
* Durable by default: each commit writes a pending mark for its bindings in
|
|
2539
3115
|
* the same transaction, so an eviction or a deploy between the commit and the
|
|
@@ -2601,4 +3177,4 @@ const attach = (projection, options = {}) => {
|
|
|
2601
3177
|
});
|
|
2602
3178
|
};
|
|
2603
3179
|
const ProjectionWakeup = { attach };
|
|
2604
|
-
export { CheckpointRecord, CheckpointStore, commit_exports as Commit, fold_by_key_exports as FoldByKey, FoldByKeyError, HandlerFailed, InvalidBinding, NotAttached, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, RunnerEvent, state_table_exports as StateTable, Transaction };
|
|
3180
|
+
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, Transaction };
|