effect-durable-agent 0.1.0-alpha.1
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/CHANGELOG.md +10 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +21 -0
- package/README.md +305 -0
- package/SECURITY.md +8 -0
- package/dist/command-queues-CQ9cwRP7.d.ts +468 -0
- package/dist/commands-Ce1ec6kH.d.ts +104 -0
- package/dist/compaction-YayFKo_1.d.ts +144 -0
- package/dist/core-Hv3cFydL.d.ts +81 -0
- package/dist/domain/command-queues.d.ts +2 -0
- package/dist/domain/command-queues.js +97 -0
- package/dist/domain/command-queues.js.map +1 -0
- package/dist/domain/message-transcript.d.ts +2 -0
- package/dist/domain/message-transcript.js +111 -0
- package/dist/domain/message-transcript.js.map +1 -0
- package/dist/domain/reduced-state-schema.d.ts +996 -0
- package/dist/domain/reduced-state-schema.js +286 -0
- package/dist/domain/reduced-state-schema.js.map +1 -0
- package/dist/domain/reduced-state.d.ts +2 -0
- package/dist/domain/reduced-state.js +2 -0
- package/dist/durable-C3Rz7kg3.js +625 -0
- package/dist/durable-C3Rz7kg3.js.map +1 -0
- package/dist/durable-DlScwmCy.d.ts +7424 -0
- package/dist/durable-object-runtime-B7jwBY2R.js +1494 -0
- package/dist/durable-object-runtime-B7jwBY2R.js.map +1 -0
- package/dist/durable-object-runtime-pWv0ohlz.d.ts +257 -0
- package/dist/durable-object-storage-Czy7IPrh.d.ts +41 -0
- package/dist/events-Bb9-Cu-7.d.ts +918 -0
- package/dist/host/durable-object-runtime.d.ts +2 -0
- package/dist/host/durable-object-runtime.js +2 -0
- package/dist/host/durable-object-storage.d.ts +2 -0
- package/dist/host/durable-object-storage.js +0 -0
- package/dist/host/durable-object.d.ts +83 -0
- package/dist/host/durable-object.js +191 -0
- package/dist/host/durable-object.js.map +1 -0
- package/dist/host/websocket-wire.d.ts +2 -0
- package/dist/host/websocket-wire.js +88 -0
- package/dist/host/websocket-wire.js.map +1 -0
- package/dist/id-generator-C2Q15uZM.d.ts +33 -0
- package/dist/index-BVVgDSdq.d.ts +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/keep-alive-DYDsH6qN.d.ts +111 -0
- package/dist/keep-alive-p8dIcSVy.js +109 -0
- package/dist/keep-alive-p8dIcSVy.js.map +1 -0
- package/dist/message-transcript-BCHdHAe2.d.ts +32 -0
- package/dist/prompt-projector-9_02lk5-.d.ts +40 -0
- package/dist/reduced-state-C4nVVzz9.js +910 -0
- package/dist/reduced-state-C4nVVzz9.js.map +1 -0
- package/dist/reducer-registry-C0svUa63.d.ts +69 -0
- package/dist/runtime-C56FQxiL.d.ts +60 -0
- package/dist/services/compaction.d.ts +2 -0
- package/dist/services/compaction.js +426 -0
- package/dist/services/compaction.js.map +1 -0
- package/dist/services/id-generator.d.ts +2 -0
- package/dist/services/id-generator.js +56 -0
- package/dist/services/id-generator.js.map +1 -0
- package/dist/services/prompt-projector.d.ts +2 -0
- package/dist/services/prompt-projector.js +27 -0
- package/dist/services/prompt-projector.js.map +1 -0
- package/dist/services/reducer-registry.d.ts +2 -0
- package/dist/services/reducer-registry.js +71 -0
- package/dist/services/reducer-registry.js.map +1 -0
- package/dist/services/runtime.d.ts +2 -0
- package/dist/services/runtime.js +84 -0
- package/dist/services/runtime.js.map +1 -0
- package/dist/services/session-query.d.ts +2 -0
- package/dist/services/session-query.js +2 -0
- package/dist/services/session-store.d.ts +2 -0
- package/dist/services/session-store.js +2 -0
- package/dist/services/sink-registry.d.ts +2 -0
- package/dist/services/sink-registry.js +2 -0
- package/dist/services/span-names.d.ts +28 -0
- package/dist/services/span-names.js +42 -0
- package/dist/services/span-names.js.map +1 -0
- package/dist/services/tool-registry.d.ts +2 -0
- package/dist/services/tool-registry.js +46 -0
- package/dist/services/tool-registry.js.map +1 -0
- package/dist/services/tracing.d.ts +76 -0
- package/dist/services/tracing.js +116 -0
- package/dist/services/tracing.js.map +1 -0
- package/dist/session-query-DOc1KanA.js +2930 -0
- package/dist/session-query-DOc1KanA.js.map +1 -0
- package/dist/session-query-DlRo5Ufc.d.ts +769 -0
- package/dist/session-store-D2Ore1QC.d.ts +295 -0
- package/dist/session-store-pYxQW9qh.js +214 -0
- package/dist/session-store-pYxQW9qh.js.map +1 -0
- package/dist/sink-registry-CFC6xjsN.js +312 -0
- package/dist/sink-registry-CFC6xjsN.js.map +1 -0
- package/dist/sink-registry-CIU0LD3m.d.ts +158 -0
- package/dist/testkit/layers.d.ts +101 -0
- package/dist/testkit/layers.js +108 -0
- package/dist/testkit/layers.js.map +1 -0
- package/dist/tool-registry-CcnkAAQK.d.ts +51 -0
- package/dist/tracing-BXHAkxkx.d.ts +111 -0
- package/dist/types/commands.d.ts +2 -0
- package/dist/types/commands.js +60 -0
- package/dist/types/commands.js.map +1 -0
- package/dist/types/core.d.ts +2 -0
- package/dist/types/core.js +68 -0
- package/dist/types/core.js.map +1 -0
- package/dist/types/events/durable.d.ts +2 -0
- package/dist/types/events/durable.js +2 -0
- package/dist/types/events.d.ts +4 -0
- package/dist/types/events.js +90 -0
- package/dist/types/events.js.map +1 -0
- package/dist/types/tracing.d.ts +2 -0
- package/dist/types/tracing.js +99 -0
- package/dist/types/tracing.js.map +1 -0
- package/dist/websocket-wire-DvOu_6BJ.d.ts +16773 -0
- package/docs/assets/architecture.svg +106 -0
- package/docs/assets/event-sequence.svg +143 -0
- package/docs/assets/gcp-trace.png +0 -0
- package/docs/message-steering.md +831 -0
- package/docs/releasing.md +57 -0
- package/docs/spec.md +774 -0
- package/docs/subagents.md +725 -0
- package/docs/testing.md +64 -0
- package/docs/ui-projection.md +742 -0
- package/docs/websocket-protocol.md +613 -0
- package/examples/001-no-tools/README.md +65 -0
- package/examples/001-no-tools/worker.ts +79 -0
- package/examples/002-slack-bridge/README.md +134 -0
- package/examples/002-slack-bridge/events.ts +115 -0
- package/examples/002-slack-bridge/reducer.ts +216 -0
- package/examples/002-slack-bridge/scenario.test.ts +223 -0
- package/examples/002-slack-bridge/sinks.ts +109 -0
- package/examples/002-slack-bridge/worker.ts +140 -0
- package/examples/003-sandbox-lifecycle/README.md +78 -0
- package/examples/003-sandbox-lifecycle/events.ts +203 -0
- package/examples/003-sandbox-lifecycle/reducer.ts +305 -0
- package/examples/003-sandbox-lifecycle/scenario.test.ts +202 -0
- package/examples/_shared/event-id.ts +12 -0
- package/examples/_shared/http.ts +27 -0
- package/examples/_shared/openai.ts +33 -0
- package/package.json +181 -0
- package/testing/offline-trace/README.md +63 -0
- package/tooling/oxlint/index.mjs +15 -0
- package/tooling/oxlint/rules/effect-span-from-catalog.mjs +152 -0
- package/tooling/oxlint/rules/span-catalog-format.mjs +74 -0
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { SequenceNumber, durablePosition } from "./types/core.js";
|
|
2
|
+
import { Jn as turnFailedEventType, Xn as turnStoppedEventType, Yn as turnStartedEventType, qn as turnCompletedEventType } from "./durable-C3Rz7kg3.js";
|
|
3
|
+
import { f as reduceCommittedEvents, o as foldReducedState } from "./reduced-state-C4nVVzz9.js";
|
|
4
|
+
import { a as EDASessionStoreError, i as EDASessionStore, t as CommittedDurableEvent } from "./session-store-pYxQW9qh.js";
|
|
5
|
+
import { IdGenerator } from "./services/id-generator.js";
|
|
6
|
+
import { n as EventFactory, r as SessionContext, t as EDAKeepAlive } from "./keep-alive-p8dIcSVy.js";
|
|
7
|
+
import { annotateEdaSpan } from "./services/tracing.js";
|
|
8
|
+
import { EDAReducerRegistry } from "./services/reducer-registry.js";
|
|
9
|
+
import * as Context from "effect/Context";
|
|
10
|
+
import * as Effect from "effect/Effect";
|
|
11
|
+
import * as Layer from "effect/Layer";
|
|
12
|
+
import * as Schema from "effect/Schema";
|
|
13
|
+
import * as Stream from "effect/Stream";
|
|
14
|
+
import * as Cause from "effect/Cause";
|
|
15
|
+
import * as Ref from "effect/Ref";
|
|
16
|
+
import * as Scope from "effect/Scope";
|
|
17
|
+
import * as PubSub from "effect/PubSub";
|
|
18
|
+
import * as Duration from "effect/Duration";
|
|
19
|
+
import * as Schedule from "effect/Schedule";
|
|
20
|
+
import * as SynchronizedRef from "effect/SynchronizedRef";
|
|
21
|
+
//#region src/services/live-event-bus.ts
|
|
22
|
+
/** Conservative raw-delta cap for one open turn's live-only reconnect replay. */
|
|
23
|
+
const activeTurnEphemeralReplayCapacity = 4096;
|
|
24
|
+
/** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */
|
|
25
|
+
var LiveEventBus = class LiveEventBus extends Context.Service()("@effect-durable-agent/LiveEventBus") {
|
|
26
|
+
static Live = Layer.effect(LiveEventBus, Effect.gen(function* () {
|
|
27
|
+
return makeLiveBus(yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown), yield* Ref.make({
|
|
28
|
+
events: [],
|
|
29
|
+
overflowed: false
|
|
30
|
+
}));
|
|
31
|
+
}));
|
|
32
|
+
};
|
|
33
|
+
const makeLiveBus = (pubsub, activeTurnReplay) => ({
|
|
34
|
+
publish: (event) => updateActiveTurnReplay(activeTurnReplay, event).pipe(Effect.andThen(PubSub.publish(pubsub, event))),
|
|
35
|
+
subscribeQueue: () => PubSub.subscribe(pubsub),
|
|
36
|
+
subscribe: () => Effect.map(PubSub.subscribe(pubsub), (subscription) => Stream.fromEffectRepeat(PubSub.take(subscription))),
|
|
37
|
+
activeTurnReplay: () => Ref.get(activeTurnReplay)
|
|
38
|
+
});
|
|
39
|
+
const updateActiveTurnReplay = (ref, event) => Ref.update(ref, (state) => nextActiveTurnReplay(state, event));
|
|
40
|
+
const nextActiveTurnReplay = (state, event) => {
|
|
41
|
+
if (event.event.type === turnStartedEventType) return {
|
|
42
|
+
turnId: event.event.payload.turnId,
|
|
43
|
+
events: [],
|
|
44
|
+
overflowed: false
|
|
45
|
+
};
|
|
46
|
+
if (event.event.type === turnCompletedEventType || event.event.type === turnFailedEventType || event.event.type === turnStoppedEventType) {
|
|
47
|
+
const turnId = event.event.payload.turnId;
|
|
48
|
+
return turnId === void 0 || state.turnId === void 0 || turnId === state.turnId ? {
|
|
49
|
+
events: [],
|
|
50
|
+
overflowed: false
|
|
51
|
+
} : state;
|
|
52
|
+
}
|
|
53
|
+
if (event.event.durability !== "ephemeral" || state.turnId === void 0) return state;
|
|
54
|
+
const events = [...state.events, event];
|
|
55
|
+
if (events.length <= 4096) return {
|
|
56
|
+
...state,
|
|
57
|
+
events
|
|
58
|
+
};
|
|
59
|
+
return {
|
|
60
|
+
...state,
|
|
61
|
+
events: events.slice(events.length - activeTurnEphemeralReplayCapacity),
|
|
62
|
+
overflowed: true
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/services/sink-checkpoint-store.ts
|
|
67
|
+
/** Stable sink name used as the durable checkpoint key. */
|
|
68
|
+
const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand("EDASinkName"));
|
|
69
|
+
/**
|
|
70
|
+
* Semantic checkpoint store for registered EDA sinks.
|
|
71
|
+
*
|
|
72
|
+
* Checkpoints are intentionally exposed as load/save/commit operations rather
|
|
73
|
+
* than SQL. Sink side effects happen outside event append transactions, and the
|
|
74
|
+
* cursor advances only after the sink finishes its own external work.
|
|
75
|
+
*/
|
|
76
|
+
var SinkCheckpointStore = class SinkCheckpointStore extends Context.Service()("@effect-durable-agent/SinkCheckpointStore") {
|
|
77
|
+
/** In-memory checkpoint implementation for store/runtime tests. */
|
|
78
|
+
static InMemory = Layer.effect(SinkCheckpointStore, Effect.gen(function* () {
|
|
79
|
+
return makeInMemorySinkCheckpointStore(yield* Ref.make(/* @__PURE__ */ new Map()));
|
|
80
|
+
}));
|
|
81
|
+
};
|
|
82
|
+
/** Build a ref-backed checkpoint map with the same public semantics as host adapters. */
|
|
83
|
+
const makeInMemorySinkCheckpointStore = (checkpoints) => ({
|
|
84
|
+
load: (sinkName) => Ref.get(checkpoints).pipe(Effect.map((map) => map.get(sinkName) ?? {
|
|
85
|
+
afterSeq: SequenceNumber.make(0),
|
|
86
|
+
payload: void 0
|
|
87
|
+
})),
|
|
88
|
+
saveState: (sinkName, payload) => Ref.update(checkpoints, (map) => {
|
|
89
|
+
const next = new Map(map);
|
|
90
|
+
next.set(sinkName, {
|
|
91
|
+
afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),
|
|
92
|
+
payload
|
|
93
|
+
});
|
|
94
|
+
return next;
|
|
95
|
+
}),
|
|
96
|
+
commit: (sinkName, afterSeq, payload) => Ref.update(checkpoints, (map) => {
|
|
97
|
+
const next = new Map(map);
|
|
98
|
+
next.set(sinkName, {
|
|
99
|
+
afterSeq,
|
|
100
|
+
payload
|
|
101
|
+
});
|
|
102
|
+
return next;
|
|
103
|
+
})
|
|
104
|
+
});
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/services/sink-registry.ts
|
|
107
|
+
/** Convenience constructor preserving a sink's literal name/type information. */
|
|
108
|
+
const EDASink = { make: (sink) => sink };
|
|
109
|
+
/** Registry and runner for app-provided EDA sinks. */
|
|
110
|
+
var EDASinkRegistry = class EDASinkRegistry extends Context.Service()("@effect-durable-agent/EDASinkRegistry") {
|
|
111
|
+
static Empty = Layer.succeed(EDASinkRegistry, {
|
|
112
|
+
sinks: [],
|
|
113
|
+
startSinkRunners: () => Effect.void,
|
|
114
|
+
notifyDurableHeadAdvanced: () => Effect.void,
|
|
115
|
+
publishEphemeralToSinks: () => Effect.void
|
|
116
|
+
});
|
|
117
|
+
static Live = (sinks) => Layer.effect(EDASinkRegistry, makeSinkRegistry(sinks));
|
|
118
|
+
};
|
|
119
|
+
const defaultBatchSize = 100;
|
|
120
|
+
const maxDurableSinkRetryDelay = Duration.seconds(5);
|
|
121
|
+
const sinkCheckpointFormatVersion = 1;
|
|
122
|
+
const durableSinkRetrySchedule = Schedule.exponential("100 millis").pipe(Schedule.jittered, Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.min(duration, maxDurableSinkRetryDelay))));
|
|
123
|
+
const makeSinkRegistry = (sinks) => Effect.gen(function* () {
|
|
124
|
+
const session = yield* SessionContext;
|
|
125
|
+
const store = yield* EDASessionStore;
|
|
126
|
+
const liveBus = yield* LiveEventBus;
|
|
127
|
+
const checkpointStore = yield* SinkCheckpointStore;
|
|
128
|
+
const eventFactory = yield* EventFactory;
|
|
129
|
+
const ids = yield* IdGenerator;
|
|
130
|
+
const reducerRegistry = yield* EDAReducerRegistry;
|
|
131
|
+
const keepAlive = yield* EDAKeepAlive;
|
|
132
|
+
const started = yield* Ref.make(false);
|
|
133
|
+
const baseContext = (staged, publishEphemeral, scope, checkpoint) => ({
|
|
134
|
+
sessionId: session.sessionId,
|
|
135
|
+
checkpoint,
|
|
136
|
+
events: eventFactory,
|
|
137
|
+
makeEventId: ids.makeEventId,
|
|
138
|
+
emitEphemeral: publishEphemeral,
|
|
139
|
+
stageDurable: (event) => Effect.sync(() => staged.push(event)),
|
|
140
|
+
forkScoped: (effect) => effect.pipe(Effect.forkIn(scope), Effect.asVoid)
|
|
141
|
+
});
|
|
142
|
+
const makeSinkRunner = (sink, input) => Effect.gen(function* () {
|
|
143
|
+
const sinkName = EDASinkName.make(sink.name);
|
|
144
|
+
const storedCheckpoint = yield* checkpointStore.load(sinkName);
|
|
145
|
+
const checkpointRef = yield* SynchronizedRef.make(storedCheckpoint);
|
|
146
|
+
const checkpoint = makeSinkCheckpoint(checkpointStore, sinkName, checkpointRef);
|
|
147
|
+
const cursor = storedCheckpoint.afterSeq;
|
|
148
|
+
const prefix = yield* readDurablePrefixThrough(store, cursor);
|
|
149
|
+
const state = yield* Ref.make({
|
|
150
|
+
cursor,
|
|
151
|
+
reduced: reduceCommittedEvents(prefix),
|
|
152
|
+
reducerStates: reducerRegistry.reduce(reducerRegistry.initial, prefix)
|
|
153
|
+
});
|
|
154
|
+
const live = yield* liveBus.subscribeQueue().pipe(Scope.provide(input.scope));
|
|
155
|
+
const processDurableBatch = Effect.fnUntraced(function* (allEvents) {
|
|
156
|
+
if (allEvents.length === 0) return;
|
|
157
|
+
const current = yield* Ref.get(state);
|
|
158
|
+
const fresh = allEvents.filter((entry) => entry.position.seq > current.cursor);
|
|
159
|
+
if (fresh.length === 0) return;
|
|
160
|
+
const durable = sink.durable;
|
|
161
|
+
const throughSeq = fresh.at(-1).position.seq;
|
|
162
|
+
const nextReduced = foldReducedState(current.reduced, fresh);
|
|
163
|
+
const nextReducerStates = reducerRegistry.reduce(current.reducerStates, fresh);
|
|
164
|
+
const eventsForSink = durable === void 0 ? [] : filterInterested(fresh, durable.interests);
|
|
165
|
+
if (durable !== void 0 && eventsForSink.length > 0) yield* Effect.gen(function* () {
|
|
166
|
+
const staged = [];
|
|
167
|
+
yield* durable.process({
|
|
168
|
+
allEvents: fresh,
|
|
169
|
+
events: eventsForSink,
|
|
170
|
+
stateAfter: nextReduced,
|
|
171
|
+
reducerStates: nextReducerStates,
|
|
172
|
+
throughSeq
|
|
173
|
+
}, baseContext(staged, input.publishEphemeral, input.scope, checkpoint));
|
|
174
|
+
if (staged.length > 0) {
|
|
175
|
+
yield* annotateEdaSpan({ "eda.sink.staged_events": staged.length });
|
|
176
|
+
yield* input.appendDurableBatch(staged);
|
|
177
|
+
}
|
|
178
|
+
}).pipe(Effect.withSpan("agent.sink.drain", { attributes: {
|
|
179
|
+
"eda.sink.name": sink.name,
|
|
180
|
+
"eda.sink.cursor.before": current.cursor,
|
|
181
|
+
"eda.sink.events.read": fresh.length,
|
|
182
|
+
"eda.sink.events.interested": eventsForSink.length,
|
|
183
|
+
"eda.sink.cursor.after": throughSeq
|
|
184
|
+
} }));
|
|
185
|
+
yield* commitSinkCheckpoint(checkpointStore, sinkName, checkpointRef, throughSeq);
|
|
186
|
+
yield* Ref.set(state, {
|
|
187
|
+
cursor: throughSeq,
|
|
188
|
+
reduced: nextReduced,
|
|
189
|
+
reducerStates: nextReducerStates
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
const processDurableBatchWithRetry = (events) => keepAlive.withActiveWork(`sink:${sink.name}`, processDurableBatch(events).pipe(Effect.tapError((error) => Effect.logWarning("EDA sink durable projection failed; retrying", {
|
|
193
|
+
error: formatSinkError(error),
|
|
194
|
+
sink: sink.name
|
|
195
|
+
})), Effect.retry(durableSinkRetrySchedule)));
|
|
196
|
+
const drainDurablesThrough = (targetHead) => Effect.gen(function* () {
|
|
197
|
+
while (true) {
|
|
198
|
+
const current = yield* Ref.get(state);
|
|
199
|
+
if (current.cursor >= targetHead) return;
|
|
200
|
+
const allEvents = yield* readCursorBatchThrough(store, current.cursor, targetHead, sink.durable?.batchSize);
|
|
201
|
+
if (allEvents.length === 0) return;
|
|
202
|
+
yield* processDurableBatchWithRetry(allEvents);
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
const processLiveDurable = (event) => Effect.gen(function* () {
|
|
206
|
+
const current = yield* Ref.get(state);
|
|
207
|
+
if (event.position.seq <= current.cursor) return;
|
|
208
|
+
if (event.position.seq > current.cursor + 1) yield* drainDurablesThrough(SequenceNumber.make(event.position.seq - 1));
|
|
209
|
+
const afterCatchup = yield* Ref.get(state);
|
|
210
|
+
if (event.position.seq > afterCatchup.cursor + 1) {
|
|
211
|
+
yield* Effect.logWarning("EDA sink runner could not catch up before live durable", {
|
|
212
|
+
cursor: afterCatchup.cursor,
|
|
213
|
+
eventSeq: event.position.seq,
|
|
214
|
+
sink: sink.name
|
|
215
|
+
});
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
yield* processDurableBatchWithRetry([committedDurableFromPositioned(event)]);
|
|
219
|
+
});
|
|
220
|
+
const processLiveEphemeral = (event) => Effect.gen(function* () {
|
|
221
|
+
const before = yield* Ref.get(state);
|
|
222
|
+
if (event.position.seq < before.cursor) return;
|
|
223
|
+
if (event.position.seq > before.cursor) yield* drainDurablesThrough(event.position.seq);
|
|
224
|
+
const after = yield* Ref.get(state);
|
|
225
|
+
if (event.position.seq !== after.cursor) return;
|
|
226
|
+
if (sink.ephemeral === void 0 || !matchesInterest(event.event.type, sink.ephemeral.interests)) return;
|
|
227
|
+
yield* sink.ephemeral.process(event, baseContext([], input.publishEphemeral, input.scope, checkpoint)).pipe(Effect.catchCause((cause) => Effect.logError("EDA sink ephemeral projection failed", {
|
|
228
|
+
cause: String(cause),
|
|
229
|
+
sink: sink.name
|
|
230
|
+
})));
|
|
231
|
+
});
|
|
232
|
+
const processLiveEvent = (event) => event.event.durability === "durable" ? processLiveDurable(event) : processLiveEphemeral(event);
|
|
233
|
+
yield* Effect.gen(function* () {
|
|
234
|
+
yield* drainDurablesThrough(input.initialHead);
|
|
235
|
+
yield* Effect.forever(Effect.gen(function* () {
|
|
236
|
+
yield* processLiveEvent(yield* PubSub.take(live));
|
|
237
|
+
}));
|
|
238
|
+
}).pipe(Effect.catchCause((cause) => Effect.logError("EDA sink runner failed", {
|
|
239
|
+
cause: Cause.pretty(cause),
|
|
240
|
+
sink: sink.name
|
|
241
|
+
}))).pipe(Effect.forkIn(input.scope));
|
|
242
|
+
});
|
|
243
|
+
return {
|
|
244
|
+
sinks,
|
|
245
|
+
startSinkRunners: Effect.fnUntraced(function* (input) {
|
|
246
|
+
if (yield* Ref.getAndSet(started, true)) return;
|
|
247
|
+
yield* Effect.forEach(sinks, (sink) => makeSinkRunner(sink, input), {
|
|
248
|
+
discard: true,
|
|
249
|
+
concurrency: "unbounded"
|
|
250
|
+
});
|
|
251
|
+
}),
|
|
252
|
+
notifyDurableHeadAdvanced: () => Effect.void,
|
|
253
|
+
publishEphemeralToSinks: () => Effect.void
|
|
254
|
+
};
|
|
255
|
+
});
|
|
256
|
+
const readDurablePrefixThrough = (store, throughSeq) => {
|
|
257
|
+
if (throughSeq <= SequenceNumber.make(0)) return Effect.succeed([]);
|
|
258
|
+
return store.eventsAfter(SequenceNumber.make(0)).pipe(Stream.takeWhile((event) => event.position.seq <= throughSeq), Stream.runCollect, Effect.map((events) => Array.from(events)));
|
|
259
|
+
};
|
|
260
|
+
const makeSinkCheckpoint = (store, sinkName, checkpointRef) => ({
|
|
261
|
+
get: (schema, initial) => SynchronizedRef.get(checkpointRef).pipe(Effect.flatMap((checkpoint) => {
|
|
262
|
+
const serialized = serializedSinkState(checkpoint.payload);
|
|
263
|
+
return serialized === void 0 ? Effect.succeed(initial) : decodeSinkState(schema, serialized.state);
|
|
264
|
+
})),
|
|
265
|
+
save: (schema, state) => encodeSinkState(schema, state).pipe(Effect.flatMap((encoded) => {
|
|
266
|
+
const payload = {
|
|
267
|
+
formatVersion: sinkCheckpointFormatVersion,
|
|
268
|
+
state: encoded,
|
|
269
|
+
updatedAtMs: Date.now()
|
|
270
|
+
};
|
|
271
|
+
return SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) => store.saveState(sinkName, payload).pipe(Effect.as([void 0, {
|
|
272
|
+
afterSeq: checkpoint.afterSeq,
|
|
273
|
+
payload
|
|
274
|
+
}])));
|
|
275
|
+
}))
|
|
276
|
+
});
|
|
277
|
+
const commitSinkCheckpoint = (store, sinkName, checkpointRef, afterSeq) => SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) => store.commit(sinkName, afterSeq, checkpoint.payload).pipe(Effect.as([void 0, {
|
|
278
|
+
afterSeq,
|
|
279
|
+
payload: checkpoint.payload
|
|
280
|
+
}])));
|
|
281
|
+
const serializedSinkState = (payload) => {
|
|
282
|
+
if (typeof payload !== "object" || payload === null || !("formatVersion" in payload) || payload.formatVersion !== sinkCheckpointFormatVersion || !("state" in payload) || !("updatedAtMs" in payload) || typeof payload.updatedAtMs !== "number") return;
|
|
283
|
+
return {
|
|
284
|
+
formatVersion: sinkCheckpointFormatVersion,
|
|
285
|
+
state: payload.state,
|
|
286
|
+
updatedAtMs: payload.updatedAtMs
|
|
287
|
+
};
|
|
288
|
+
};
|
|
289
|
+
const decodeSinkState = (schema, encoded) => Effect.try({
|
|
290
|
+
try: () => Schema.decodeUnknownSync(schema)(encoded),
|
|
291
|
+
catch: (cause) => sinkCheckpointCodecError("decoding", cause)
|
|
292
|
+
});
|
|
293
|
+
const encodeSinkState = (schema, state) => Effect.try({
|
|
294
|
+
try: () => Schema.encodeUnknownSync(schema)(state),
|
|
295
|
+
catch: (cause) => sinkCheckpointCodecError("encoding", cause)
|
|
296
|
+
});
|
|
297
|
+
const sinkCheckpointCodecError = (operation, cause) => new EDASessionStoreError({ message: cause instanceof Error ? `${operation} sink checkpoint: ${cause.message}` : `${operation} sink checkpoint: ${String(cause)}` });
|
|
298
|
+
const readCursorBatchThrough = (store, afterSeq, throughSeq, batchSize = defaultBatchSize) => store.eventsAfter(afterSeq).pipe(Stream.takeWhile((event) => event.position.seq <= throughSeq), Stream.take(batchSize), Stream.runCollect, Effect.map((events) => Array.from(events)));
|
|
299
|
+
const committedDurableFromPositioned = (event) => CommittedDurableEvent.make({
|
|
300
|
+
event: event.event,
|
|
301
|
+
position: durablePosition(event.position.seq)
|
|
302
|
+
});
|
|
303
|
+
const filterInterested = (events, interests) => events.filter((event) => matchesInterest(event.event.type, interests));
|
|
304
|
+
const matchesInterest = (type, interests) => interests === void 0 || interests.some((interest) => interest === type);
|
|
305
|
+
const formatSinkError = (error) => {
|
|
306
|
+
if (Cause.isUnknownError(error)) return `${error.message ?? error._tag}: ${formatSinkError(error.cause)}`;
|
|
307
|
+
return error instanceof Error ? error.message : String(error);
|
|
308
|
+
};
|
|
309
|
+
//#endregion
|
|
310
|
+
export { LiveEventBus as i, EDASinkRegistry as n, SinkCheckpointStore as r, EDASink as t };
|
|
311
|
+
|
|
312
|
+
//# sourceMappingURL=sink-registry-CFC6xjsN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sink-registry-CFC6xjsN.js","names":[],"sources":["../src/services/live-event-bus.ts","../src/services/sink-checkpoint-store.ts","../src/services/sink-registry.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { TurnId } from \"../types/core\";\nimport {\n PositionedEvent,\n turnCompletedEventType,\n turnFailedEventType,\n turnStartedEventType,\n turnStoppedEventType,\n} from \"../types/events\";\n\n/** Conservative raw-delta cap for one open turn's live-only reconnect replay. */\nexport const activeTurnEphemeralReplayCapacity = 4_096;\n\n/** Live-only replay buffer for the currently open turn. */\nexport interface ActiveTurnEphemeralReplay {\n readonly turnId?: TurnId;\n readonly events: ReadonlyArray<PositionedEvent>;\n readonly overflowed: boolean;\n}\n\n/** In-memory live fanout plus active-turn replay source for reconnect streams. */\nexport interface LiveEventBusShape {\n readonly publish: (event: PositionedEvent) => Effect.Effect<boolean>;\n readonly subscribe: () => Effect.Effect<Stream.Stream<PositionedEvent>, never, Scope.Scope>;\n readonly subscribeQueue: () => Effect.Effect<\n PubSub.Subscription<PositionedEvent>,\n never,\n Scope.Scope\n >;\n /** Snapshot raw live-only events retained for the currently open turn. */\n readonly activeTurnReplay: () => Effect.Effect<ActiveTurnEphemeralReplay>;\n}\n\n/** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */\nexport class LiveEventBus extends Context.Service<LiveEventBus, LiveEventBusShape>()(\n \"@effect-durable-agent/LiveEventBus\",\n) {\n static readonly Live = Layer.effect(\n LiveEventBus,\n Effect.gen(function* () {\n const pubsub = yield* Effect.acquireRelease(\n PubSub.unbounded<PositionedEvent>(),\n PubSub.shutdown,\n );\n const activeTurnReplay = yield* Ref.make<ActiveTurnEphemeralReplay>({\n events: [],\n overflowed: false,\n });\n return makeLiveBus(pubsub, activeTurnReplay);\n }),\n );\n}\n\nconst makeLiveBus = (\n pubsub: PubSub.PubSub<PositionedEvent>,\n activeTurnReplay: Ref.Ref<ActiveTurnEphemeralReplay>,\n): LiveEventBusShape => ({\n publish: (event) =>\n updateActiveTurnReplay(activeTurnReplay, event).pipe(\n Effect.andThen(PubSub.publish(pubsub, event)),\n ),\n subscribeQueue: () => PubSub.subscribe(pubsub),\n subscribe: () =>\n Effect.map(PubSub.subscribe(pubsub), (subscription) =>\n Stream.fromEffectRepeat(PubSub.take(subscription)),\n ),\n activeTurnReplay: () => Ref.get(activeTurnReplay),\n});\n\nconst updateActiveTurnReplay = (\n ref: Ref.Ref<ActiveTurnEphemeralReplay>,\n event: PositionedEvent,\n): Effect.Effect<void> => Ref.update(ref, (state) => nextActiveTurnReplay(state, event));\n\nconst nextActiveTurnReplay = (\n state: ActiveTurnEphemeralReplay,\n event: PositionedEvent,\n): ActiveTurnEphemeralReplay => {\n if (event.event.type === turnStartedEventType) {\n return {\n turnId: (event.event.payload as { readonly turnId: TurnId }).turnId,\n events: [],\n overflowed: false,\n };\n }\n\n if (\n event.event.type === turnCompletedEventType ||\n event.event.type === turnFailedEventType ||\n event.event.type === turnStoppedEventType\n ) {\n const turnId = (event.event.payload as { readonly turnId?: TurnId }).turnId;\n return turnId === undefined || state.turnId === undefined || turnId === state.turnId\n ? { events: [], overflowed: false }\n : state;\n }\n\n if (event.event.durability !== \"ephemeral\" || state.turnId === undefined) {\n return state;\n }\n\n const events = [...state.events, event];\n if (events.length <= activeTurnEphemeralReplayCapacity) {\n return { ...state, events };\n }\n return {\n ...state,\n events: events.slice(events.length - activeTurnEphemeralReplayCapacity),\n overflowed: true,\n };\n};\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { EDASessionStoreError } from \"./session-store\";\n\n/** Stable sink name used as the durable checkpoint key. */\nexport const EDASinkName = Schema.NonEmptyString.pipe(Schema.brand(\"EDASinkName\"));\nexport type EDASinkName = typeof EDASinkName.Type;\n\n/** Persisted cursor and sink-owned payload for one registered sink. */\nexport interface StoredSinkCheckpoint {\n readonly afterSeq: SequenceNumber;\n readonly payload: unknown | undefined;\n}\n\n/** Durable checkpoint persistence port for at-least-once sink runners. */\nexport interface SinkCheckpointStoreShape {\n /** Read the latest committed cursor and sink-owned payload. */\n readonly load: (\n sinkName: EDASinkName,\n ) => Effect.Effect<StoredSinkCheckpoint, EDASessionStoreError>;\n /** Save sink-owned state without advancing the durable cursor. */\n readonly saveState: (\n sinkName: EDASinkName,\n payload: unknown,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Atomically commit the processed cursor together with current sink-owned state. */\n readonly commit: (\n sinkName: EDASinkName,\n afterSeq: SequenceNumber,\n payload: unknown | undefined,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * Semantic checkpoint store for registered EDA sinks.\n *\n * Checkpoints are intentionally exposed as load/save/commit operations rather\n * than SQL. Sink side effects happen outside event append transactions, and the\n * cursor advances only after the sink finishes its own external work.\n */\nexport class SinkCheckpointStore extends Context.Service<\n SinkCheckpointStore,\n SinkCheckpointStoreShape\n>()(\"@effect-durable-agent/SinkCheckpointStore\") {\n /** In-memory checkpoint implementation for store/runtime tests. */\n static readonly InMemory = Layer.effect(\n SinkCheckpointStore,\n Effect.gen(function* () {\n const checkpoints = yield* Ref.make<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>(\n new Map(),\n );\n return makeInMemorySinkCheckpointStore(checkpoints);\n }),\n );\n}\n\n/** Build a ref-backed checkpoint map with the same public semantics as host adapters. */\nconst makeInMemorySinkCheckpointStore = (\n checkpoints: Ref.Ref<ReadonlyMap<EDASinkName, StoredSinkCheckpoint>>,\n): SinkCheckpointStoreShape => ({\n load: (sinkName) =>\n Ref.get(checkpoints).pipe(\n Effect.map(\n (map) =>\n map.get(sinkName) ?? {\n afterSeq: SequenceNumber.make(0),\n payload: undefined,\n },\n ),\n ),\n saveState: (sinkName, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, {\n afterSeq: map.get(sinkName)?.afterSeq ?? SequenceNumber.make(0),\n payload,\n });\n return next;\n }),\n commit: (sinkName, afterSeq, payload) =>\n Ref.update(checkpoints, (map) => {\n const next = new Map(map);\n next.set(sinkName, { afterSeq, payload });\n return next;\n }),\n});\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport {\n foldReducedState,\n reduceCommittedEvents,\n type ReducedState,\n} from \"../domain/reduced-state\";\nimport { EDAReducerRegistry, type EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { EventId, SessionId, SequenceNumber, durablePosition } from \"../types/core\";\nimport type {\n DurableEventEnvelope,\n EphemeralEventEnvelope,\n EventType,\n PositionedEvent,\n} from \"../types/events\";\nimport type { EDASessionStoreShape } from \"./session-store\";\nimport { CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport type { EventFactoryShape } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { LiveEventBus } from \"./live-event-bus\";\nimport { SessionContext } from \"./session-context\";\nimport {\n EDASinkName,\n SinkCheckpointStore,\n type SinkCheckpointStoreShape,\n type StoredSinkCheckpoint,\n} from \"./sink-checkpoint-store\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Cursor-window input delivered to one durable sink drain. */\nexport interface EDASinkDurableBatch {\n /** All durable events replayed for this cursor window, including uninterested events. */\n readonly allEvents: ReadonlyArray<CommittedDurableEvent>;\n /** Events matching the sink's durable interests. */\n readonly events: ReadonlyArray<CommittedDurableEvent>;\n /** Authoritative reduced state folded exactly through `throughSeq`. */\n readonly stateAfter: ReducedState;\n /** App-specific durable reducer states folded exactly through `throughSeq`. */\n readonly reducerStates: EDAReducerStateSnapshot;\n /** Durable sequence through which the sink may advance after success. */\n readonly throughSeq: SequenceNumber;\n}\n\n/** Typed, sink-owned durable state stored independently from cursor advancement. */\nexport interface EDASinkCheckpoint {\n /** Decode current durable state, or return `initial` for a new or legacy cursor row. */\n readonly get: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n initial: State,\n ) => Effect.Effect<State, EDASessionStoreError>;\n /** Validate, encode, and durably save state without advancing the sink cursor. */\n readonly save: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/** Capabilities exposed to sink processors without granting raw store or bus access. */\nexport interface EDASinkContext {\n readonly sessionId: SessionId;\n /** Sink-owned checkpoint state, serialized with cursor commits and background writes. */\n readonly checkpoint: EDASinkCheckpoint;\n /** Build a framework durable event if the sink needs to emit one. */\n readonly events: EventFactoryShape;\n /** Mint an app durable event id for staged custom events. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Publish a best-effort live-only event. */\n readonly emitEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n /** Stage durable events; the runner commits them after the sink succeeds. */\n readonly stageDurable: (event: DurableEventEnvelope) => Effect.Effect<void>;\n /** Fork background sink work into the session scope. */\n readonly forkScoped: (effect: Effect.Effect<unknown, unknown>) => Effect.Effect<void>;\n}\n\n/** At-least-once sink definition backed by a durable checkpoint. */\nexport interface EDADurableSinkDefinition {\n readonly interests?: ReadonlyArray<EventType | string>;\n readonly batchSize?: number;\n readonly process: (\n batch: EDASinkDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, unknown>;\n}\n\n/** Best-effort live-only sink definition. */\nexport interface EDAEphemeralSinkDefinition {\n readonly interests?: ReadonlyArray<EventType | string>;\n readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, unknown>;\n}\n\n/**\n * Named app integration hook with optional durable and ephemeral filters.\n *\n * Every sink runs on one serialized position-ordered lane. Durable callbacks are\n * retried before the sink checkpoint advances; ephemeral callbacks are best-effort\n * and are only processed after the durable prefix at their anchor sequence has\n * been projected.\n */\nexport interface EDASink {\n readonly name: string;\n readonly durable?: EDADurableSinkDefinition;\n readonly ephemeral?: EDAEphemeralSinkDefinition;\n}\n\n/** Convenience constructor preserving a sink's literal name/type information. */\nexport const EDASink = {\n make: <const Sink extends EDASink>(sink: Sink): Sink => sink,\n};\n\n/** Session-owned capabilities needed to start all registered sink runners. */\nexport interface EDASinkRunnerStartInput {\n readonly appendDurableBatch: (\n events: ReadonlyArray<DurableEventEnvelope>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n readonly initialHead: SequenceNumber;\n readonly publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n readonly scope: Scope.Scope;\n}\n\n/** Registry service coordinating durable checkpoints and live sink delivery. */\nexport interface EDASinkRegistryShape {\n readonly sinks: ReadonlyArray<EDASink>;\n /** Start long-lived sink runners. Safe to call once during session-state acquisition. */\n readonly startSinkRunners: (\n input: EDASinkRunnerStartInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Coalesced non-blocking nudge that the durable log head advanced. */\n readonly notifyDurableHeadAdvanced: (head: SequenceNumber) => Effect.Effect<void>;\n /** Best-effort non-blocking delivery to ephemeral sink workers. */\n readonly publishEphemeralToSinks: (\n event: PositionedEvent,\n publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>,\n ) => Effect.Effect<void>;\n}\n\n/** Registry and runner for app-provided EDA sinks. */\nexport class EDASinkRegistry extends Context.Service<EDASinkRegistry, EDASinkRegistryShape>()(\n \"@effect-durable-agent/EDASinkRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDASinkRegistry, {\n sinks: [],\n startSinkRunners: () => Effect.void,\n notifyDurableHeadAdvanced: () => Effect.void,\n publishEphemeralToSinks: () => Effect.void,\n } satisfies EDASinkRegistryShape);\n\n static readonly Live = (sinks: ReadonlyArray<EDASink>) =>\n Layer.effect(EDASinkRegistry, makeSinkRegistry(sinks));\n}\n\nconst defaultBatchSize = 100;\nconst maxDurableSinkRetryDelay = Duration.seconds(5);\nconst sinkCheckpointFormatVersion = 1;\nconst durableSinkRetrySchedule = Schedule.exponential(\"100 millis\").pipe(\n Schedule.jittered,\n Schedule.modifyDelay(({ duration }) =>\n Effect.succeed(Duration.min(duration, maxDurableSinkRetryDelay)),\n ),\n);\n\ninterface DurableRunnerState {\n readonly cursor: SequenceNumber;\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\ninterface SerializedSinkState {\n readonly formatVersion: typeof sinkCheckpointFormatVersion;\n readonly state: unknown;\n readonly updatedAtMs: number;\n}\n\nconst makeSinkRegistry = (sinks: ReadonlyArray<EDASink>) =>\n Effect.gen(function* () {\n const session = yield* SessionContext;\n const store = yield* EDASessionStore;\n const liveBus = yield* LiveEventBus;\n const checkpointStore = yield* SinkCheckpointStore;\n const eventFactory = yield* EventFactory;\n const ids = yield* IdGenerator;\n const reducerRegistry = yield* EDAReducerRegistry;\n const keepAlive = yield* EDAKeepAlive;\n const started = yield* Ref.make(false);\n\n const baseContext = (\n staged: Array<DurableEventEnvelope>,\n publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>,\n scope: Scope.Scope,\n checkpoint: EDASinkCheckpoint,\n ): EDASinkContext => ({\n sessionId: session.sessionId,\n checkpoint,\n events: eventFactory,\n makeEventId: ids.makeEventId,\n emitEphemeral: publishEphemeral,\n stageDurable: (event) => Effect.sync(() => staged.push(event)),\n forkScoped: (effect) => effect.pipe(Effect.forkIn(scope), Effect.asVoid),\n });\n\n const makeSinkRunner = (sink: EDASink, input: EDASinkRunnerStartInput) =>\n Effect.gen(function* () {\n const sinkName = EDASinkName.make(sink.name);\n const storedCheckpoint = yield* checkpointStore.load(sinkName);\n const checkpointRef = yield* SynchronizedRef.make(storedCheckpoint);\n const checkpoint = makeSinkCheckpoint(checkpointStore, sinkName, checkpointRef);\n const cursor = storedCheckpoint.afterSeq;\n const prefix = yield* readDurablePrefixThrough(store, cursor);\n const state = yield* Ref.make<DurableRunnerState>({\n cursor,\n reduced: reduceCommittedEvents(prefix),\n reducerStates: reducerRegistry.reduce(reducerRegistry.initial, prefix),\n });\n const live = yield* liveBus.subscribeQueue().pipe(Scope.provide(input.scope));\n\n const processDurableBatch = Effect.fnUntraced(function* (\n allEvents: ReadonlyArray<CommittedDurableEvent>,\n ) {\n if (allEvents.length === 0) {\n return;\n }\n\n const current = yield* Ref.get(state);\n const fresh = allEvents.filter((entry) => entry.position.seq > current.cursor);\n if (fresh.length === 0) {\n return;\n }\n\n const durable = sink.durable;\n const throughSeq = fresh.at(-1)!.position.seq;\n const nextReduced = foldReducedState(current.reduced, fresh);\n const nextReducerStates = reducerRegistry.reduce(current.reducerStates, fresh);\n const eventsForSink =\n durable === undefined ? [] : filterInterested(fresh, durable.interests);\n\n if (durable !== undefined && eventsForSink.length > 0) {\n yield* Effect.gen(function* () {\n const staged: Array<DurableEventEnvelope> = [];\n yield* durable.process(\n {\n allEvents: fresh,\n events: eventsForSink,\n stateAfter: nextReduced,\n reducerStates: nextReducerStates,\n throughSeq,\n },\n baseContext(staged, input.publishEphemeral, input.scope, checkpoint),\n );\n if (staged.length > 0) {\n yield* annotateEdaSpan({ \"eda.sink.staged_events\": staged.length });\n yield* input.appendDurableBatch(staged);\n }\n }).pipe(\n Effect.withSpan(\"agent.sink.drain\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.sink.cursor.before\": current.cursor,\n \"eda.sink.events.read\": fresh.length,\n \"eda.sink.events.interested\": eventsForSink.length,\n \"eda.sink.cursor.after\": throughSeq,\n },\n }),\n );\n }\n\n yield* commitSinkCheckpoint(checkpointStore, sinkName, checkpointRef, throughSeq);\n yield* Ref.set(state, {\n cursor: throughSeq,\n reduced: nextReduced,\n reducerStates: nextReducerStates,\n });\n });\n\n const processDurableBatchWithRetry = (events: ReadonlyArray<CommittedDurableEvent>) =>\n keepAlive.withActiveWork(\n `sink:${sink.name}`,\n processDurableBatch(events).pipe(\n Effect.tapError((error) =>\n Effect.logWarning(\"EDA sink durable projection failed; retrying\", {\n error: formatSinkError(error),\n sink: sink.name,\n }),\n ),\n Effect.retry(durableSinkRetrySchedule),\n ),\n );\n\n const drainDurablesThrough = (targetHead: SequenceNumber) =>\n Effect.gen(function* () {\n while (true) {\n const current = yield* Ref.get(state);\n if (current.cursor >= targetHead) {\n return;\n }\n const allEvents = yield* readCursorBatchThrough(\n store,\n current.cursor,\n targetHead,\n sink.durable?.batchSize,\n );\n if (allEvents.length === 0) {\n return;\n }\n yield* processDurableBatchWithRetry(allEvents);\n }\n });\n\n const processLiveDurable = (event: PositionedEvent) =>\n Effect.gen(function* () {\n const current = yield* Ref.get(state);\n if (event.position.seq <= current.cursor) {\n return;\n }\n if (event.position.seq > current.cursor + 1) {\n yield* drainDurablesThrough(SequenceNumber.make(event.position.seq - 1));\n }\n const afterCatchup = yield* Ref.get(state);\n if (event.position.seq > afterCatchup.cursor + 1) {\n yield* Effect.logWarning(\"EDA sink runner could not catch up before live durable\", {\n cursor: afterCatchup.cursor,\n eventSeq: event.position.seq,\n sink: sink.name,\n });\n return;\n }\n yield* processDurableBatchWithRetry([committedDurableFromPositioned(event)]);\n });\n\n const processLiveEphemeral = (event: PositionedEvent) =>\n Effect.gen(function* () {\n const before = yield* Ref.get(state);\n if (event.position.seq < before.cursor) {\n return;\n }\n if (event.position.seq > before.cursor) {\n yield* drainDurablesThrough(event.position.seq);\n }\n const after = yield* Ref.get(state);\n if (event.position.seq !== after.cursor) {\n return;\n }\n if (\n sink.ephemeral === undefined ||\n !matchesInterest(event.event.type, sink.ephemeral.interests)\n ) {\n return;\n }\n yield* sink.ephemeral\n .process(event, baseContext([], input.publishEphemeral, input.scope, checkpoint))\n .pipe(\n Effect.catchCause((cause) =>\n Effect.logError(\"EDA sink ephemeral projection failed\", {\n cause: String(cause),\n sink: sink.name,\n }),\n ),\n );\n });\n\n const processLiveEvent = (event: PositionedEvent) =>\n event.event.durability === \"durable\"\n ? processLiveDurable(event)\n : processLiveEphemeral(event);\n\n const runLoop = Effect.gen(function* () {\n yield* drainDurablesThrough(input.initialHead);\n yield* Effect.forever(\n Effect.gen(function* () {\n const event = yield* PubSub.take(live);\n yield* processLiveEvent(event);\n }),\n );\n }).pipe(\n Effect.catchCause((cause) =>\n Effect.logError(\"EDA sink runner failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n\n yield* runLoop.pipe(Effect.forkIn(input.scope));\n });\n\n return {\n sinks,\n startSinkRunners: Effect.fnUntraced(function* (input: EDASinkRunnerStartInput) {\n const wasStarted = yield* Ref.getAndSet(started, true);\n if (wasStarted) {\n return;\n }\n yield* Effect.forEach(sinks, (sink) => makeSinkRunner(sink, input), {\n discard: true,\n concurrency: \"unbounded\",\n });\n }),\n notifyDurableHeadAdvanced: () => Effect.void,\n publishEphemeralToSinks: () => Effect.void,\n } satisfies EDASinkRegistryShape;\n });\n\nconst readDurablePrefixThrough = (store: EDASessionStoreShape, throughSeq: SequenceNumber) => {\n if (throughSeq <= SequenceNumber.make(0)) {\n return Effect.succeed([]);\n }\n return store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((event) => event.position.seq <= throughSeq),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n};\n\nconst makeSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n): EDASinkCheckpoint => ({\n get: (schema, initial) =>\n SynchronizedRef.get(checkpointRef).pipe(\n Effect.flatMap((checkpoint) => {\n const serialized = serializedSinkState(checkpoint.payload);\n return serialized === undefined\n ? Effect.succeed(initial)\n : decodeSinkState(schema, serialized.state);\n }),\n ),\n save: (schema, state) =>\n encodeSinkState(schema, state).pipe(\n Effect.flatMap((encoded) => {\n const payload: SerializedSinkState = {\n formatVersion: sinkCheckpointFormatVersion,\n state: encoded,\n updatedAtMs: Date.now(),\n };\n return SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.saveState(sinkName, payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq: checkpoint.afterSeq,\n payload,\n },\n ] as const),\n ),\n );\n }),\n ),\n});\n\nconst commitSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n afterSeq: SequenceNumber,\n): Effect.Effect<void, EDASessionStoreError> =>\n SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.commit(sinkName, afterSeq, checkpoint.payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq,\n payload: checkpoint.payload,\n },\n ] as const),\n ),\n );\n\nconst serializedSinkState = (payload: unknown): SerializedSinkState | undefined => {\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n !(\"formatVersion\" in payload) ||\n payload.formatVersion !== sinkCheckpointFormatVersion ||\n !(\"state\" in payload) ||\n !(\"updatedAtMs\" in payload) ||\n typeof payload.updatedAtMs !== \"number\"\n ) {\n return undefined;\n }\n return {\n formatVersion: sinkCheckpointFormatVersion,\n state: payload.state,\n updatedAtMs: payload.updatedAtMs,\n };\n};\n\nconst decodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n encoded: unknown,\n): Effect.Effect<State, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(encoded),\n catch: (cause) => sinkCheckpointCodecError(\"decoding\", cause),\n });\n\nconst encodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n): Effect.Effect<unknown, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.encodeUnknownSync(schema)(state),\n catch: (cause) => sinkCheckpointCodecError(\"encoding\", cause),\n });\n\nconst sinkCheckpointCodecError = (operation: string, cause: unknown) =>\n new EDASessionStoreError({\n message:\n cause instanceof Error\n ? `${operation} sink checkpoint: ${cause.message}`\n : `${operation} sink checkpoint: ${String(cause)}`,\n });\n\nconst readCursorBatchThrough = (\n store: EDASessionStoreShape,\n afterSeq: SequenceNumber,\n throughSeq: SequenceNumber,\n batchSize = defaultBatchSize,\n) =>\n store.eventsAfter(afterSeq).pipe(\n Stream.takeWhile((event) => event.position.seq <= throughSeq),\n Stream.take(batchSize),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n\nconst committedDurableFromPositioned = (event: PositionedEvent): CommittedDurableEvent =>\n CommittedDurableEvent.make({\n event: event.event as DurableEventEnvelope,\n position: durablePosition(event.position.seq),\n });\n\nconst filterInterested = (\n events: ReadonlyArray<CommittedDurableEvent>,\n interests: ReadonlyArray<EventType | string> | undefined,\n): ReadonlyArray<CommittedDurableEvent> =>\n events.filter((event) => matchesInterest(event.event.type, interests));\n\nconst matchesInterest = (\n type: EventType | string,\n interests: ReadonlyArray<EventType | string> | undefined,\n): boolean => interests === undefined || interests.some((interest) => interest === type);\n\nconst formatSinkError = (error: unknown): string => {\n if (Cause.isUnknownError(error)) {\n return `${error.message ?? error._tag}: ${formatSinkError(error.cause)}`;\n }\n return error instanceof Error ? error.message : String(error);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,oCAAoC;;AAuBjD,IAAa,eAAb,MAAa,qBAAqB,QAAQ,QAAyC,EACjF,oCACF,EAAE;CACA,OAAgB,OAAO,MAAM,OAC3B,cACA,OAAO,IAAI,aAAa;EAStB,OAAO,YAAY,OARG,OAAO,eAC3B,OAAO,UAA2B,GAClC,OAAO,QACT,GAK2B,OAJK,IAAI,KAAgC;GAClE,QAAQ,CAAC;GACT,YAAY;EACd,CAAC,CAC0C;CAC7C,CAAC,CACH;AACF;AAEA,MAAM,eACJ,QACA,sBACuB;CACvB,UAAU,UACR,uBAAuB,kBAAkB,KAAK,EAAE,KAC9C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,OACA,UACA,YACA,YAAY,qBAEZ,MAAM,YAAY,QAAQ,EAAE,KAC1B,OAAO,WAAW,UAAU,MAAM,SAAS,OAAO,UAAU,GAC5D,OAAO,KAAK,SAAS,GACrB,OAAO,YACP,OAAO,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAC3C;AAEF,MAAM,kCAAkC,UACtC,sBAAsB,KAAK;CACzB,OAAO,MAAM;CACb,UAAU,gBAAgB,MAAM,SAAS,GAAG;AAC9C,CAAC;AAEH,MAAM,oBACJ,QACA,cAEA,OAAO,QAAQ,UAAU,gBAAgB,MAAM,MAAM,MAAM,SAAS,CAAC;AAEvE,MAAM,mBACJ,MACA,cACY,cAAc,KAAA,KAAa,UAAU,MAAM,aAAa,aAAa,IAAI;AAEvF,MAAM,mBAAmB,UAA2B;CAClD,IAAI,MAAM,eAAe,KAAK,GAC5B,OAAO,GAAG,MAAM,WAAW,MAAM,KAAK,IAAI,gBAAgB,MAAM,KAAK;CAEvE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D"}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { c as EventId, h as SessionId, m as SequenceNumber, y as TurnId } from "./core-Hv3cFydL.js";
|
|
2
|
+
import { D as DurableEventEnvelope, L as PositionedEvent, M as EventType, O as EphemeralEventEnvelope } from "./events-Bb9-Cu-7.js";
|
|
3
|
+
import { a as EDASessionStore, o as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-D2Ore1QC.js";
|
|
4
|
+
import { S as ReducedState } from "./command-queues-CQ9cwRP7.js";
|
|
5
|
+
import { i as EDAReducerStateSnapshot, n as EDAReducerRegistry } from "./reducer-registry-C0svUa63.js";
|
|
6
|
+
import { t as IdGenerator } from "./id-generator-C2Q15uZM.js";
|
|
7
|
+
import { i as SessionContext, n as EventFactory, r as EventFactoryShape, t as EDAKeepAlive } from "./keep-alive-DYDsH6qN.js";
|
|
8
|
+
import * as Context from "effect/Context";
|
|
9
|
+
import * as Effect from "effect/Effect";
|
|
10
|
+
import * as Layer from "effect/Layer";
|
|
11
|
+
import * as Schema from "effect/Schema";
|
|
12
|
+
import * as Stream from "effect/Stream";
|
|
13
|
+
import * as Scope from "effect/Scope";
|
|
14
|
+
import * as PubSub from "effect/PubSub";
|
|
15
|
+
|
|
16
|
+
//#region src/services/live-event-bus.d.ts
|
|
17
|
+
/** Live-only replay buffer for the currently open turn. */
|
|
18
|
+
interface ActiveTurnEphemeralReplay {
|
|
19
|
+
readonly turnId?: TurnId;
|
|
20
|
+
readonly events: ReadonlyArray<PositionedEvent>;
|
|
21
|
+
readonly overflowed: boolean;
|
|
22
|
+
}
|
|
23
|
+
/** In-memory live fanout plus active-turn replay source for reconnect streams. */
|
|
24
|
+
interface LiveEventBusShape {
|
|
25
|
+
readonly publish: (event: PositionedEvent) => Effect.Effect<boolean>;
|
|
26
|
+
readonly subscribe: () => Effect.Effect<Stream.Stream<PositionedEvent>, never, Scope.Scope>;
|
|
27
|
+
readonly subscribeQueue: () => Effect.Effect<PubSub.Subscription<PositionedEvent>, never, Scope.Scope>;
|
|
28
|
+
/** Snapshot raw live-only events retained for the currently open turn. */
|
|
29
|
+
readonly activeTurnReplay: () => Effect.Effect<ActiveTurnEphemeralReplay>;
|
|
30
|
+
}
|
|
31
|
+
declare const LiveEventBus_base: Context.ServiceClass<LiveEventBus, "@effect-durable-agent/LiveEventBus", LiveEventBusShape>;
|
|
32
|
+
/** Unbounded in-memory fanout plus bounded active-turn ephemeral replay. */
|
|
33
|
+
declare class LiveEventBus extends LiveEventBus_base {
|
|
34
|
+
static readonly Live: Layer.Layer<LiveEventBus, never, never>;
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
//#region src/services/sink-checkpoint-store.d.ts
|
|
38
|
+
/** Stable sink name used as the durable checkpoint key. */
|
|
39
|
+
declare const EDASinkName: Schema.brand<Schema.NonEmptyString, "EDASinkName">;
|
|
40
|
+
type EDASinkName = typeof EDASinkName.Type;
|
|
41
|
+
/** Persisted cursor and sink-owned payload for one registered sink. */
|
|
42
|
+
interface StoredSinkCheckpoint {
|
|
43
|
+
readonly afterSeq: SequenceNumber;
|
|
44
|
+
readonly payload: unknown | undefined;
|
|
45
|
+
}
|
|
46
|
+
/** Durable checkpoint persistence port for at-least-once sink runners. */
|
|
47
|
+
interface SinkCheckpointStoreShape {
|
|
48
|
+
/** Read the latest committed cursor and sink-owned payload. */
|
|
49
|
+
readonly load: (sinkName: EDASinkName) => Effect.Effect<StoredSinkCheckpoint, EDASessionStoreError>;
|
|
50
|
+
/** Save sink-owned state without advancing the durable cursor. */
|
|
51
|
+
readonly saveState: (sinkName: EDASinkName, payload: unknown) => Effect.Effect<void, EDASessionStoreError>;
|
|
52
|
+
/** Atomically commit the processed cursor together with current sink-owned state. */
|
|
53
|
+
readonly commit: (sinkName: EDASinkName, afterSeq: SequenceNumber, payload: unknown | undefined) => Effect.Effect<void, EDASessionStoreError>;
|
|
54
|
+
}
|
|
55
|
+
declare const SinkCheckpointStore_base: Context.ServiceClass<SinkCheckpointStore, "@effect-durable-agent/SinkCheckpointStore", SinkCheckpointStoreShape>;
|
|
56
|
+
/**
|
|
57
|
+
* Semantic checkpoint store for registered EDA sinks.
|
|
58
|
+
*
|
|
59
|
+
* Checkpoints are intentionally exposed as load/save/commit operations rather
|
|
60
|
+
* than SQL. Sink side effects happen outside event append transactions, and the
|
|
61
|
+
* cursor advances only after the sink finishes its own external work.
|
|
62
|
+
*/
|
|
63
|
+
declare class SinkCheckpointStore extends SinkCheckpointStore_base {
|
|
64
|
+
/** In-memory checkpoint implementation for store/runtime tests. */
|
|
65
|
+
static readonly InMemory: Layer.Layer<SinkCheckpointStore, never, never>;
|
|
66
|
+
}
|
|
67
|
+
//#endregion
|
|
68
|
+
//#region src/services/sink-registry.d.ts
|
|
69
|
+
/** Cursor-window input delivered to one durable sink drain. */
|
|
70
|
+
interface EDASinkDurableBatch {
|
|
71
|
+
/** All durable events replayed for this cursor window, including uninterested events. */
|
|
72
|
+
readonly allEvents: ReadonlyArray<CommittedDurableEvent>;
|
|
73
|
+
/** Events matching the sink's durable interests. */
|
|
74
|
+
readonly events: ReadonlyArray<CommittedDurableEvent>;
|
|
75
|
+
/** Authoritative reduced state folded exactly through `throughSeq`. */
|
|
76
|
+
readonly stateAfter: ReducedState;
|
|
77
|
+
/** App-specific durable reducer states folded exactly through `throughSeq`. */
|
|
78
|
+
readonly reducerStates: EDAReducerStateSnapshot;
|
|
79
|
+
/** Durable sequence through which the sink may advance after success. */
|
|
80
|
+
readonly throughSeq: SequenceNumber;
|
|
81
|
+
}
|
|
82
|
+
/** Typed, sink-owned durable state stored independently from cursor advancement. */
|
|
83
|
+
interface EDASinkCheckpoint {
|
|
84
|
+
/** Decode current durable state, or return `initial` for a new or legacy cursor row. */
|
|
85
|
+
readonly get: <State>(schema: Schema.Codec<State, unknown, never, never>, initial: State) => Effect.Effect<State, EDASessionStoreError>;
|
|
86
|
+
/** Validate, encode, and durably save state without advancing the sink cursor. */
|
|
87
|
+
readonly save: <State>(schema: Schema.Codec<State, unknown, never, never>, state: State) => Effect.Effect<void, EDASessionStoreError>;
|
|
88
|
+
}
|
|
89
|
+
/** Capabilities exposed to sink processors without granting raw store or bus access. */
|
|
90
|
+
interface EDASinkContext {
|
|
91
|
+
readonly sessionId: SessionId;
|
|
92
|
+
/** Sink-owned checkpoint state, serialized with cursor commits and background writes. */
|
|
93
|
+
readonly checkpoint: EDASinkCheckpoint;
|
|
94
|
+
/** Build a framework durable event if the sink needs to emit one. */
|
|
95
|
+
readonly events: EventFactoryShape;
|
|
96
|
+
/** Mint an app durable event id for staged custom events. */
|
|
97
|
+
readonly makeEventId: () => Effect.Effect<EventId>;
|
|
98
|
+
/** Publish a best-effort live-only event. */
|
|
99
|
+
readonly emitEphemeral: (event: EphemeralEventEnvelope) => Effect.Effect<PositionedEvent, EDASessionStoreError>;
|
|
100
|
+
/** Stage durable events; the runner commits them after the sink succeeds. */
|
|
101
|
+
readonly stageDurable: (event: DurableEventEnvelope) => Effect.Effect<void>;
|
|
102
|
+
/** Fork background sink work into the session scope. */
|
|
103
|
+
readonly forkScoped: (effect: Effect.Effect<unknown, unknown>) => Effect.Effect<void>;
|
|
104
|
+
}
|
|
105
|
+
/** At-least-once sink definition backed by a durable checkpoint. */
|
|
106
|
+
interface EDADurableSinkDefinition {
|
|
107
|
+
readonly interests?: ReadonlyArray<EventType | string>;
|
|
108
|
+
readonly batchSize?: number;
|
|
109
|
+
readonly process: (batch: EDASinkDurableBatch, ctx: EDASinkContext) => Effect.Effect<void, unknown>;
|
|
110
|
+
}
|
|
111
|
+
/** Best-effort live-only sink definition. */
|
|
112
|
+
interface EDAEphemeralSinkDefinition {
|
|
113
|
+
readonly interests?: ReadonlyArray<EventType | string>;
|
|
114
|
+
readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, unknown>;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Named app integration hook with optional durable and ephemeral filters.
|
|
118
|
+
*
|
|
119
|
+
* Every sink runs on one serialized position-ordered lane. Durable callbacks are
|
|
120
|
+
* retried before the sink checkpoint advances; ephemeral callbacks are best-effort
|
|
121
|
+
* and are only processed after the durable prefix at their anchor sequence has
|
|
122
|
+
* been projected.
|
|
123
|
+
*/
|
|
124
|
+
interface EDASink {
|
|
125
|
+
readonly name: string;
|
|
126
|
+
readonly durable?: EDADurableSinkDefinition;
|
|
127
|
+
readonly ephemeral?: EDAEphemeralSinkDefinition;
|
|
128
|
+
}
|
|
129
|
+
/** Convenience constructor preserving a sink's literal name/type information. */
|
|
130
|
+
declare const EDASink: {
|
|
131
|
+
make: <const Sink extends EDASink>(sink: Sink) => Sink;
|
|
132
|
+
};
|
|
133
|
+
/** Session-owned capabilities needed to start all registered sink runners. */
|
|
134
|
+
interface EDASinkRunnerStartInput {
|
|
135
|
+
readonly appendDurableBatch: (events: ReadonlyArray<DurableEventEnvelope>) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;
|
|
136
|
+
readonly initialHead: SequenceNumber;
|
|
137
|
+
readonly publishEphemeral: (event: EphemeralEventEnvelope) => Effect.Effect<PositionedEvent, EDASessionStoreError>;
|
|
138
|
+
readonly scope: Scope.Scope;
|
|
139
|
+
}
|
|
140
|
+
/** Registry service coordinating durable checkpoints and live sink delivery. */
|
|
141
|
+
interface EDASinkRegistryShape {
|
|
142
|
+
readonly sinks: ReadonlyArray<EDASink>;
|
|
143
|
+
/** Start long-lived sink runners. Safe to call once during session-state acquisition. */
|
|
144
|
+
readonly startSinkRunners: (input: EDASinkRunnerStartInput) => Effect.Effect<void, EDASessionStoreError>;
|
|
145
|
+
/** Coalesced non-blocking nudge that the durable log head advanced. */
|
|
146
|
+
readonly notifyDurableHeadAdvanced: (head: SequenceNumber) => Effect.Effect<void>;
|
|
147
|
+
/** Best-effort non-blocking delivery to ephemeral sink workers. */
|
|
148
|
+
readonly publishEphemeralToSinks: (event: PositionedEvent, publishEphemeral: (event: EphemeralEventEnvelope) => Effect.Effect<PositionedEvent, EDASessionStoreError>) => Effect.Effect<void>;
|
|
149
|
+
}
|
|
150
|
+
declare const EDASinkRegistry_base: Context.ServiceClass<EDASinkRegistry, "@effect-durable-agent/EDASinkRegistry", EDASinkRegistryShape>;
|
|
151
|
+
/** Registry and runner for app-provided EDA sinks. */
|
|
152
|
+
declare class EDASinkRegistry extends EDASinkRegistry_base {
|
|
153
|
+
static readonly Empty: Layer.Layer<EDASinkRegistry, never, never>;
|
|
154
|
+
static readonly Live: (sinks: ReadonlyArray<EDASink>) => Layer.Layer<EDASinkRegistry, never, IdGenerator | LiveEventBus | EDASessionStore | EventFactory | EDAKeepAlive | EDAReducerRegistry | SessionContext | SinkCheckpointStore>;
|
|
155
|
+
}
|
|
156
|
+
//#endregion
|
|
157
|
+
export { EDASinkContext as a, EDASinkRegistryShape as c, LiveEventBus as d, EDASinkCheckpoint as i, EDASinkRunnerStartInput as l, EDAEphemeralSinkDefinition as n, EDASinkDurableBatch as o, EDASink as r, EDASinkRegistry as s, EDADurableSinkDefinition as t, SinkCheckpointStore as u };
|
|
158
|
+
//# sourceMappingURL=sink-registry-CIU0LD3m.d.ts.map
|