@streamsy/projection 0.12.0 → 0.14.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 +66 -31
- package/dist/checkpoint-store-BE0zelau.js +459 -0
- package/dist/{checkpoint-store-DCfrS4Fd.d.ts → checkpoint-store-Cy5myzCL.d.ts} +42 -7
- package/dist/checkpoint.d.ts +2 -2
- package/dist/checkpoint.js +1 -1
- package/dist/index.d.ts +253 -66
- package/dist/index.js +817 -188
- package/package.json +4 -4
- package/dist/checkpoint-store--bWf1qeP.js +0 -296
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
-
import {
|
|
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";
|
|
2
|
+
import { _ as NonRetryable, c as recordKey, d as canonicalParams, f as encodeKey, g as InvalidBinding, h as withParams, i as assertCheckpointKeyVersion, l as restore, m as unitOf, n as CheckpointStore, o as loadLatest, p as terminalOf, r as advance, s as rangesOf, t as CheckpointRecord, u as unsupportedBindingList, v as NotAttached, y as ProjectionFault } from "./checkpoint-store-BE0zelau.js";
|
|
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
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";
|
|
6
6
|
import { Streams, StreamsWriter } from "@streamsy/core/protocol";
|
|
@@ -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,58 +315,221 @@ 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
|
|
374
|
-
/** The
|
|
322
|
+
/** The storage owner's transaction, used by Commit.transaction. */
|
|
375
323
|
var Transaction = class extends Context.Service()("@streamsy/projection/Transaction") {
|
|
376
|
-
/**
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
324
|
+
/** Join the commit boundary on a memory or SQL storage host. */
|
|
325
|
+
static layer = Layer.effect(this, Effect.map(CommitBoundary, (boundary) => ({
|
|
326
|
+
owner: ownerOf(boundary),
|
|
327
|
+
withTransaction: (body) => boundary.withTransaction(body).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(new ProjectionFault({
|
|
328
|
+
phase: "checkpoint",
|
|
329
|
+
reason: "storage-failure",
|
|
330
|
+
message: "The owner transaction failed",
|
|
331
|
+
cause
|
|
332
|
+
}))))
|
|
333
|
+
})));
|
|
334
|
+
};
|
|
335
|
+
// src/per-generation.ts
|
|
336
|
+
const TypeId = Symbol.for("@streamsy/projection/PerGeneration");
|
|
337
|
+
function perGeneration(route, param, options) {
|
|
338
|
+
const shared = options?.shared ?? false;
|
|
339
|
+
const routeBy = options?.routeBy;
|
|
340
|
+
return { [TypeId]: routeBy === void 0 ? {
|
|
341
|
+
route,
|
|
342
|
+
param,
|
|
343
|
+
shared
|
|
344
|
+
} : {
|
|
345
|
+
route,
|
|
346
|
+
param,
|
|
347
|
+
shared,
|
|
348
|
+
routeBy: Object.freeze([...routeBy])
|
|
349
|
+
} };
|
|
350
|
+
}
|
|
351
|
+
const isPerGeneration = (value) => TypeId in value;
|
|
352
|
+
const generationBinding = (binding) => binding[TypeId];
|
|
353
|
+
const validateGenerationParam = (output, params) => {
|
|
354
|
+
if (!isPerGeneration(output)) return;
|
|
355
|
+
const { route, param, routeBy, shared } = generationBinding(output);
|
|
356
|
+
if (Record.has(params, param)) throw new RangeError(`Generation-bound parameter ${param} must not be a projection parameter`);
|
|
357
|
+
if (routeBy === void 0) return;
|
|
358
|
+
if (shared) throw new RangeError("Routed outputs cannot be shared");
|
|
359
|
+
if (routeBy.length === 0 || new Set(routeBy).size !== routeBy.length) throw new RangeError("routeBy requires one or more distinct route parameters");
|
|
360
|
+
const names = Array.filterMap(route.template.split("/"), (part) => part.startsWith(":") ? Result.succeed(part.slice(1)) : Result.fail(void 0));
|
|
361
|
+
for (const name of routeBy) {
|
|
362
|
+
if (!names.includes(name)) throw new RangeError(`Routed parameter ${name} must be a route parameter`);
|
|
363
|
+
if (name === param || Record.has(params, name)) throw new RangeError(`Routed parameter ${name} must not be a generation or projection parameter`);
|
|
364
|
+
}
|
|
365
|
+
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`);
|
|
394
366
|
};
|
|
367
|
+
/** Private metadata on the bound value. */
|
|
368
|
+
const GenerationOutputs = Symbol.for("@streamsy/projection/internal/GenerationOutputs");
|
|
369
|
+
/** Outputs whose creation is managed by the current transaction. */
|
|
370
|
+
const TransactionGenerationOutputs = Context.Reference("@streamsy/projection/internal/TransactionGenerationOutputs", { defaultValue: () => void 0 });
|
|
371
|
+
// src/routed-outputs.ts
|
|
372
|
+
const RoutedOutputs = Symbol.for("@streamsy/projection/internal/RoutedOutputs");
|
|
373
|
+
const processFault = (reason, message, cause) => new ProjectionFault({
|
|
374
|
+
phase: "process",
|
|
375
|
+
reason,
|
|
376
|
+
message,
|
|
377
|
+
cause
|
|
378
|
+
});
|
|
379
|
+
const requireRouteRecords = (store, phase) => store?.routes === void 0 ? Effect.fail(new ProjectionFault({
|
|
380
|
+
phase,
|
|
381
|
+
reason: "unsupported-composition",
|
|
382
|
+
message: "This CheckpointStore does not support routed outputs"
|
|
383
|
+
})) : Effect.succeed(store.routes);
|
|
384
|
+
const currentRouteRecords = Effect.serviceOption(CheckpointStore).pipe(Effect.flatMap((store) => requireRouteRecords(Option.getOrUndefined(store), "checkpoint")));
|
|
385
|
+
const routedUnit = (key, store) => ({
|
|
386
|
+
key: recordKey(key),
|
|
387
|
+
store,
|
|
388
|
+
opened: /* @__PURE__ */ new Map(),
|
|
389
|
+
lock: Semaphore.makeUnsafe(1)
|
|
390
|
+
});
|
|
391
|
+
const TransactionRoutedOutputs = Context.Reference("@streamsy/projection/internal/TransactionRoutedOutputs", { defaultValue: () => void 0 });
|
|
392
|
+
const routedDefinition = (route) => ({
|
|
393
|
+
matches: route.match,
|
|
394
|
+
restore: (id) => {
|
|
395
|
+
const parsed = route.parse(id);
|
|
396
|
+
if (Option.isNone(parsed)) return void 0;
|
|
397
|
+
const address = route.at(parsed.value);
|
|
398
|
+
return address.id === id ? address : void 0;
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
const routedHandle = (name, route, names, params, key, occupied, routed) => ({ open: (values) => Effect.gen(function* () {
|
|
402
|
+
const unit = yield* TransactionRoutedOutputs;
|
|
403
|
+
if (unit === void 0 || unit.key !== recordKey(key)) return yield* processFault("unsupported-composition", `Routed output ${name} requires its binding's process transaction`);
|
|
404
|
+
const address = yield* Effect.try({
|
|
405
|
+
try: () => {
|
|
406
|
+
if (Record.keys(values).length !== names.length || !Array.every(names, (param) => Record.has(values, param))) throw new RangeError(`Expected route parameters ${Array.join(names, ", ")}`);
|
|
407
|
+
return route.at({
|
|
408
|
+
...params,
|
|
409
|
+
...values
|
|
410
|
+
});
|
|
411
|
+
},
|
|
412
|
+
catch: (cause) => processFault("invalid-output", `Cannot resolve routed output ${name}: ${cause instanceof RangeError ? cause.message : String(cause)}`, cause)
|
|
413
|
+
});
|
|
414
|
+
if (occupied.has(address.id)) return yield* processFault("invalid-output", `Routed output ${name} overlaps an input or output at ${address.id}`);
|
|
415
|
+
if (!Predicate.isTagged(address, "Json")) return yield* processFault("invalid-output", "Projection outputs require JSON or state routes");
|
|
416
|
+
const service = yield* address.stream;
|
|
417
|
+
const owner = yield* CurrentOwner;
|
|
418
|
+
if (service.owner !== owner) return yield* processFault("unsupported-composition", `Output ${address.id} does not share the transaction owner`);
|
|
419
|
+
return yield* unit.lock.withPermits(1)(Effect.gen(function* () {
|
|
420
|
+
const opened = unit.opened.get(address.id);
|
|
421
|
+
if (opened === name) return address;
|
|
422
|
+
if (opened !== void 0) return yield* processFault("invalid-output", `Routed outputs ${opened} and ${name} both name ${address.id}`);
|
|
423
|
+
const records = yield* requireRouteRecords(unit.store, "process");
|
|
424
|
+
if ((yield* records.state(key, name, address.id)) !== "live") {
|
|
425
|
+
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}`);
|
|
426
|
+
const created = yield* createOutput(address, service.wire);
|
|
427
|
+
if (created.closed || created.nextOffset !== ZERO_OFFSET) return yield* processFault("invalid-output", `Generation-bound output ${address.id} must start empty and open`);
|
|
428
|
+
yield* records.add(key, name, address.id);
|
|
429
|
+
}
|
|
430
|
+
unit.opened.set(address.id, name);
|
|
431
|
+
return address;
|
|
432
|
+
}));
|
|
433
|
+
}) });
|
|
395
434
|
// src/commit/transaction.ts
|
|
396
|
-
const
|
|
435
|
+
const checkpointOwnerFault = (key) => new ProjectionFault({
|
|
436
|
+
phase: "checkpoint",
|
|
437
|
+
reason: "unsupported-composition",
|
|
438
|
+
message: `The checkpoint store for ${key.id} does not share the transaction owner`
|
|
439
|
+
});
|
|
440
|
+
/** Run the body for the owner, and fail when it writes to a stream on another owner. */
|
|
441
|
+
const withOwner = (tx, phase) => (body) => body.pipe(Effect.provideService(CurrentOwner, tx.owner), Effect.catchDefect((defect) => isForeignOwner(defect) ? Effect.fail(new ProjectionFault({
|
|
442
|
+
phase,
|
|
443
|
+
reason: "unsupported-composition",
|
|
444
|
+
message: defect.message
|
|
445
|
+
})) : Effect.die(defect)));
|
|
446
|
+
const checkpointState = (loaded) => loaded.pipe(Effect.map(({ record }) => Option.isSome(record) ? "present" : "absent"), Effect.catchIf((fault) => fault.reason === "retired-generation", () => Effect.succeed("retired")), Effect.catchIf((fault) => fault.reason === "invalid-record", () => Effect.succeed("present")), Effect.mapError(({ reason, message, cause }) => new ProjectionFault({
|
|
447
|
+
phase: "checkpoint",
|
|
448
|
+
reason,
|
|
449
|
+
message,
|
|
450
|
+
cause
|
|
451
|
+
})));
|
|
452
|
+
const removeWithRoutes = (store, key, checkpoint) => Effect.gen(function* () {
|
|
453
|
+
const records = yield* requireRouteRecords(store, "checkpoint");
|
|
454
|
+
if (checkpoint === "absent") yield* records.forget(key, { ignoreUnsupportedList: true });
|
|
455
|
+
else if (checkpoint === "present") {
|
|
456
|
+
yield* records.forget(key);
|
|
457
|
+
yield* store.remove(key);
|
|
458
|
+
}
|
|
459
|
+
return yield* Effect.void;
|
|
460
|
+
});
|
|
461
|
+
const retireInTransaction = (tx, request) => Effect.gen(function* () {
|
|
462
|
+
const store = yield* CheckpointStore;
|
|
463
|
+
if (ownerOf(store.load) !== tx.owner) return yield* checkpointOwnerFault(request.key);
|
|
464
|
+
return yield* tx.withTransaction(retire$1(request).pipe(withOwner(tx, "checkpoint")));
|
|
465
|
+
});
|
|
466
|
+
const TransactionCommitTypeId = Symbol("@streamsy/projection/TransactionCommit");
|
|
467
|
+
const removeInTransaction = (tx, key, cleanup) => tx.withTransaction(Effect.gen(function* () {
|
|
468
|
+
const store = yield* CheckpointStore;
|
|
469
|
+
if (ownerOf(store.load) !== tx.owner) return yield* checkpointOwnerFault(key);
|
|
470
|
+
const checkpoint = yield* checkpointState(store.load(key));
|
|
471
|
+
if (RoutedOutputs in key) yield* removeWithRoutes(store, key, checkpoint);
|
|
472
|
+
else yield* store.remove(key);
|
|
473
|
+
yield* cleanup.pipe(withOwner(tx, "checkpoint"));
|
|
474
|
+
if ((yield* checkpointState(checkpoint === "absent" ? loadLatest(store, key) : store.load(key))) !== (checkpoint === "retired" ? "retired" : "absent")) return yield* new ProjectionFault({
|
|
475
|
+
phase: "checkpoint",
|
|
476
|
+
reason: "token-conflict",
|
|
477
|
+
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.`
|
|
478
|
+
});
|
|
479
|
+
return yield* Effect.void;
|
|
480
|
+
}));
|
|
481
|
+
/**
|
|
482
|
+
* Commit the unit and checkpoint together on a memory or SQL storage host.
|
|
483
|
+
* A SqlClient used by the handler must be the storage owner's client for its
|
|
484
|
+
* statements to join the transaction.
|
|
485
|
+
*
|
|
486
|
+
* On the same client the unit joins the outer transaction without a savepoint.
|
|
487
|
+
* With two boundaries over one client, only the outer boundary's hooks and
|
|
488
|
+
* `committed` subscribers see the commit.
|
|
489
|
+
*
|
|
490
|
+
* On another SQL client the unit opens its own transaction. It commits first and
|
|
491
|
+
* survives an outer rollback. Use one client per database for nested work. With
|
|
492
|
+
* two clients on one database, SQLite can wait until it reports a busy lock.
|
|
493
|
+
* Postgres or MySQL can wait for a row lock that the outer transaction holds.
|
|
494
|
+
*
|
|
495
|
+
* Durable Object clients share the driver's transaction, so a second client
|
|
496
|
+
* joins the first. Using a second object's storage on one fiber is unsupported.
|
|
497
|
+
*/
|
|
498
|
+
const transaction = Object.assign(withPrepare(make$1({
|
|
397
499
|
name: "transaction",
|
|
398
500
|
guarantee: "exactly-once",
|
|
399
501
|
load,
|
|
400
|
-
remove:
|
|
502
|
+
remove: (key) => Transaction.use((tx) => removeInTransaction(tx, key, Effect.void)),
|
|
503
|
+
retire: (request) => Transaction.use((tx) => retireInTransaction(tx, request)),
|
|
401
504
|
apply: (pending) => Effect.gen(function* () {
|
|
402
505
|
const tx = yield* Transaction;
|
|
403
506
|
const store = yield* CheckpointStore;
|
|
404
|
-
const outputs = detailsOf(pending)
|
|
507
|
+
const { outputs, prepare } = detailsOf(pending);
|
|
508
|
+
const hasRoutes = RoutedOutputs in pending.key;
|
|
405
509
|
for (const { address, service } of Record.values(outputs)) if (service.owner !== tx.owner) return yield* new ProjectionFault({
|
|
406
510
|
phase: "load",
|
|
407
511
|
reason: "unsupported-composition",
|
|
408
512
|
message: `Output ${address.id} does not share the transaction owner`
|
|
409
513
|
});
|
|
410
|
-
|
|
514
|
+
if (ownerOf(store.load) !== tx.owner) return yield* checkpointOwnerFault(pending.key);
|
|
411
515
|
if (prepare !== void 0) yield* prepare;
|
|
412
516
|
yield* tx.withTransaction(Effect.gen(function* () {
|
|
413
|
-
|
|
517
|
+
const again = yield* store.load(pending.key);
|
|
518
|
+
if (again.token !== pending.loaded.token) return yield* new ProjectionFault({
|
|
414
519
|
phase: "checkpoint",
|
|
415
520
|
reason: "token-conflict",
|
|
416
521
|
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
522
|
});
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
523
|
+
if (Option.isNone(again.record)) for (const { address, service, generation } of Record.values(outputs)) {
|
|
524
|
+
if (generation === void 0) continue;
|
|
525
|
+
const created = yield* createOutput(address, service.wire);
|
|
526
|
+
if (!generation.shared && (created.closed || created.nextOffset !== ZERO_OFFSET)) return yield* new ProjectionFault({
|
|
527
|
+
phase: "process",
|
|
528
|
+
reason: "invalid-output",
|
|
529
|
+
message: `Generation-bound output ${address.id} must start empty and open`
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
const result = yield* pending.run.pipe(withOwner(tx, "process"), Effect.provideService(TransactionGenerationOutputs, pending.generationOutputs), Effect.provideService(TransactionRoutedOutputs, hasRoutes ? routedUnit(pending.key, store) : void 0));
|
|
423
533
|
if (result !== void 0 && "outputs" in result) for (const [name, output] of Record.toEntries(result.outputs)) {
|
|
424
534
|
if (!Array.isReadonlyArrayNonEmpty(output.items)) continue;
|
|
425
535
|
const resolved = outputs[name];
|
|
@@ -440,19 +550,32 @@ const transaction = withPrepare(make$1({
|
|
|
440
550
|
}));
|
|
441
551
|
return yield* Effect.void;
|
|
442
552
|
})
|
|
443
|
-
})).pipe(withAccepted);
|
|
553
|
+
})).pipe(withAccepted), { [TransactionCommitTypeId]: true });
|
|
554
|
+
/**
|
|
555
|
+
* Clean up binding state in the owner's transaction on forget and retire.
|
|
556
|
+
* The boundary follows the same nesting rules as {@link transaction}.
|
|
557
|
+
*/
|
|
558
|
+
const transactionWithCleanup = (cleanup) => inherit(transaction, {
|
|
559
|
+
...transaction,
|
|
560
|
+
remove: (key) => Transaction.use((tx) => removeInTransaction(tx, key, Effect.suspend(() => cleanup(key)))),
|
|
561
|
+
retire: (request) => Transaction.use((tx) => retireInTransaction(tx, {
|
|
562
|
+
...request,
|
|
563
|
+
cleanup: request.cleanup.pipe(Effect.andThen(() => cleanup(request.key)))
|
|
564
|
+
}))
|
|
565
|
+
});
|
|
444
566
|
// src/commit/producer.ts
|
|
567
|
+
const PRODUCER_ID_SUFFIX = "/v1";
|
|
445
568
|
/**
|
|
446
569
|
* The pinned tuple identity: the params join the id so two parameterisations never share a sequence.
|
|
447
570
|
* An id within the storage limit is used as it is, because outputs already hold producer state under it.
|
|
448
|
-
* A longer id becomes `<id>/
|
|
571
|
+
* A longer id becomes `<id>/v1/#<sha256 of the full id>`. A long projection id is cut by
|
|
449
572
|
* code point so the result is at most the limit.
|
|
450
573
|
*/
|
|
451
|
-
const producerId = (id,
|
|
574
|
+
const producerId = (id, params) => fitKey(`${id}${PRODUCER_ID_SUFFIX}${Record.keys(params).length === 0 ? "" : `/${canonicalParams(params)}`}`, MAX_PRODUCER_ID_LENGTH, `${id}${PRODUCER_ID_SUFFIX}/`);
|
|
452
575
|
/** The head of one output. A missing output on the checkpoint's owner is created here. */
|
|
453
|
-
const prepareOutput = (output, store) => {
|
|
576
|
+
const prepareOutput = (output, store, beforeCreate) => {
|
|
454
577
|
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)
|
|
578
|
+
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
579
|
phase: "pin",
|
|
457
580
|
reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
458
581
|
message: `Cannot prepare output ${output.address.id}`,
|
|
@@ -465,10 +588,11 @@ const asPin = (fault) => fault.phase === "checkpoint" && fault.reason === "token
|
|
|
465
588
|
reason: fault.reason,
|
|
466
589
|
message: fault.message
|
|
467
590
|
}) : fault;
|
|
468
|
-
const producer = pin(make$1({
|
|
591
|
+
const producer = pin$1(make$1({
|
|
469
592
|
name: "producer",
|
|
470
593
|
guarantee: "effectively-once",
|
|
471
594
|
remove: remove$1,
|
|
595
|
+
retire: retire$1,
|
|
472
596
|
load: (key) => Effect.gen(function* () {
|
|
473
597
|
const loaded = yield* load(key);
|
|
474
598
|
if (Option.isSome(loaded.record)) {
|
|
@@ -518,13 +642,27 @@ const producer = pin(make$1({
|
|
|
518
642
|
}
|
|
519
643
|
let token = before.token;
|
|
520
644
|
if (pending === void 0 && Record.keys(seqs).length > 0) {
|
|
645
|
+
const checkBeforeCreate = Effect.gen(function* () {
|
|
646
|
+
if ((yield* owner.load(projection)).token !== before.token) return yield* new ProjectionFault({
|
|
647
|
+
phase: "pin",
|
|
648
|
+
reason: "token-conflict",
|
|
649
|
+
message: `Record for ${projection.id} changed before creating an output`
|
|
650
|
+
});
|
|
651
|
+
return yield* Effect.void;
|
|
652
|
+
});
|
|
521
653
|
for (const [name, output] of Record.toEntries(streams)) {
|
|
522
654
|
if (seqs[name] === void 0) continue;
|
|
523
|
-
|
|
655
|
+
const head = yield* prepareOutput(output, owner, output.generation === void 0 ? Effect.void : checkBeforeCreate);
|
|
656
|
+
if (head.closed) return yield* new ProjectionFault({
|
|
524
657
|
phase: "pin",
|
|
525
658
|
reason: "invalid-output",
|
|
526
659
|
message: `Output ${output.address.id} is closed`
|
|
527
660
|
});
|
|
661
|
+
if (output.generation?.shared === false && positions[name] === void 0 && head.nextOffset !== ZERO_OFFSET) return yield* new ProjectionFault({
|
|
662
|
+
phase: "pin",
|
|
663
|
+
reason: "invalid-output",
|
|
664
|
+
message: `Generation-bound output ${output.address.id} must start empty and open`
|
|
665
|
+
});
|
|
528
666
|
positions[name] = positions[name] ?? {
|
|
529
667
|
epoch: projection.generation,
|
|
530
668
|
nextSeq: 0
|
|
@@ -543,7 +681,7 @@ const producer = pin(make$1({
|
|
|
543
681
|
if (before.record.state !== void 0) Object.assign(pinned, { state: before.record.state });
|
|
544
682
|
token = yield* owner.compareAndSet(projection, before.token, pinned).pipe(Effect.mapError(asPin));
|
|
545
683
|
}
|
|
546
|
-
const appendAs = yield* producerId(projection.id, projection.
|
|
684
|
+
const appendAs = yield* producerId(projection.id, projection.params);
|
|
547
685
|
for (const [name, output] of Record.toEntries(streams)) {
|
|
548
686
|
const seq = seqs[name];
|
|
549
687
|
const items = processed.items[name] ?? [];
|
|
@@ -571,11 +709,12 @@ const producer = pin(make$1({
|
|
|
571
709
|
})
|
|
572
710
|
})).pipe(withAccepted);
|
|
573
711
|
// src/commit/at-least-once.ts
|
|
574
|
-
const atLeastOnce = pin(make$1({
|
|
712
|
+
const atLeastOnce = pin$1(make$1({
|
|
575
713
|
name: "atLeastOnce",
|
|
576
714
|
guarantee: "at-least-once",
|
|
577
715
|
load,
|
|
578
716
|
remove: remove$1,
|
|
717
|
+
retire: retire$1,
|
|
579
718
|
apply: (pending) => Effect.gen(function* () {
|
|
580
719
|
const store = yield* CheckpointStore;
|
|
581
720
|
const before = beforeRecord(pending);
|
|
@@ -612,24 +751,32 @@ var commit_exports = /* @__PURE__ */ __exportAll({
|
|
|
612
751
|
Emitted: () => Emitted,
|
|
613
752
|
Folded: () => Folded,
|
|
614
753
|
HandlerFailed: () => HandlerFailed,
|
|
615
|
-
TypeId: () => TypeId,
|
|
754
|
+
TypeId: () => TypeId$1,
|
|
616
755
|
atLeastOnce: () => atLeastOnce,
|
|
617
756
|
checkpoint: () => checkpoint,
|
|
618
757
|
make: () => make$1,
|
|
619
758
|
producer: () => producer,
|
|
620
759
|
transaction: () => transaction,
|
|
760
|
+
transactionWithCleanup: () => transactionWithCleanup,
|
|
621
761
|
withCompensation: () => withCompensation
|
|
622
762
|
});
|
|
623
763
|
// src/accepted.ts
|
|
624
764
|
/** Private output name, stable across producer retries. */
|
|
625
765
|
const acceptedKey = "@streamsy/accepted";
|
|
626
|
-
const validateAccepted = (
|
|
627
|
-
if (
|
|
766
|
+
const validateAccepted = (output, params, inputTemplates, commit, outputNames = []) => {
|
|
767
|
+
if (output === void 0) return;
|
|
628
768
|
if (!supportsAccepted(commit)) throw new RangeError("accepted requires Commit.transaction or Commit.producer");
|
|
769
|
+
validateGenerationParam(output, params);
|
|
770
|
+
const { route: accepted, param, routeBy } = isPerGeneration(output) ? generationBinding(output) : {
|
|
771
|
+
route: output,
|
|
772
|
+
param: void 0,
|
|
773
|
+
routeBy: void 0
|
|
774
|
+
};
|
|
775
|
+
if (routeBy !== void 0) throw new RangeError("accepted does not support routed outputs");
|
|
629
776
|
if (accepted.collections !== Streamsy.wakeCollections) {
|
|
630
777
|
if (accepted.collections.stream?.schema !== Streamsy.WakeRow || accepted.collections.stream.key !== "stream") throw new RangeError("accepted requires a wake stream declaration");
|
|
631
778
|
}
|
|
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`);
|
|
779
|
+
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
780
|
for (const template of inputTemplates) if (template === accepted.template) throw new RangeError("An accepted stream may not name an input stream");
|
|
634
781
|
if (Array.contains(outputNames, "@streamsy/accepted")) throw new RangeError(`Output name ${acceptedKey} is reserved for accepted`);
|
|
635
782
|
};
|
|
@@ -678,6 +825,122 @@ const acceptedResult = (result, output) => {
|
|
|
678
825
|
wakeAt: result.wakeAt
|
|
679
826
|
} : emitted;
|
|
680
827
|
};
|
|
828
|
+
// src/outputs.ts
|
|
829
|
+
const resolveOutputs = (outputs, acceptedOutput, params, key, inputs) => {
|
|
830
|
+
const generationOutputs = /* @__PURE__ */ new Map();
|
|
831
|
+
const resolve = (name, output) => {
|
|
832
|
+
if (isPerGeneration(output)) {
|
|
833
|
+
const { route, param, shared } = generationBinding(output);
|
|
834
|
+
generationOutputs.set(name, { shared });
|
|
835
|
+
return route.at({
|
|
836
|
+
...params,
|
|
837
|
+
[param]: key.generation
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
return isDeclaration(output) ? output.at(params) : output;
|
|
841
|
+
};
|
|
842
|
+
const routed = /* @__PURE__ */ new Map();
|
|
843
|
+
const streams = Record.fromEntries(Array.flatMap(Record.toEntries(outputs), ([name, output]) => {
|
|
844
|
+
if (isPerGeneration(output) && generationBinding(output).routeBy !== void 0) {
|
|
845
|
+
routed.set(name, routedDefinition(generationBinding(output).route));
|
|
846
|
+
return [];
|
|
847
|
+
}
|
|
848
|
+
return [[name, resolve(name, output)]];
|
|
849
|
+
}));
|
|
850
|
+
const accepted = acceptedOutput === void 0 ? void 0 : resolve(acceptedKey, acceptedOutput);
|
|
851
|
+
const addresses = accepted === void 0 ? Record.values(streams) : [...Record.values(streams), accepted];
|
|
852
|
+
const ids = Array.map(addresses, (address) => address.id);
|
|
853
|
+
if (new Set(ids).size !== ids.length) throw new RangeError("Two outputs may not name the same stream");
|
|
854
|
+
const inputIds = new Set(Array.map(Record.values(inputs), (address) => address.id));
|
|
855
|
+
if (Array.some(ids, (id) => inputIds.has(id))) throw new RangeError("An output may not name an input stream");
|
|
856
|
+
if (Array.some(addresses, (address) => !Predicate.isTagged(address, "Json"))) throw new RangeError("Projection outputs require JSON or state routes");
|
|
857
|
+
const occupied = /* @__PURE__ */ new Set([...inputIds, ...ids]);
|
|
858
|
+
const handles = Record.fromEntries(Array.flatMap(Record.toEntries(outputs), ([name, output]) => {
|
|
859
|
+
if (!isPerGeneration(output)) return [];
|
|
860
|
+
const { route, param, routeBy } = generationBinding(output);
|
|
861
|
+
return routeBy === void 0 ? [] : [[name, routedHandle(name, route, routeBy, {
|
|
862
|
+
...params,
|
|
863
|
+
[param]: key.generation
|
|
864
|
+
}, key, occupied, routed)]];
|
|
865
|
+
}));
|
|
866
|
+
return {
|
|
867
|
+
streams,
|
|
868
|
+
accepted,
|
|
869
|
+
generationOutputs,
|
|
870
|
+
routed,
|
|
871
|
+
handlerOutputs: routed.size === 0 ? streams : {
|
|
872
|
+
...streams,
|
|
873
|
+
...handles
|
|
874
|
+
}
|
|
875
|
+
};
|
|
876
|
+
};
|
|
877
|
+
const createOutput = (address, wire) => Streams.create(address).pipe(Effect.provideService(StreamsWriter, wire), Effect.mapError((cause) => new ProjectionFault({
|
|
878
|
+
phase: "process",
|
|
879
|
+
reason: isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
880
|
+
message: `Cannot create output ${address.id}`,
|
|
881
|
+
cause
|
|
882
|
+
})));
|
|
883
|
+
const boundOutputs = (bound) => bound.accepted === void 0 ? bound.streams ?? {} : {
|
|
884
|
+
...bound.streams,
|
|
885
|
+
[acceptedKey]: bound.accepted
|
|
886
|
+
};
|
|
887
|
+
/** Create the generation-bound outputs of one binding, using each output's owner. */
|
|
888
|
+
const createOutputs = (bound) => Effect.gen(function* () {
|
|
889
|
+
const bindings = bound[GenerationOutputs];
|
|
890
|
+
if (bindings === void 0) return;
|
|
891
|
+
for (const [name, address] of Record.toEntries(boundOutputs(bound))) {
|
|
892
|
+
if (!bindings.has(name)) continue;
|
|
893
|
+
const { wire } = yield* address.stream;
|
|
894
|
+
yield* createOutput(address, wire);
|
|
895
|
+
}
|
|
896
|
+
});
|
|
897
|
+
const collect = (outputs, buffers, emitted) => Effect.gen(function* () {
|
|
898
|
+
for (const [name, entries] of Record.toEntries(emitted)) {
|
|
899
|
+
const output = outputs[name];
|
|
900
|
+
if (!Record.has(outputs, name) || output === void 0 || !Array.isArray(entries)) return yield* new ProjectionFault({
|
|
901
|
+
phase: "process",
|
|
902
|
+
reason: "invalid-output",
|
|
903
|
+
message: `Invalid output array ${name}`
|
|
904
|
+
});
|
|
905
|
+
const values = yield* Effect.try({
|
|
906
|
+
try: () => "collections" in output ? DurableState.changes(output, {}, entries) : entries,
|
|
907
|
+
catch: (cause) => new ProjectionFault({
|
|
908
|
+
phase: "process",
|
|
909
|
+
reason: "invalid-output",
|
|
910
|
+
message: `Invalid row change for ${name}`,
|
|
911
|
+
cause
|
|
912
|
+
})
|
|
913
|
+
});
|
|
914
|
+
(buffers[name] ??= []).push(...values);
|
|
915
|
+
}
|
|
916
|
+
return yield* Effect.void;
|
|
917
|
+
});
|
|
918
|
+
const pin = (reason, message, cause) => new ProjectionFault({
|
|
919
|
+
phase: "pin",
|
|
920
|
+
reason,
|
|
921
|
+
message,
|
|
922
|
+
cause
|
|
923
|
+
});
|
|
924
|
+
/** Append one unit under its pinned tuple; appended and duplicate are one outcome. */
|
|
925
|
+
const appendPinned = Effect.fn("Projection.appendPinned")(function* (output, wire, items, position) {
|
|
926
|
+
return yield* Streams.append(output, items, { producer: position }).pipe(Effect.provideService(StreamsWriter, wire), Effect.catchTags({
|
|
927
|
+
EncodeFault: () => new ProjectionFault({
|
|
928
|
+
phase: "process",
|
|
929
|
+
reason: "invalid-output",
|
|
930
|
+
message: `Cannot encode output for ${output.id}`
|
|
931
|
+
}),
|
|
932
|
+
StaleEpoch: (error) => pin("stale-epoch", `Epoch ${position.producerEpoch} of ${output.id} is behind ${error.currentEpoch}`),
|
|
933
|
+
ProducerGap: (error) => pin("invalid-record", `Sequence ${error.receivedSeq} of ${output.id} does not follow ${error.expectedSeq}`),
|
|
934
|
+
NotSupported: (error) => pin("unsupported-composition", `${output.id} does not support ${error.feature}`),
|
|
935
|
+
StorageFault: (cause) => pin("storage-failure", `Cannot append to ${output.id}`, cause),
|
|
936
|
+
TransportFault: (cause) => pin("storage-failure", `Cannot append to ${output.id}`, cause),
|
|
937
|
+
StreamNotFound: () => pin("invalid-output", `Output ${output.id} does not exist`),
|
|
938
|
+
StreamGone: () => pin("invalid-output", `Output ${output.id} is gone`),
|
|
939
|
+
StreamClosed: () => pin("invalid-output", `Output ${output.id} is closed`),
|
|
940
|
+
AppendConflict: () => pin("invalid-output", `Output ${output.id} refused the append`),
|
|
941
|
+
StreamBusy: () => pin("output-busy", `Output ${output.id} is busy`)
|
|
942
|
+
}));
|
|
943
|
+
});
|
|
681
944
|
// src/state.ts
|
|
682
945
|
const bindState = (definition, params) => {
|
|
683
946
|
const initial = definition.initial;
|
|
@@ -716,10 +979,10 @@ const wakeAt = (time) => {
|
|
|
716
979
|
const isWakeAt = (value) => Predicate.isTagged(value, "WakeAt");
|
|
717
980
|
// src/step.ts
|
|
718
981
|
/** 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* () {
|
|
982
|
+
const adapt = (kind, key, state, streams, outputs, handler, batch, unit, encoded, prepared, attempt = 1) => Effect.gen(function* () {
|
|
720
983
|
if (kind === "process") return yield* Effect.map(handler(batch, unit, {
|
|
721
984
|
prepared,
|
|
722
|
-
outputs
|
|
985
|
+
outputs,
|
|
723
986
|
attempt
|
|
724
987
|
}), (result) => isWakeAt(result) ? result : void 0);
|
|
725
988
|
let value = state === void 0 ? void 0 : yield* currentState(key, state, encoded);
|
|
@@ -751,6 +1014,9 @@ const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepare
|
|
|
751
1014
|
});
|
|
752
1015
|
});
|
|
753
1016
|
// src/declaration.ts
|
|
1017
|
+
/** Internal access to the same binding at a chosen generation. */
|
|
1018
|
+
const BindGeneration = Symbol.for("@streamsy/projection/internal/BindGeneration");
|
|
1019
|
+
const bindAtGeneration = (declaration, params, generation) => declaration[BindGeneration]?.(params, generation);
|
|
754
1020
|
const isDeclaration = (input) => "at" in input;
|
|
755
1021
|
const encodeParams = (id, codecs, params) => {
|
|
756
1022
|
const values = params;
|
|
@@ -764,24 +1030,20 @@ const addressesOf = (inputs, params) => {
|
|
|
764
1030
|
return Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, input]) => [name, isDeclaration(input) ? input.at(params) : input]));
|
|
765
1031
|
};
|
|
766
1032
|
const declare = (definition, bind) => {
|
|
767
|
-
const version = definition.version ?? 1;
|
|
768
1033
|
const generation = definition.generation ?? 1;
|
|
769
|
-
|
|
1034
|
+
const atGeneration = (params, selected) => bind({
|
|
1035
|
+
id: definition.id,
|
|
1036
|
+
generation: selected,
|
|
1037
|
+
params: encodeParams(definition.id, definition.params, params),
|
|
1038
|
+
decoded: params
|
|
1039
|
+
});
|
|
1040
|
+
const declaration = {
|
|
770
1041
|
retry: definition.retry,
|
|
771
1042
|
id: definition.id,
|
|
772
|
-
version,
|
|
773
1043
|
generation,
|
|
774
1044
|
params: definition.params,
|
|
775
1045
|
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
|
-
},
|
|
1046
|
+
at: (params) => atGeneration(params, generation),
|
|
785
1047
|
parse: (id) => {
|
|
786
1048
|
for (const input of Record.values(definition.inputs)) {
|
|
787
1049
|
if (!isDeclaration(input)) continue;
|
|
@@ -791,30 +1053,44 @@ const declare = (definition, bind) => {
|
|
|
791
1053
|
return Option.none();
|
|
792
1054
|
}
|
|
793
1055
|
};
|
|
1056
|
+
return Object.defineProperty(declaration, BindGeneration, { value: atGeneration });
|
|
1057
|
+
};
|
|
1058
|
+
/** @internal Reject legacy definitions passed from JavaScript or unchecked TypeScript. */
|
|
1059
|
+
const rejectProjectionVersion = (id, definition) => {
|
|
1060
|
+
if (!("version" in definition) || definition.version === void 0) return;
|
|
1061
|
+
const advice = definition.version === 1 ? "Remove version: 1 from the declaration." : "Raise generation above every generation the projection has used.";
|
|
1062
|
+
throw new RangeError(`Projection ${id}: version was removed. ${advice}`);
|
|
794
1063
|
};
|
|
795
1064
|
const build = (kind, definition) => {
|
|
1065
|
+
rejectProjectionVersion(definition.id, definition);
|
|
796
1066
|
const commit = definition.commit ?? checkpoint;
|
|
797
|
-
|
|
1067
|
+
const outputs = definition.outputs ?? {};
|
|
1068
|
+
for (const output of Record.values(outputs)) {
|
|
1069
|
+
validateGenerationParam(output, definition.params);
|
|
1070
|
+
if (isPerGeneration(output) && generationBinding(output).routeBy !== void 0) {
|
|
1071
|
+
if (kind !== "process") throw new RangeError("Routed outputs require Projection.process");
|
|
1072
|
+
if (!supportsPrepare(commit)) throw new RangeError("Routed outputs require Commit.transaction");
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
validateAccepted(definition.accepted, definition.params, Array.map(Array.filter(Record.values(definition.inputs), isDeclaration), (input) => input.template), commit, Record.keys(outputs));
|
|
798
1076
|
if (definition.prepare !== void 0 && !supportsPrepare(commit)) throw new RangeError("prepare requires Commit.transaction");
|
|
799
1077
|
return declare(definition, ({ decoded, ...key }) => {
|
|
800
1078
|
const state = definition.state === void 0 ? void 0 : bindState(definition.state, decoded);
|
|
801
1079
|
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 {
|
|
1080
|
+
const { streams, accepted, generationOutputs, routed, handlerOutputs } = resolveOutputs(outputs, definition.accepted, decoded, key, inputs);
|
|
1081
|
+
const bound = {
|
|
809
1082
|
...key,
|
|
810
1083
|
inputs,
|
|
811
1084
|
state,
|
|
812
1085
|
streams,
|
|
813
1086
|
accepted,
|
|
814
1087
|
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)
|
|
1088
|
+
prepare: definition.prepare === void 0 ? void 0 : (batch, unit) => definition.prepare(batch, withParams(unit, decoded), { outputs: handlerOutputs }),
|
|
1089
|
+
process: (batch, unit, encoded, prepared, attempt = 1) => adapt(kind, key, state, streams, handlerOutputs, definition[kind], batch, withParams(unit, decoded), encoded, prepared, attempt)
|
|
817
1090
|
};
|
|
1091
|
+
if (generationOutputs.size > 0) Object.assign(bound, { [GenerationOutputs]: generationOutputs });
|
|
1092
|
+
if (routed.size > 0) Object.assign(bound, { [RoutedOutputs]: routed });
|
|
1093
|
+
return bound;
|
|
818
1094
|
});
|
|
819
1095
|
};
|
|
820
1096
|
// src/fold.ts
|
|
@@ -838,10 +1114,15 @@ function mapAccumBatch(definition) {
|
|
|
838
1114
|
}
|
|
839
1115
|
// src/forget.ts
|
|
840
1116
|
/**
|
|
841
|
-
* Deletes
|
|
1117
|
+
* Deletes a live checkpoint and marks its routed outputs as forgotten so retirement
|
|
1118
|
+
* can still find them. Preserves retirement tombstones. Stop the follower first,
|
|
1119
|
+
* or use a new generation.
|
|
1120
|
+
* Pass the binding from `declaration.at(params)` for a routed projection. A bare
|
|
1121
|
+
* key deletes the checkpoint and leaves the route records live.
|
|
842
1122
|
* Delete stream outputs first, because forgetting restarts their producer sequences.
|
|
843
1123
|
*/
|
|
844
1124
|
const forget = (projection) => Effect.gen(function* () {
|
|
1125
|
+
assertCheckpointKeyVersion(projection);
|
|
845
1126
|
if (projection.commit.remove === void 0) return yield* new ProjectionFault({
|
|
846
1127
|
phase: "checkpoint",
|
|
847
1128
|
reason: "unsupported-composition",
|
|
@@ -937,7 +1218,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
|
|
|
937
1218
|
}
|
|
938
1219
|
const gone = Array.some(Record.values(batch), (slice) => slice.gone === true);
|
|
939
1220
|
const ranges = pending?.ranges ?? (dueOnly ? {} : rangesOf(batch));
|
|
940
|
-
const unit = unitOf(projection.id, projection.
|
|
1221
|
+
const unit = unitOf(projection.id, projection.generation, projection.params, ranges, due);
|
|
941
1222
|
context?.unit(unit);
|
|
942
1223
|
const { pending: _pending, wakeAt: _wakeAt, ...record } = before.record;
|
|
943
1224
|
const closed = { ...record.closed };
|
|
@@ -949,16 +1230,17 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
|
|
|
949
1230
|
};
|
|
950
1231
|
if (gone) Object.assign(next, { ended: true });
|
|
951
1232
|
const outputs = {};
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
service
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
const address = projection.accepted;
|
|
958
|
-
outputs[acceptedKey] = {
|
|
1233
|
+
let generationOutputs;
|
|
1234
|
+
for (const [name, address] of Record.toEntries(boundOutputs(projection))) {
|
|
1235
|
+
const service = yield* address.stream;
|
|
1236
|
+
const generation = projection[GenerationOutputs]?.get(name);
|
|
1237
|
+
const output = {
|
|
959
1238
|
address,
|
|
960
|
-
service
|
|
1239
|
+
service,
|
|
1240
|
+
generation
|
|
961
1241
|
};
|
|
1242
|
+
outputs[name] = output;
|
|
1243
|
+
if (generation !== void 0) (generationOutputs ??= /* @__PURE__ */ new Map()).set(name, output);
|
|
962
1244
|
}
|
|
963
1245
|
let prepared;
|
|
964
1246
|
let result;
|
|
@@ -989,6 +1271,7 @@ const step = Effect.fn("Projection.pass")(function* (projection, context, allowE
|
|
|
989
1271
|
upToDate: batch[name]?.upToDate ?? false
|
|
990
1272
|
}]))
|
|
991
1273
|
});
|
|
1274
|
+
if (generationOutputs !== void 0) Object.assign(request, { generationOutputs });
|
|
992
1275
|
yield* projection.commit.apply(request).pipe(Effect.catchTag("HandlerFailed", (failure) => Effect.fail(failure.error)));
|
|
993
1276
|
const stored = withState(next, result);
|
|
994
1277
|
if (gone) yield* forget(projection);
|
|
@@ -1205,10 +1488,10 @@ var Registry = class Registry extends Context.Service()("@streamsy/projection/Re
|
|
|
1205
1488
|
const reached = (value) => value !== void 0 && compare(value, offset) >= 0;
|
|
1206
1489
|
return yield* Effect.scoped(Effect.gen(function* () {
|
|
1207
1490
|
const runner = yield* find(binding);
|
|
1208
|
-
if (runner.
|
|
1491
|
+
if (runner.generation !== binding.generation) return yield* new ProjectionFault({
|
|
1209
1492
|
phase: "load",
|
|
1210
1493
|
reason: "identity-mismatch",
|
|
1211
|
-
message: `Attached
|
|
1494
|
+
message: `Attached generation of ${binding.id} is ${runner.generation}, but the binding uses generation ${binding.generation}`
|
|
1212
1495
|
});
|
|
1213
1496
|
const pull = yield* Stream.toPull(observations);
|
|
1214
1497
|
const checkpoint = yield* read(binding);
|
|
@@ -1266,8 +1549,16 @@ const registerRunner = (registry, runner) => {
|
|
|
1266
1549
|
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
1550
|
};
|
|
1268
1551
|
// src/failure.ts
|
|
1552
|
+
const nonRetryableHandlerReason = "non-retryable-handler";
|
|
1553
|
+
const marked = (reason) => Cause.isFailReason(reason) && Predicate.hasProperty(reason.error, NonRetryable) && reason.error[NonRetryable] === true;
|
|
1554
|
+
const hasNonRetryableHandler = (cause) => Array.some(cause.reasons, marked);
|
|
1269
1555
|
/** Unknown handler errors and defects retry; only a known non-retryable fault stops work. */
|
|
1270
|
-
const retryable = (cause) => !Array.some(cause.reasons, (reason) =>
|
|
1556
|
+
const retryable = (cause) => !Array.some(cause.reasons, (reason) => {
|
|
1557
|
+
if (!Cause.isFailReason(reason)) return false;
|
|
1558
|
+
const { error } = reason;
|
|
1559
|
+
if (marked(reason)) return true;
|
|
1560
|
+
return (Schema.is(ProjectionFault)(error) || Schema.is(StorageFault)(error)) && !error.retryable;
|
|
1561
|
+
});
|
|
1271
1562
|
const runnerFailure = (cause, at) => ({
|
|
1272
1563
|
at,
|
|
1273
1564
|
retryable: retryable(cause),
|
|
@@ -1293,7 +1584,7 @@ const invalid = (id, message, cause) => new ProjectionFault({
|
|
|
1293
1584
|
cause
|
|
1294
1585
|
});
|
|
1295
1586
|
/** 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* () {
|
|
1587
|
+
const triggersOf = (projection, generation, declarations, match, marks, host = "process") => Effect.gen(function* () {
|
|
1297
1588
|
const storage = yield* Storage;
|
|
1298
1589
|
const records = yield* Effect.serviceOption(OwnerRecords);
|
|
1299
1590
|
const boundary = yield* Effect.serviceOption(CommitBoundary);
|
|
@@ -1324,6 +1615,7 @@ const triggersOf = (projection, declarations, match, marks, host = "process") =>
|
|
|
1324
1615
|
streams.set(id, encodeKey([
|
|
1325
1616
|
"streamsy.projection.trigger.v1",
|
|
1326
1617
|
projection,
|
|
1618
|
+
String(generation),
|
|
1327
1619
|
id
|
|
1328
1620
|
]));
|
|
1329
1621
|
}
|
|
@@ -1536,6 +1828,124 @@ const triggersOf = (projection, declarations, match, marks, host = "process") =>
|
|
|
1536
1828
|
}))
|
|
1537
1829
|
};
|
|
1538
1830
|
});
|
|
1831
|
+
// src/catch-up.ts
|
|
1832
|
+
const Tail = Schema.Struct({
|
|
1833
|
+
stream: StreamId,
|
|
1834
|
+
offset: Offset,
|
|
1835
|
+
closed: Schema.Boolean
|
|
1836
|
+
});
|
|
1837
|
+
/** A serializable vector of fixed source tails, keyed by input name. */
|
|
1838
|
+
const Tails = Schema.Record(Schema.String, Tail);
|
|
1839
|
+
const isOffset = Schema.is(Offset);
|
|
1840
|
+
const historyUnavailable = (input, message, cause) => new ProjectionFault({
|
|
1841
|
+
phase: "read",
|
|
1842
|
+
reason: "history-unavailable",
|
|
1843
|
+
input,
|
|
1844
|
+
message,
|
|
1845
|
+
cause
|
|
1846
|
+
});
|
|
1847
|
+
const head$1 = Effect.fn("Projection.catchUp.head")(function* (name, address) {
|
|
1848
|
+
const { wire } = yield* address.stream;
|
|
1849
|
+
const storageFailure = (cause) => new ProjectionFault({
|
|
1850
|
+
phase: "read",
|
|
1851
|
+
reason: "storage-failure",
|
|
1852
|
+
input: name,
|
|
1853
|
+
message: `Cannot read the head of ${address.id}`,
|
|
1854
|
+
cause
|
|
1855
|
+
});
|
|
1856
|
+
const result = yield* wire.head(address.id).pipe(Effect.catchTags({
|
|
1857
|
+
StreamNotFound: (cause) => historyUnavailable(name, `Input stream ${address.id} is missing`, cause),
|
|
1858
|
+
StreamGone: (cause) => historyUnavailable(name, `Input stream ${address.id} is gone`, cause),
|
|
1859
|
+
StorageFault: storageFailure,
|
|
1860
|
+
TransportFault: storageFailure
|
|
1861
|
+
}));
|
|
1862
|
+
if (!isOffset(result.nextOffset)) return yield* new ProjectionFault({
|
|
1863
|
+
phase: "read",
|
|
1864
|
+
reason: "invalid-source",
|
|
1865
|
+
input: name,
|
|
1866
|
+
message: `Head of ${address.id} has an invalid offset`
|
|
1867
|
+
});
|
|
1868
|
+
return {
|
|
1869
|
+
stream: address.id,
|
|
1870
|
+
offset: result.nextOffset,
|
|
1871
|
+
closed: result.closed
|
|
1872
|
+
};
|
|
1873
|
+
});
|
|
1874
|
+
/** Capture each resolved input head once. The vector can be reused while producers keep writing. */
|
|
1875
|
+
const tails = Effect.fn("Projection.tails")(function* (projection) {
|
|
1876
|
+
const entries = yield* Effect.forEach(inputEntries(projection.inputs), ([name, address]) => head$1(name, address).pipe(Effect.map((value) => [name, value])));
|
|
1877
|
+
return Record.fromEntries(entries);
|
|
1878
|
+
});
|
|
1879
|
+
const validateTails = Effect.fnUntraced(function* (projection, targets) {
|
|
1880
|
+
const decoded = yield* Schema.decodeEffect(Tails, {
|
|
1881
|
+
onExcessProperty: "error",
|
|
1882
|
+
reportInput: true
|
|
1883
|
+
})(targets).pipe(Effect.mapError((cause) => new ProjectionFault({
|
|
1884
|
+
phase: "load",
|
|
1885
|
+
reason: "invalid-options",
|
|
1886
|
+
message: `Invalid tails for ${projection.id}: ${cause.message}`,
|
|
1887
|
+
cause
|
|
1888
|
+
})));
|
|
1889
|
+
for (const [name, address] of inputEntries(projection.inputs)) if (decoded[name]?.stream !== address.id) return yield* new ProjectionFault({
|
|
1890
|
+
phase: "load",
|
|
1891
|
+
reason: "identity-mismatch",
|
|
1892
|
+
input: name,
|
|
1893
|
+
message: `Tail for ${name} must name stream ${address.id}`
|
|
1894
|
+
});
|
|
1895
|
+
if (Record.size(decoded) !== Record.size(projection.inputs)) return yield* new ProjectionFault({
|
|
1896
|
+
phase: "load",
|
|
1897
|
+
reason: "identity-mismatch",
|
|
1898
|
+
message: `Tail input names differ from the declaration of ${projection.id}`
|
|
1899
|
+
});
|
|
1900
|
+
return decoded;
|
|
1901
|
+
});
|
|
1902
|
+
const measure = Effect.fnUntraced(function* (projection, targets, verifyHeads) {
|
|
1903
|
+
const { record } = yield* restore(projection, projection.commit);
|
|
1904
|
+
if (record.ended) return yield* new ProjectionFault({
|
|
1905
|
+
phase: "load",
|
|
1906
|
+
reason: "history-unavailable",
|
|
1907
|
+
message: `Binding of ${projection.id} ended after an input was lost`
|
|
1908
|
+
});
|
|
1909
|
+
const entries = yield* Effect.forEach(inputEntries(projection.inputs), Effect.fnUntraced(function* ([name, address]) {
|
|
1910
|
+
const committed = record.inputs[name];
|
|
1911
|
+
const target = targets[name];
|
|
1912
|
+
if (!isOffset(committed)) return yield* new ProjectionFault({
|
|
1913
|
+
phase: "load",
|
|
1914
|
+
reason: "invalid-record",
|
|
1915
|
+
input: name,
|
|
1916
|
+
message: `Stored offset for ${name} is not a valid offset`
|
|
1917
|
+
});
|
|
1918
|
+
if (verifyHeads) {
|
|
1919
|
+
const current = yield* head$1(name, address);
|
|
1920
|
+
const order = compare(current.offset, target.offset);
|
|
1921
|
+
if (order < 0 || target.closed && (!current.closed || order !== 0)) return yield* historyUnavailable(name, `Head of ${address.id} no longer contains its tail`);
|
|
1922
|
+
}
|
|
1923
|
+
const behind = compare(committed, target.offset) < 0 || target.closed && record.closed?.[name] !== true || record.pending !== void 0 && Record.has(record.pending.ranges, name);
|
|
1924
|
+
return [name, {
|
|
1925
|
+
committed,
|
|
1926
|
+
target: target.offset,
|
|
1927
|
+
behind
|
|
1928
|
+
}];
|
|
1929
|
+
}));
|
|
1930
|
+
return {
|
|
1931
|
+
caughtUp: record.pending === void 0 && Array.every(entries, ([, input]) => !input.behind),
|
|
1932
|
+
inputs: Record.fromEntries(entries)
|
|
1933
|
+
};
|
|
1934
|
+
});
|
|
1935
|
+
/** Compare fixed source tails with one committed checkpoint, including processed closes. Checks source readiness only. */
|
|
1936
|
+
const lag = Effect.fn("Projection.lag")(function* (projection, targets) {
|
|
1937
|
+
const fixed = targets === void 0 ? yield* tails(projection) : yield* validateTails(projection, targets);
|
|
1938
|
+
return yield* measure(projection, fixed, targets !== void 0);
|
|
1939
|
+
});
|
|
1940
|
+
const pollInterval = "250 millis";
|
|
1941
|
+
/** Wait for one fixed vector of source tails. The caller controls the timeout. */
|
|
1942
|
+
const caughtUp = Effect.fn("Projection.caughtUp")(function* (projection, targets) {
|
|
1943
|
+
const fixed = targets === void 0 ? yield* tails(projection) : yield* validateTails(projection, targets);
|
|
1944
|
+
return yield* measure(projection, fixed, true).pipe(Effect.repeat({
|
|
1945
|
+
schedule: Schedule.spaced(pollInterval),
|
|
1946
|
+
while: (progress) => !progress.caughtUp
|
|
1947
|
+
}), Effect.asVoid);
|
|
1948
|
+
});
|
|
1539
1949
|
// src/runner.ts
|
|
1540
1950
|
/** Re-read wall time after a suspended host resumes, even for distant deadlines. */
|
|
1541
1951
|
const MAX_DUE_WAIT_MS = 3e4;
|
|
@@ -1595,6 +2005,26 @@ const bindingOf = (declaration, key) => Option.flatMap(Schema.decodeOption(Param
|
|
|
1595
2005
|
return Option.none();
|
|
1596
2006
|
}
|
|
1597
2007
|
});
|
|
2008
|
+
const startupInventory = Effect.fn("Projection.startupInventory")(function* (declaration) {
|
|
2009
|
+
const store = yield* Effect.serviceOption(CheckpointStore);
|
|
2010
|
+
const list = Option.getOrUndefined(store)?.list;
|
|
2011
|
+
const id = declaration.id;
|
|
2012
|
+
return yield* Effect.gen(function* () {
|
|
2013
|
+
if (list === void 0) return [];
|
|
2014
|
+
const keys = /* @__PURE__ */ new Set();
|
|
2015
|
+
const current = /* @__PURE__ */ new Set();
|
|
2016
|
+
for (const { generation, params } of yield* list(id)) (generation === declaration.generation ? current : keys).add(canonicalParams(params));
|
|
2017
|
+
if (Record.isEmptyRecord(declaration.params)) keys.add(canonicalParams({}));
|
|
2018
|
+
for (const key of current) keys.delete(key);
|
|
2019
|
+
const candidates = [];
|
|
2020
|
+
for (const key of keys) {
|
|
2021
|
+
const bound = bindingOf(declaration, key);
|
|
2022
|
+
if (Option.isSome(bound)) candidates.push(bound.value);
|
|
2023
|
+
else yield* Effect.logWarning(`Projection ${id} skipped startup params ${key}: they no longer decode`);
|
|
2024
|
+
}
|
|
2025
|
+
return candidates;
|
|
2026
|
+
}).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([]))));
|
|
2027
|
+
});
|
|
1598
2028
|
/**
|
|
1599
2029
|
* A binding that faults with `history-unavailable` on an input whose head is
|
|
1600
2030
|
* absent can never run: its source is gone, and an id never returns. With a
|
|
@@ -1618,9 +2048,8 @@ const sourceGone = (inputs, cause) => Effect.gen(function* () {
|
|
|
1618
2048
|
* that transaction. Dies when the storage layer has no marks, for example
|
|
1619
2049
|
* over remote storage.
|
|
1620
2050
|
*/
|
|
1621
|
-
const durableMarks = (projection, match) => Effect.gen(function* () {
|
|
2051
|
+
const durableMarks = (projection, match, marks) => Effect.gen(function* () {
|
|
1622
2052
|
const hooks = yield* Effect.serviceOption(CommitHooks);
|
|
1623
|
-
const marks = yield* Effect.serviceOption(ProjectionMarks);
|
|
1624
2053
|
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.`));
|
|
1625
2054
|
yield* hooks.value.beforeCommit((ids) => {
|
|
1626
2055
|
const keys = /* @__PURE__ */ new Set();
|
|
@@ -1657,6 +2086,13 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
1657
2086
|
const match = matcher(declaration);
|
|
1658
2087
|
return Effect.gen(function* () {
|
|
1659
2088
|
const storage = yield* Storage;
|
|
2089
|
+
const storedMarks = durable ? yield* Effect.serviceOption(ProjectionMarks) : Option.none();
|
|
2090
|
+
const maxIdLength = Option.getOrUndefined(storedMarks)?.maxProjectionIdLength;
|
|
2091
|
+
if (maxIdLength !== void 0 && Array.fromIterable(declaration.id).length > maxIdLength) return yield* Effect.die(new StorageFault({
|
|
2092
|
+
operation: "projection.attach",
|
|
2093
|
+
message: `MySQL projection id must be at most ${maxIdLength} characters`,
|
|
2094
|
+
retryable: false
|
|
2095
|
+
}));
|
|
1660
2096
|
const registry = yield* Effect.serviceOption(Registry);
|
|
1661
2097
|
const publish = Option.isSome(registry) ? eventPublisher(registry.value) : void 0;
|
|
1662
2098
|
const committed = yield* storage.committed;
|
|
@@ -1682,19 +2118,44 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
1682
2118
|
}, () => Effect.sync(() => {
|
|
1683
2119
|
active -= 1;
|
|
1684
2120
|
}));
|
|
1685
|
-
const marks = durable ? yield* durableMarks(declaration.id, match) : memoryProjectionMarks();
|
|
2121
|
+
const marks = durable ? yield* durableMarks(declaration.id, match, storedMarks) : memoryProjectionMarks();
|
|
1686
2122
|
let failure = Option.none();
|
|
1687
2123
|
let started = false;
|
|
1688
|
-
const
|
|
2124
|
+
const startPermit = yield* Semaphore.make(1);
|
|
2125
|
+
const prepare = Effect.fnUntraced(function* (binding) {
|
|
2126
|
+
const loaded = yield* binding.commit.load(binding);
|
|
2127
|
+
if (Option.isSome(loaded.record)) return false;
|
|
2128
|
+
if ((binding[GenerationOutputs]?.size ?? 0) > 0) {
|
|
2129
|
+
yield* tails(binding);
|
|
2130
|
+
yield* createOutputs(binding);
|
|
2131
|
+
}
|
|
2132
|
+
return true;
|
|
2133
|
+
});
|
|
2134
|
+
const seed = Effect.gen(function* () {
|
|
2135
|
+
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([]))));
|
|
2136
|
+
const byKey = new Map(Array.map(candidates, (binding) => [canonicalParams(binding.params), binding]));
|
|
2137
|
+
for (const chunk of Array.chunksOf([...byKey], SCHEDULE_CHUNK)) {
|
|
2138
|
+
const keys = [];
|
|
2139
|
+
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);
|
|
2140
|
+
if (keys.length > 0) yield* marks.mark(declaration.id, keys).pipe(Effect.mapError(storageFault("marks.mark")));
|
|
2141
|
+
}
|
|
2142
|
+
}).pipe(Effect.mapError((cause) => new StorageFault({
|
|
2143
|
+
operation: "projection.startup",
|
|
2144
|
+
message: `Cannot queue startup replay for ${declaration.id}`,
|
|
2145
|
+
retryable: retryable(Cause.fail(cause)),
|
|
2146
|
+
cause
|
|
2147
|
+
})));
|
|
2148
|
+
const start = startPermit.withPermit(Effect.gen(function* () {
|
|
1689
2149
|
if (started) return;
|
|
1690
2150
|
yield* marks.resume(declaration.id);
|
|
2151
|
+
yield* seed;
|
|
1691
2152
|
started = true;
|
|
1692
2153
|
}));
|
|
1693
2154
|
const observeFailure = (effect) => effect.pipe(Effect.catchCause((cause) => Effect.gen(function* () {
|
|
1694
2155
|
failure = Option.some(runnerFailure(cause, yield* Clock.currentTimeMillis));
|
|
1695
2156
|
return yield* Effect.failCause(cause);
|
|
1696
2157
|
})));
|
|
1697
|
-
const triggers = options.triggers === void 0 || options.triggers.length === 0 ? void 0 : yield* triggersOf(declaration.id, options.triggers, match, marks, host);
|
|
2158
|
+
const triggers = options.triggers === void 0 || options.triggers.length === 0 ? void 0 : yield* triggersOf(declaration.id, declaration.generation, options.triggers, match, marks, host);
|
|
1698
2159
|
const add = (ids) => Effect.gen(function* () {
|
|
1699
2160
|
const bindings = /* @__PURE__ */ new Map();
|
|
1700
2161
|
for (const id of ids) {
|
|
@@ -1793,10 +2254,14 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
1793
2254
|
}).pipe(Effect.catchCause((cause) => Effect.logError(`Projection ${id} binding ${key} onExhausted failed`, cause)));
|
|
1794
2255
|
}
|
|
1795
2256
|
const dueAt = Option.map(delay, (ms) => failed.at + ms);
|
|
2257
|
+
const reason = hasNonRetryableHandler(exit.cause) ? Option.some(nonRetryableHandlerReason) : failed.reason;
|
|
1796
2258
|
yield* marks.fail(id, key, {
|
|
1797
2259
|
attempts,
|
|
1798
2260
|
dueAt,
|
|
1799
|
-
failure:
|
|
2261
|
+
failure: {
|
|
2262
|
+
...failed,
|
|
2263
|
+
reason
|
|
2264
|
+
}
|
|
1800
2265
|
});
|
|
1801
2266
|
if (publish !== void 0) yield* publish(RunnerEvent.Failed({
|
|
1802
2267
|
projection: id,
|
|
@@ -1880,7 +2345,7 @@ const runnerOf = (declaration, options = {}, defaultDurable = false, host = "pro
|
|
|
1880
2345
|
attempts: row.attempts,
|
|
1881
2346
|
dueAt: row.stopped ? Option.none() : Option.some(row.dueAt),
|
|
1882
2347
|
stopped: row.stopped,
|
|
1883
|
-
exhausted: row.stopped && (row.attempts >= (declaration.retry?.maxAttempts ?? Number.POSITIVE_INFINITY) || Option.isNone(yield* bindingDelay(declaration.retry?.schedule, row.attempts))),
|
|
2348
|
+
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
2349
|
failure: row.failure
|
|
1885
2350
|
};
|
|
1886
2351
|
}));
|
|
@@ -1912,6 +2377,8 @@ var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Sche
|
|
|
1912
2377
|
* subscribes to `Storage.committed` when it is built, so build it with the
|
|
1913
2378
|
* storage layer and before the app writes. For each written id, the input's
|
|
1914
2379
|
* `parse` gives the params, and the runner runs `projection.at(params)`.
|
|
2380
|
+
* The background runner also queues startup replays from the checkpoint
|
|
2381
|
+
* inventory or `options.bindings`.
|
|
1915
2382
|
*
|
|
1916
2383
|
* Use it on long-lived hosts (Bun, Node). On a Cloudflare object, use
|
|
1917
2384
|
* `ProjectionWakeup.attach(projection)`.
|
|
@@ -1953,7 +2420,6 @@ const attach$1 = (projection, options = {}) => {
|
|
|
1953
2420
|
const registry = yield* Effect.serviceOption(Registry);
|
|
1954
2421
|
const changed = Option.isNone(registry) ? Effect.void : yield* registerRunner(registry.value, {
|
|
1955
2422
|
id: projection.id,
|
|
1956
|
-
version: projection.version,
|
|
1957
2423
|
generation: projection.generation,
|
|
1958
2424
|
schedule,
|
|
1959
2425
|
rescan,
|
|
@@ -2018,13 +2484,43 @@ const current = Effect.fn("Projection.current")(function* (projection) {
|
|
|
2018
2484
|
offsets: offsetsOf$1({ inputs: offsets })
|
|
2019
2485
|
};
|
|
2020
2486
|
const ranges = rangesOf(page.slices);
|
|
2021
|
-
const unit = unitOf(projection.id, projection.
|
|
2487
|
+
const unit = unitOf(projection.id, projection.generation, projection.params, ranges);
|
|
2022
2488
|
const result = yield* projection.process(page.slices, unit, encoded);
|
|
2023
2489
|
state = result.value;
|
|
2024
2490
|
encoded = result.encoded;
|
|
2025
2491
|
offsets = advance(offsets, ranges);
|
|
2026
2492
|
}
|
|
2027
2493
|
});
|
|
2494
|
+
// src/bindings.ts
|
|
2495
|
+
/**
|
|
2496
|
+
* Lists the decoded params of bindings with live checkpoints in the selected store.
|
|
2497
|
+
* By default it includes every generation of the declaration's id. The inventory
|
|
2498
|
+
* reads every stored version slot, even with a generation filter.
|
|
2499
|
+
* Each binding appears once, in unspecified order.
|
|
2500
|
+
*
|
|
2501
|
+
* Fails with `InvalidBinding` if live params cannot round-trip through the current
|
|
2502
|
+
* codecs. On MySQL, listing fails while the range contains a legacy hashed key
|
|
2503
|
+
* that has yet to be rewritten.
|
|
2504
|
+
*/
|
|
2505
|
+
const bindings = Effect.fn("Projection.bindings")(function* (declaration, options) {
|
|
2506
|
+
const store = yield* CheckpointStore;
|
|
2507
|
+
if (store.list === void 0) return yield* unsupportedBindingList();
|
|
2508
|
+
const schema = Schema.Struct(declaration.params);
|
|
2509
|
+
const decode = Schema.decodeUnknownEffect(schema, { onExcessProperty: "error" });
|
|
2510
|
+
const encode = Schema.encodeEffect(schema);
|
|
2511
|
+
const stored = /* @__PURE__ */ new Map();
|
|
2512
|
+
for (const { generation, params } of yield* store.list(declaration.id)) if (options?.generation === void 0 || generation === options.generation) stored.set(canonicalParams(params), params);
|
|
2513
|
+
return yield* Effect.forEach(stored.values(), (params) => Effect.gen(function* () {
|
|
2514
|
+
const invalid = () => new InvalidBinding({
|
|
2515
|
+
projection: declaration.id,
|
|
2516
|
+
params
|
|
2517
|
+
});
|
|
2518
|
+
const decoded = yield* decode(params).pipe(Effect.mapError(invalid));
|
|
2519
|
+
const encoded = yield* encode(decoded).pipe(Effect.mapError(invalid));
|
|
2520
|
+
if (canonicalParams(encoded) !== canonicalParams(params)) return yield* invalid();
|
|
2521
|
+
return decoded;
|
|
2522
|
+
}));
|
|
2523
|
+
});
|
|
2028
2524
|
// src/decide.ts
|
|
2029
2525
|
/** Up to three retries after a lost race, so at most four appends per call. */
|
|
2030
2526
|
const defaultDecideRetry = Schedule.recurs(3);
|
|
@@ -2076,6 +2572,108 @@ const retryLostRace = Effect.fnUntraced(function* (attempt, schedule) {
|
|
|
2076
2572
|
return yield* Effect.fromResult(outcome);
|
|
2077
2573
|
});
|
|
2078
2574
|
const isOffsetMismatch = (error) => Predicate.isTagged(error, "OffsetMismatch");
|
|
2575
|
+
// src/retire.ts
|
|
2576
|
+
const streamOrder = Order.make((left, right) => Order.String(left.output, right.output) || Order.String(left.id, right.id));
|
|
2577
|
+
const cleanStream = (address, wire, mode) => {
|
|
2578
|
+
const { id, contentType } = address;
|
|
2579
|
+
return (mode === "remove" ? wire.remove(id).pipe(Effect.as("removed")) : wire.append(id, {
|
|
2580
|
+
close: true,
|
|
2581
|
+
data: /* @__PURE__ */ new Uint8Array(),
|
|
2582
|
+
contentType
|
|
2583
|
+
}).pipe(Effect.as("closed"), Effect.catchTag("StreamClosed", () => Effect.succeed("closed")))).pipe(Effect.catchTags({
|
|
2584
|
+
StreamNotFound: () => Effect.succeed("absent"),
|
|
2585
|
+
StreamGone: () => Effect.succeed("absent")
|
|
2586
|
+
}), Effect.mapError((cause) => new ProjectionFault({
|
|
2587
|
+
phase: "checkpoint",
|
|
2588
|
+
reason: Predicate.isTagged(cause, "StreamBusy") ? "output-busy" : isStreamsFault(cause) ? "storage-failure" : "invalid-output",
|
|
2589
|
+
message: `Cannot ${mode} output ${id}`,
|
|
2590
|
+
cause
|
|
2591
|
+
})));
|
|
2592
|
+
};
|
|
2593
|
+
/** Retire one binding and clean up its exclusively owned generation outputs. */
|
|
2594
|
+
const retire = (declaration, params, options) => {
|
|
2595
|
+
const bound = bindAtGeneration(declaration, params, options.generation);
|
|
2596
|
+
const mode = options.streams ?? "remove";
|
|
2597
|
+
return Effect.gen(function* () {
|
|
2598
|
+
if (bound?.commit.retire === void 0) return yield* new ProjectionFault({
|
|
2599
|
+
phase: "checkpoint",
|
|
2600
|
+
reason: "unsupported-composition",
|
|
2601
|
+
message: "Retirement requires a projection declaration with a Commit that supports it"
|
|
2602
|
+
});
|
|
2603
|
+
const shared = [];
|
|
2604
|
+
const owned = [];
|
|
2605
|
+
const bindings = bound[GenerationOutputs];
|
|
2606
|
+
const routes = bound[RoutedOutputs];
|
|
2607
|
+
const context = yield* Effect.context();
|
|
2608
|
+
for (const [output, address] of Record.toEntries(boundOutputs(bound))) {
|
|
2609
|
+
const binding = bindings?.get(output);
|
|
2610
|
+
if (binding === void 0) continue;
|
|
2611
|
+
if (binding.shared) shared.push({
|
|
2612
|
+
output,
|
|
2613
|
+
id: address.id,
|
|
2614
|
+
result: "shared"
|
|
2615
|
+
});
|
|
2616
|
+
else owned.push({
|
|
2617
|
+
output,
|
|
2618
|
+
address,
|
|
2619
|
+
service: yield* address.stream
|
|
2620
|
+
});
|
|
2621
|
+
}
|
|
2622
|
+
let streams = shared;
|
|
2623
|
+
return {
|
|
2624
|
+
record: yield* bound.commit.retire({
|
|
2625
|
+
key: {
|
|
2626
|
+
id: bound.id,
|
|
2627
|
+
generation: bound.generation,
|
|
2628
|
+
params: bound.params
|
|
2629
|
+
},
|
|
2630
|
+
cleanup: Effect.gen(function* () {
|
|
2631
|
+
const owner = yield* CurrentOwner;
|
|
2632
|
+
const results = [...shared];
|
|
2633
|
+
const clean = (output, address, service) => {
|
|
2634
|
+
if (owner !== void 0 && service.owner !== owner) return Effect.fail(new ProjectionFault({
|
|
2635
|
+
phase: "checkpoint",
|
|
2636
|
+
reason: "unsupported-composition",
|
|
2637
|
+
message: `Output ${address.id} does not share the transaction owner`
|
|
2638
|
+
}));
|
|
2639
|
+
return cleanStream(address, service.wire, mode).pipe(Effect.map((result) => ({
|
|
2640
|
+
output,
|
|
2641
|
+
id: address.id,
|
|
2642
|
+
result
|
|
2643
|
+
})));
|
|
2644
|
+
};
|
|
2645
|
+
for (const { output, address, service } of owned) results.push(yield* clean(output, address, service));
|
|
2646
|
+
if (routes !== void 0) {
|
|
2647
|
+
const records = yield* currentRouteRecords;
|
|
2648
|
+
const listed = Array.map(yield* records.list(bound), ({ output, streamId }) => ({
|
|
2649
|
+
output,
|
|
2650
|
+
id: streamId
|
|
2651
|
+
}));
|
|
2652
|
+
for (const { output, id } of Array.sort(listed, streamOrder)) {
|
|
2653
|
+
const definition = routes.get(output);
|
|
2654
|
+
const invalid = (cause) => new ProjectionFault({
|
|
2655
|
+
phase: "checkpoint",
|
|
2656
|
+
reason: "invalid-record",
|
|
2657
|
+
message: `Cannot restore routed output ${output} at ${id}`,
|
|
2658
|
+
cause
|
|
2659
|
+
});
|
|
2660
|
+
const address = yield* Effect.try({
|
|
2661
|
+
try: () => definition?.restore(id),
|
|
2662
|
+
catch: invalid
|
|
2663
|
+
});
|
|
2664
|
+
if (address === void 0) return yield* invalid();
|
|
2665
|
+
results.push(yield* clean(output, address, Context.get(context, address.stream)));
|
|
2666
|
+
}
|
|
2667
|
+
if (mode === "remove") yield* records.clear(bound);
|
|
2668
|
+
}
|
|
2669
|
+
streams = results;
|
|
2670
|
+
return yield* Effect.void;
|
|
2671
|
+
})
|
|
2672
|
+
}),
|
|
2673
|
+
streams: Array.sort(streams, streamOrder)
|
|
2674
|
+
};
|
|
2675
|
+
});
|
|
2676
|
+
};
|
|
2079
2677
|
// src/wake.ts
|
|
2080
2678
|
const row = (stream, offset, closed) => DurableState.upsert("stream", closed ? {
|
|
2081
2679
|
stream,
|
|
@@ -2104,10 +2702,10 @@ const row = (stream, offset, closed) => DurableState.upsert("stream", closed ? {
|
|
|
2104
2702
|
* ```
|
|
2105
2703
|
*/
|
|
2106
2704
|
function wake(definition) {
|
|
2705
|
+
rejectProjectionVersion(definition.id, definition);
|
|
2107
2706
|
const input = definition.input;
|
|
2108
2707
|
return build("mapAccumBatch", {
|
|
2109
2708
|
id: definition.id,
|
|
2110
|
-
version: definition.version,
|
|
2111
2709
|
generation: definition.generation,
|
|
2112
2710
|
params: definition.params,
|
|
2113
2711
|
commit: producer,
|
|
@@ -2129,7 +2727,11 @@ function wake(definition) {
|
|
|
2129
2727
|
var projection_exports = /* @__PURE__ */ __exportAll({
|
|
2130
2728
|
Registry: () => Registry,
|
|
2131
2729
|
RunnerEvent: () => RunnerEvent,
|
|
2730
|
+
Tails: () => Tails,
|
|
2132
2731
|
attach: () => attach$1,
|
|
2732
|
+
bindings: () => bindings,
|
|
2733
|
+
caughtUp: () => caughtUp,
|
|
2734
|
+
createOutputs: () => createOutputs,
|
|
2133
2735
|
current: () => current,
|
|
2134
2736
|
decide: () => decide,
|
|
2135
2737
|
each: () => each,
|
|
@@ -2137,20 +2739,25 @@ var projection_exports = /* @__PURE__ */ __exportAll({
|
|
|
2137
2739
|
fold: () => fold,
|
|
2138
2740
|
follow: () => follow,
|
|
2139
2741
|
forget: () => forget,
|
|
2742
|
+
generationBinding: () => generationBinding,
|
|
2743
|
+
isPerGeneration: () => isPerGeneration,
|
|
2140
2744
|
items: () => items,
|
|
2141
2745
|
key: () => key,
|
|
2746
|
+
lag: () => lag,
|
|
2142
2747
|
mapAccum: () => mapAccum,
|
|
2143
2748
|
mapAccumBatch: () => mapAccumBatch,
|
|
2144
2749
|
pass: () => pass,
|
|
2750
|
+
perGeneration: () => perGeneration,
|
|
2145
2751
|
process: () => process$1,
|
|
2146
2752
|
read: () => read,
|
|
2753
|
+
retire: () => retire,
|
|
2147
2754
|
run: () => run,
|
|
2755
|
+
tails: () => tails,
|
|
2148
2756
|
wake: () => wake,
|
|
2149
2757
|
wakeAt: () => wakeAt
|
|
2150
2758
|
});
|
|
2151
2759
|
const key = (projection) => ({
|
|
2152
2760
|
id: projection.id,
|
|
2153
|
-
version: projection.version,
|
|
2154
2761
|
generation: projection.generation,
|
|
2155
2762
|
params: projection.params
|
|
2156
2763
|
});
|
|
@@ -2221,6 +2828,7 @@ const storedValues = Effect.fn("StateTable.storedValues")(function* (sql, id, co
|
|
|
2221
2828
|
});
|
|
2222
2829
|
// src/state-table.ts
|
|
2223
2830
|
var state_table_exports = /* @__PURE__ */ __exportAll({
|
|
2831
|
+
clear: () => clear,
|
|
2224
2832
|
define: () => define,
|
|
2225
2833
|
migrate: () => migrate,
|
|
2226
2834
|
rebuild: () => rebuild,
|
|
@@ -2245,6 +2853,16 @@ const sqlFault = (id) => (cause) => new ProjectionFault({
|
|
|
2245
2853
|
message: `Cannot update the rows of ${id}`,
|
|
2246
2854
|
cause
|
|
2247
2855
|
});
|
|
2856
|
+
/** Statements of a client without an open transaction would outlive a rolled-back unit. */
|
|
2857
|
+
const transactionClient = (id) => Effect.gen(function* () {
|
|
2858
|
+
const sql = yield* SqlClient.SqlClient;
|
|
2859
|
+
if (Option.isNone(yield* Effect.serviceOption(sql.transactionService))) return yield* new ProjectionFault({
|
|
2860
|
+
phase: "process",
|
|
2861
|
+
reason: "unsupported-composition",
|
|
2862
|
+
message: `The SqlClient for the rows of ${id} has no open transaction. Use the storage owner's client inside its transaction.`
|
|
2863
|
+
});
|
|
2864
|
+
return sql;
|
|
2865
|
+
});
|
|
2248
2866
|
const apply = Effect.fn("StateTable.apply")(function* (sql, id, before, items) {
|
|
2249
2867
|
let epoch = before.epoch;
|
|
2250
2868
|
let open = before.snapshot_open;
|
|
@@ -2305,7 +2923,7 @@ const migrate = Effect.fn("StateTable.migrate")(function* (sql) {
|
|
|
2305
2923
|
) WITHOUT ROWID`;
|
|
2306
2924
|
});
|
|
2307
2925
|
const synchronize = (address) => Effect.gen(function* () {
|
|
2308
|
-
const
|
|
2926
|
+
const sql = yield* transactionClient(address.id);
|
|
2309
2927
|
const { wire } = yield* address.stream;
|
|
2310
2928
|
const unavailable = () => new ProjectionFault({
|
|
2311
2929
|
phase: "read",
|
|
@@ -2352,7 +2970,7 @@ const synchronize = (address) => Effect.gen(function* () {
|
|
|
2352
2970
|
return yield* save(sql, address.id, state);
|
|
2353
2971
|
}).pipe(Effect.catchTag("SqlError", sqlFault(address.id)), Effect.asVoid, Effect.withSpan("StateTable.sync"));
|
|
2354
2972
|
const applySlice = (address, slice) => Effect.gen(function* () {
|
|
2355
|
-
const
|
|
2973
|
+
const sql = yield* transactionClient(address.id);
|
|
2356
2974
|
const stored = yield* head(sql, address.id);
|
|
2357
2975
|
if (Option.isSome(stored) && stored.value.applied_offset === slice.from || Option.isNone(stored) && slice.from === ZERO_OFFSET) {
|
|
2358
2976
|
if (Option.isNone(stored)) yield* clearRows(sql, address.id);
|
|
@@ -2418,39 +3036,48 @@ const reads = (id, collections) => {
|
|
|
2418
3036
|
};
|
|
2419
3037
|
/** A State stream's declaration, kept current by the ordinary projection runners. */
|
|
2420
3038
|
function define(state, options = {}) {
|
|
3039
|
+
const id = `state-table/${state.key}`;
|
|
3040
|
+
rejectProjectionVersion(id, options);
|
|
2421
3041
|
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
|
-
|
|
3042
|
+
const declaration = declare({
|
|
3043
|
+
id,
|
|
3044
|
+
params: state.paramCodecs,
|
|
3045
|
+
inputs: {}
|
|
3046
|
+
}, ({ decoded, ...key }) => {
|
|
3047
|
+
const address = state.at(decoded);
|
|
3048
|
+
const raw = Object.assign(StreamAddress.json(address.id, { schema: Schema.String }), {
|
|
3049
|
+
stream: address.stream,
|
|
3050
|
+
codec: Schema.String
|
|
3051
|
+
});
|
|
3052
|
+
const accepted = options.accepted?.at(decoded);
|
|
3053
|
+
if (accepted?.id === address.id) throw new RangeError("An accepted stream may not name an input stream");
|
|
3054
|
+
return {
|
|
3055
|
+
...key,
|
|
3056
|
+
accepted,
|
|
3057
|
+
inputs: { state: raw },
|
|
3058
|
+
commit: transaction,
|
|
3059
|
+
process: (batch) => applySlice(raw, batch.state),
|
|
3060
|
+
...reads(address.id, state.collections),
|
|
3061
|
+
sync: () => synchronize(raw)
|
|
3062
|
+
};
|
|
3063
|
+
});
|
|
3064
|
+
return Object.assign(declaration, {
|
|
2445
3065
|
inputs: { state },
|
|
2446
3066
|
parse: state.parse
|
|
2447
|
-
};
|
|
3067
|
+
});
|
|
2448
3068
|
}
|
|
3069
|
+
const clearIndex = (id) => Effect.gen(function* () {
|
|
3070
|
+
const sql = yield* transactionClient(id);
|
|
3071
|
+
yield* clearRows(sql, id);
|
|
3072
|
+
yield* sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`;
|
|
3073
|
+
}).pipe(Effect.catchTag("SqlError", sqlFault(id)));
|
|
3074
|
+
/** Delete cached rows and their applied offset, even if the State stream has been removed. */
|
|
3075
|
+
const clear = Effect.fn("StateTable.clear")(function* (table) {
|
|
3076
|
+
yield* (yield* Transaction).withTransaction(clearIndex(table.inputs.state.id));
|
|
3077
|
+
});
|
|
2449
3078
|
/** Discard the index and replay the State stream atomically, retaining the binding checkpoint. */
|
|
2450
3079
|
const rebuild = Effect.fn("StateTable.rebuild")(function* (table) {
|
|
2451
|
-
|
|
2452
|
-
const id = table.inputs.state.id;
|
|
2453
|
-
yield* tx.withTransaction(clearRows(tx.sql, id).pipe(Effect.andThen(tx.sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`), Effect.catchTag("SqlError", sqlFault(id)), Effect.andThen(table.sync())));
|
|
3080
|
+
yield* (yield* Transaction).withTransaction(clearIndex(table.inputs.state.id).pipe(Effect.andThen(table.sync())));
|
|
2454
3081
|
});
|
|
2455
3082
|
/** Append a reset to the State stream. The next table run applies it. */
|
|
2456
3083
|
const reset = Effect.fn("StateTable.reset")(function* (table) {
|
|
@@ -2483,8 +3110,9 @@ const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function*
|
|
|
2483
3110
|
const params = table.parse(output.id);
|
|
2484
3111
|
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
3112
|
const { wire } = yield* output.stream;
|
|
2486
|
-
yield*
|
|
2487
|
-
yield*
|
|
3113
|
+
const generationBound = (yield* TransactionGenerationOutputs)?.get(spec.output)?.address.id === output.id;
|
|
3114
|
+
if (!generationBound) yield* wire.create(output.id, { contentType: output.contentType }).pipe(Effect.mapError(writeFault(output.id)));
|
|
3115
|
+
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
3116
|
const groups = /* @__PURE__ */ new Map();
|
|
2489
3117
|
for (const { item } of items(batch)) for (const record of spec.records(item, unit)) {
|
|
2490
3118
|
const key = spec.key(record, unit);
|
|
@@ -2534,6 +3162,8 @@ function process(table, spec) {
|
|
|
2534
3162
|
* request writes. Triggers must belong to this storage owner. A provided trigger
|
|
2535
3163
|
* service on another owner dies at attach with a RangeError naming its stream;
|
|
2536
3164
|
* remote trigger followers require the process host, Projection.attach.
|
|
3165
|
+
* On acquire, startup replays from the checkpoint inventory or `options.bindings`
|
|
3166
|
+
* are queued for the alarm on this object.
|
|
2537
3167
|
*
|
|
2538
3168
|
* Durable by default: each commit writes a pending mark for its bindings in
|
|
2539
3169
|
* the same transaction, so an eviction or a deploy between the commit and the
|
|
@@ -2553,7 +3183,6 @@ const attach = (projection, options = {}) => {
|
|
|
2553
3183
|
const registry = yield* Effect.serviceOption(Registry);
|
|
2554
3184
|
const changed = Option.isNone(registry) ? Effect.void : yield* registerRunner(registry.value, {
|
|
2555
3185
|
id: projection.id,
|
|
2556
|
-
version: projection.version,
|
|
2557
3186
|
generation: projection.generation,
|
|
2558
3187
|
status: Effect.gen(function* () {
|
|
2559
3188
|
const state = host === void 0 ? {
|
|
@@ -2601,4 +3230,4 @@ const attach = (projection, options = {}) => {
|
|
|
2601
3230
|
});
|
|
2602
3231
|
};
|
|
2603
3232
|
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 };
|
|
3233
|
+
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 };
|