effect-durable-agent 0.1.0-alpha.5 → 0.1.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{command-queues-Dwdf41mq.d.ts → command-queues-C8muEqeQ.d.ts} +2 -2
- package/dist/{compaction-DpHOf-g7.d.ts → compaction-D7W0-Ur1.d.ts} +4 -4
- package/dist/{context-projection-B4DWOZgi.d.ts → context-projection-C43pyxn2.d.ts} +2 -2
- package/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/context-projection.d.ts +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/reduced-state.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{message-transcript-CFn_D3MH.d.ts → message-transcript-DsKTT47f.d.ts} +3 -3
- package/dist/{prompt-projector-C2meuNrV.d.ts → prompt-projector-hqPh5-NI.d.ts} +4 -4
- package/dist/{reducer-registry-K9FqZq5-.d.ts → reducer-registry--vQFATXb.d.ts} +16 -6
- package/dist/{runtime-5NEJngu3.d.ts → runtime-DXvMCq-J.d.ts} +7 -10
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/reducer-registry.d.ts +2 -2
- package/dist/services/reducer-registry.js +7 -3
- package/dist/services/reducer-registry.js.map +1 -1
- package/dist/services/runtime-layer.d.ts +12 -9
- package/dist/services/runtime-layer.js +6 -4
- package/dist/services/runtime-layer.js.map +1 -1
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +2 -5
- package/dist/services/runtime.js.map +1 -1
- package/dist/services/session-event-observer.d.ts +2 -0
- package/dist/services/session-event-observer.js +13 -0
- package/dist/services/session-event-observer.js.map +1 -0
- package/dist/services/session-query.d.ts +2 -2
- package/dist/services/session-query.js +5 -5
- package/dist/services/session-query.js.map +1 -1
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +1 -1
- package/dist/services/session-store.js +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/span-names.d.ts +1 -1
- package/dist/services/span-names.js +1 -1
- package/dist/services/span-names.js.map +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/services/tracing.js +23 -2
- package/dist/services/tracing.js.map +1 -1
- package/dist/session-event-observer-D_aoFnQs.d.ts +24 -0
- package/dist/{session-query-5oyZRaQL.d.ts → session-query-lUZQpMvM.d.ts} +11 -11
- package/dist/{session-state-CI1xeT6f.d.ts → session-state-Bi3oEbJU.d.ts} +10 -10
- package/dist/{session-state-D7dqko7r.js → session-state-C4m0j6CJ.js} +3 -3
- package/dist/{session-state-D7dqko7r.js.map → session-state-C4m0j6CJ.js.map} +1 -1
- package/dist/{session-store-BLg6UvZa.d.ts → session-store-ofm8FFxs.d.ts} +2 -2
- package/dist/{sink-checkpoint-store-B9WNvDtY.d.ts → sink-checkpoint-store-BQVbI9DQ.d.ts} +2 -2
- package/dist/{sink-registry-CO3YPS1p.d.ts → sink-registry-CE-hL7cB.d.ts} +11 -19
- package/dist/{sink-registry-BbmoI9uv.js → sink-registry-DH6uiEgP.js} +14 -9
- package/dist/sink-registry-DH6uiEgP.js.map +1 -0
- package/dist/testkit/layers.d.ts +10 -10
- package/dist/testkit/layers.js +4 -4
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-B8H1P6Pu.d.ts → tool-registry-ClHdr_G5.d.ts} +2 -2
- package/dist/{websocket-wire-DPxwY4G5.d.ts → websocket.d.ts} +316 -4
- package/dist/websocket.js +497 -0
- package/dist/websocket.js.map +1 -0
- package/package.json +8 -12
- package/dist/host/websocket-protocol.d.ts +0 -252
- package/dist/host/websocket-protocol.js +0 -111
- package/dist/host/websocket-protocol.js.map +0 -1
- package/dist/host/websocket-wire.d.ts +0 -2
- package/dist/host/websocket-wire.js +0 -122
- package/dist/host/websocket-wire.js.map +0 -1
- package/dist/services/websocket-delivery.d.ts +0 -90
- package/dist/services/websocket-delivery.js +0 -221
- package/dist/services/websocket-delivery.js.map +0 -1
- package/dist/sink-registry-BbmoI9uv.js.map +0 -1
|
@@ -1,221 +0,0 @@
|
|
|
1
|
-
import { SequenceNumber } from "../types/core.js";
|
|
2
|
-
import { EDAWebSocketErrorFrame, EDAWebSocketEventsFrame, EDAWebSocketHelloFrame, EDAWebSocketLaggedFrame, EDA_WEB_SOCKET_PROTOCOL_VERSION, EDA_WS_CLOSE_LAGGED, EDA_WS_CLOSE_PROTOCOL_ERROR, FrameId, laggedCloseReason } from "../host/websocket-protocol.js";
|
|
3
|
-
import * as Schema from "effect/Schema";
|
|
4
|
-
//#region src/services/websocket-delivery.ts
|
|
5
|
-
/** Slow subscriber reasons that intentionally close only the lagging socket. */
|
|
6
|
-
const SubscriberLagReason = Schema.Literals(["buffer-overflow", "ack-timeout"]);
|
|
7
|
-
/** Build the delivery state for a new connection or a post-eviction restore. */
|
|
8
|
-
const makeWebSocketDeliveryState = (input) => ({
|
|
9
|
-
subscriberId: input.subscriberId,
|
|
10
|
-
policy: input.policy,
|
|
11
|
-
coldRestored: input.coldRestored ?? false,
|
|
12
|
-
lastAckedSeq: input.resumeSeq,
|
|
13
|
-
lastAckedFrameId: 0,
|
|
14
|
-
lastSentFrameId: 0,
|
|
15
|
-
nextFrameId: 1,
|
|
16
|
-
sentDurableThroughSeq: input.resumeSeq,
|
|
17
|
-
inFlight: [],
|
|
18
|
-
pendingEphemeral: []
|
|
19
|
-
});
|
|
20
|
-
/** First frame for a freshly accepted connection. Cold restores never re-send hello. */
|
|
21
|
-
const deliveryHelloFrame = (state) => EDAWebSocketHelloFrame.make({
|
|
22
|
-
_tag: "hello",
|
|
23
|
-
protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,
|
|
24
|
-
subscriberId: state.subscriberId,
|
|
25
|
-
resumeSeq: state.lastAckedSeq,
|
|
26
|
-
flowControl: state.policy
|
|
27
|
-
});
|
|
28
|
-
/**
|
|
29
|
-
* Deliver committed durable events read from the store.
|
|
30
|
-
*
|
|
31
|
-
* The store is the only buffer for durable events: frames are emitted while
|
|
32
|
-
* the ACK window has room and the remainder is requested again via
|
|
33
|
-
* `wantsCatchUpAfterSeq` once ACKs reopen the window.
|
|
34
|
-
*/
|
|
35
|
-
const onDurableEvents = (state, events, head, nowMs) => {
|
|
36
|
-
const stale = staleAckResult(state, nowMs);
|
|
37
|
-
if (stale !== void 0) return stale;
|
|
38
|
-
let next = state;
|
|
39
|
-
const frames = [];
|
|
40
|
-
let batch = [];
|
|
41
|
-
const flushBatch = () => {
|
|
42
|
-
if (batch.length === 0) return;
|
|
43
|
-
const sent = sendEventsFrame(next, batch, nowMs);
|
|
44
|
-
if (sent.close !== void 0) return {
|
|
45
|
-
...sent,
|
|
46
|
-
frames: [...frames, ...sent.frames]
|
|
47
|
-
};
|
|
48
|
-
next = sent.state;
|
|
49
|
-
frames.push(...sent.frames);
|
|
50
|
-
batch = [];
|
|
51
|
-
};
|
|
52
|
-
for (const event of events) {
|
|
53
|
-
if (event.event.durability === "durable" && event.position.seq <= next.sentDurableThroughSeq) continue;
|
|
54
|
-
if (batch.length === 0 && windowCapacity(next) <= 0) break;
|
|
55
|
-
batch.push(event);
|
|
56
|
-
if (batch.length >= next.policy.maxFrameEvents) {
|
|
57
|
-
const closed = flushBatch();
|
|
58
|
-
if (closed !== void 0) return closed;
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
const closed = flushBatch();
|
|
62
|
-
if (closed !== void 0) return closed;
|
|
63
|
-
return {
|
|
64
|
-
state: next,
|
|
65
|
-
frames,
|
|
66
|
-
...windowCapacity(next) > 0 && next.sentDurableThroughSeq < head ? { wantsCatchUpAfterSeq: next.sentDurableThroughSeq } : {}
|
|
67
|
-
};
|
|
68
|
-
};
|
|
69
|
-
/**
|
|
70
|
-
* Deliver one live ephemeral event.
|
|
71
|
-
*
|
|
72
|
-
* Ephemeral events have no durable backing, so a bounded in-memory buffer
|
|
73
|
-
* holds them while the ACK window is full; overflow lag-closes only this
|
|
74
|
-
* subscriber, mirroring the previous streaming behavior.
|
|
75
|
-
*/
|
|
76
|
-
const onEphemeralEvent = (state, event, nowMs) => {
|
|
77
|
-
const stale = staleAckResult(state, nowMs);
|
|
78
|
-
if (stale !== void 0) return stale;
|
|
79
|
-
if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) return sendEventsFrame(state, [event], nowMs);
|
|
80
|
-
const pendingEphemeral = [...state.pendingEphemeral, event];
|
|
81
|
-
if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) return laggedResult(state, "buffer-overflow");
|
|
82
|
-
return {
|
|
83
|
-
state: {
|
|
84
|
-
...state,
|
|
85
|
-
pendingEphemeral
|
|
86
|
-
},
|
|
87
|
-
frames: []
|
|
88
|
-
};
|
|
89
|
-
};
|
|
90
|
-
/** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */
|
|
91
|
-
const onClientAck = (state, ack, nowMs) => {
|
|
92
|
-
const validated = state.coldRestored ? applyColdAck(state, ack) : applyWarmAck(state, ack);
|
|
93
|
-
if (validated._tag === "close") return validated.result;
|
|
94
|
-
if (validated._tag === "ignore") return {
|
|
95
|
-
state,
|
|
96
|
-
frames: []
|
|
97
|
-
};
|
|
98
|
-
let next = validated.state;
|
|
99
|
-
const frames = [];
|
|
100
|
-
while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {
|
|
101
|
-
const [head, ...rest] = next.pendingEphemeral;
|
|
102
|
-
const sent = sendEventsFrame({
|
|
103
|
-
...next,
|
|
104
|
-
pendingEphemeral: rest
|
|
105
|
-
}, [head], nowMs);
|
|
106
|
-
if (sent.close !== void 0) return {
|
|
107
|
-
...sent,
|
|
108
|
-
frames: [...frames, ...sent.frames],
|
|
109
|
-
persistSeq: validated.persistSeq
|
|
110
|
-
};
|
|
111
|
-
next = sent.state;
|
|
112
|
-
frames.push(...sent.frames);
|
|
113
|
-
}
|
|
114
|
-
const stale = staleAckResult(next, nowMs);
|
|
115
|
-
if (stale !== void 0) return {
|
|
116
|
-
...stale,
|
|
117
|
-
frames: [...frames, ...stale.frames],
|
|
118
|
-
persistSeq: validated.persistSeq
|
|
119
|
-
};
|
|
120
|
-
return {
|
|
121
|
-
state: next,
|
|
122
|
-
frames,
|
|
123
|
-
persistSeq: validated.persistSeq,
|
|
124
|
-
...windowCapacity(next) > 0 && next.pendingEphemeral.length === 0 ? { wantsCatchUpAfterSeq: next.sentDurableThroughSeq } : {}
|
|
125
|
-
};
|
|
126
|
-
};
|
|
127
|
-
const applyWarmAck = (state, ack) => {
|
|
128
|
-
if (ack.frameId <= state.lastAckedFrameId) return ack.durableThroughSeq > state.lastAckedSeq ? protocolClose(state, "Duplicate ACK attempted to advance durable seq") : { _tag: "ignore" };
|
|
129
|
-
if (ack.frameId > state.lastSentFrameId) return protocolClose(state, "ACK referenced an unsent frame");
|
|
130
|
-
if (ack.durableThroughSeq < state.lastAckedSeq) return protocolClose(state, "ACK durable seq moved backwards");
|
|
131
|
-
const acknowledged = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);
|
|
132
|
-
if (acknowledged.length === 0) return protocolClose(state, "ACK referenced no in-flight frames");
|
|
133
|
-
const allowedDurableSeq = SequenceNumber.make(acknowledged.reduce((max, frame) => Math.max(max, frame.durableThroughSeq), state.lastAckedSeq));
|
|
134
|
-
if (ack.durableThroughSeq > allowedDurableSeq) return protocolClose(state, "ACK durable seq exceeded sent frame boundary");
|
|
135
|
-
return {
|
|
136
|
-
_tag: "apply",
|
|
137
|
-
persistSeq: ack.durableThroughSeq,
|
|
138
|
-
state: {
|
|
139
|
-
...state,
|
|
140
|
-
inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),
|
|
141
|
-
lastAckedFrameId: ack.frameId,
|
|
142
|
-
lastAckedSeq: ack.durableThroughSeq
|
|
143
|
-
}
|
|
144
|
-
};
|
|
145
|
-
};
|
|
146
|
-
const applyColdAck = (state, ack) => {
|
|
147
|
-
if (ack.durableThroughSeq < state.lastAckedSeq) return { _tag: "ignore" };
|
|
148
|
-
const lastAckedSeq = SequenceNumber.make(Math.max(state.lastAckedSeq, ack.durableThroughSeq));
|
|
149
|
-
return {
|
|
150
|
-
_tag: "apply",
|
|
151
|
-
persistSeq: lastAckedSeq,
|
|
152
|
-
state: {
|
|
153
|
-
...state,
|
|
154
|
-
inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),
|
|
155
|
-
lastAckedFrameId: Math.max(state.lastAckedFrameId, ack.frameId),
|
|
156
|
-
lastAckedSeq,
|
|
157
|
-
sentDurableThroughSeq: SequenceNumber.make(Math.max(state.sentDurableThroughSeq, lastAckedSeq))
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
};
|
|
161
|
-
const windowCapacity = (state) => state.policy.maxInFlightFrames - state.inFlight.length;
|
|
162
|
-
const sendEventsFrame = (state, events, nowMs) => {
|
|
163
|
-
const frameId = FrameId.make(state.nextFrameId);
|
|
164
|
-
const durableThroughSeq = SequenceNumber.make(events.reduce((max, event) => event.event.durability === "durable" ? Math.max(max, event.position.seq) : max, state.sentDurableThroughSeq));
|
|
165
|
-
const frame = EDAWebSocketEventsFrame.make({
|
|
166
|
-
_tag: "events",
|
|
167
|
-
frameId,
|
|
168
|
-
events,
|
|
169
|
-
durableThroughSeq
|
|
170
|
-
});
|
|
171
|
-
const encodedBytes = new TextEncoder().encode(JSON.stringify(frame)).byteLength;
|
|
172
|
-
if (encodedBytes > state.policy.maxFrameBytes) return protocolClose(state, `Encoded WebSocket frame exceeded maxFrameBytes (${encodedBytes} > ${state.policy.maxFrameBytes})`).result;
|
|
173
|
-
return {
|
|
174
|
-
state: {
|
|
175
|
-
...state,
|
|
176
|
-
inFlight: [...state.inFlight, {
|
|
177
|
-
frameId,
|
|
178
|
-
durableThroughSeq,
|
|
179
|
-
sentAtMs: nowMs
|
|
180
|
-
}],
|
|
181
|
-
lastSentFrameId: frameId,
|
|
182
|
-
nextFrameId: frameId + 1,
|
|
183
|
-
sentDurableThroughSeq: durableThroughSeq
|
|
184
|
-
},
|
|
185
|
-
frames: [frame]
|
|
186
|
-
};
|
|
187
|
-
};
|
|
188
|
-
/** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */
|
|
189
|
-
const staleAckResult = (state, nowMs) => {
|
|
190
|
-
return state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs) ? laggedResult(state, "ack-timeout") : void 0;
|
|
191
|
-
};
|
|
192
|
-
const laggedResult = (state, reason) => ({
|
|
193
|
-
state,
|
|
194
|
-
frames: [EDAWebSocketLaggedFrame.make({
|
|
195
|
-
_tag: "lagged",
|
|
196
|
-
resumeSeq: state.lastAckedSeq,
|
|
197
|
-
reason
|
|
198
|
-
})],
|
|
199
|
-
close: {
|
|
200
|
-
code: EDA_WS_CLOSE_LAGGED,
|
|
201
|
-
reason: laggedCloseReason(state.lastAckedSeq)
|
|
202
|
-
}
|
|
203
|
-
});
|
|
204
|
-
const protocolClose = (state, message) => ({
|
|
205
|
-
_tag: "close",
|
|
206
|
-
result: {
|
|
207
|
-
state,
|
|
208
|
-
frames: [EDAWebSocketErrorFrame.make({
|
|
209
|
-
_tag: "error",
|
|
210
|
-
message: message.slice(0, 120)
|
|
211
|
-
})],
|
|
212
|
-
close: {
|
|
213
|
-
code: EDA_WS_CLOSE_PROTOCOL_ERROR,
|
|
214
|
-
reason: "protocol"
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
});
|
|
218
|
-
//#endregion
|
|
219
|
-
export { SubscriberLagReason, deliveryHelloFrame, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent };
|
|
220
|
-
|
|
221
|
-
//# sourceMappingURL=websocket-delivery.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"websocket-delivery.js","names":[],"sources":["../../src/services/websocket-delivery.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\nimport {\n EDA_WEB_SOCKET_PROTOCOL_VERSION,\n EDA_WS_CLOSE_LAGGED,\n EDA_WS_CLOSE_PROTOCOL_ERROR,\n EDAWebSocketEventsFrame,\n EDAWebSocketErrorFrame,\n EDAWebSocketHelloFrame,\n EDAWebSocketLaggedFrame,\n FrameId,\n SubscriberId,\n laggedCloseReason,\n type EDAWebSocketAckFrame,\n type EDAWebSocketFlowControl,\n type EDAWebSocketServerFrame,\n} from \"../host/websocket-protocol\";\n\n/** Slow subscriber reasons that intentionally close only the lagging socket. */\nexport const SubscriberLagReason = Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]);\nexport type SubscriberLagReason = typeof SubscriberLagReason.Type;\n\n/** One sent-but-unacknowledged events frame. */\nexport interface InFlightFrame {\n readonly frameId: FrameId;\n readonly durableThroughSeq: SequenceNumber;\n readonly sentAtMs: number;\n}\n\n/**\n * In-memory delivery state for one accepted event WebSocket.\n *\n * This state is deliberately disposable: hibernation-capable hosts persist\n * only the acknowledged durable cursor in the socket attachment and rebuild\n * a cold state after isolate eviction. Nothing here owns a fiber, a timer,\n * or a stream; all progress is driven by explicit host calls.\n */\nexport interface EDAWebSocketDeliveryState {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n /**\n * True when this state was rebuilt from a persisted attachment after the\n * in-memory frame bookkeeping was lost. Frame-id validation is relaxed for\n * the remainder of the connection because pre-eviction frame ids are\n * unknowable; durable cursors stay strictly monotonic either way.\n */\n readonly coldRestored: boolean;\n readonly lastAckedSeq: SequenceNumber;\n readonly lastAckedFrameId: number;\n readonly lastSentFrameId: number;\n readonly nextFrameId: number;\n readonly sentDurableThroughSeq: SequenceNumber;\n readonly inFlight: ReadonlyArray<InFlightFrame>;\n readonly pendingEphemeral: ReadonlyArray<PositionedEvent>;\n}\n\n/** Close instruction for the host WebSocket boundary. */\nexport interface DeliveryClose {\n readonly code: number;\n readonly reason: string;\n}\n\n/** Result of one pure delivery transition. */\nexport interface EDAWebSocketDeliveryResult {\n readonly state: EDAWebSocketDeliveryState;\n /** Frames to send in order, including any final lagged/error frame before `close`. */\n readonly frames: ReadonlyArray<EDAWebSocketServerFrame>;\n /** When set, persist this acknowledged durable cursor to the socket attachment. */\n readonly persistSeq?: SequenceNumber;\n /** When set, send `frames` then close the socket and drop its state. */\n readonly close?: DeliveryClose;\n /** When set, the host should read a durable slice after this seq and call `onDurableEvents`. */\n readonly wantsCatchUpAfterSeq?: SequenceNumber;\n}\n\n/** Inputs for one fresh or cold-restored delivery state. */\nexport interface MakeDeliveryStateInput {\n readonly subscriberId: SubscriberId;\n readonly resumeSeq: SequenceNumber;\n readonly policy: EDAWebSocketFlowControl;\n readonly coldRestored?: boolean;\n}\n\n/** Build the delivery state for a new connection or a post-eviction restore. */\nexport const makeWebSocketDeliveryState = (\n input: MakeDeliveryStateInput,\n): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n coldRestored: input.coldRestored ?? false,\n lastAckedSeq: input.resumeSeq,\n lastAckedFrameId: 0,\n lastSentFrameId: 0,\n nextFrameId: 1,\n sentDurableThroughSeq: input.resumeSeq,\n inFlight: [],\n pendingEphemeral: [],\n});\n\n/** First frame for a freshly accepted connection. Cold restores never re-send hello. */\nexport const deliveryHelloFrame = (state: EDAWebSocketDeliveryState): EDAWebSocketHelloFrame =>\n EDAWebSocketHelloFrame.make({\n _tag: \"hello\",\n protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,\n subscriberId: state.subscriberId,\n resumeSeq: state.lastAckedSeq,\n flowControl: state.policy,\n });\n\n/**\n * Deliver committed durable events read from the store.\n *\n * The store is the only buffer for durable events: frames are emitted while\n * the ACK window has room and the remainder is requested again via\n * `wantsCatchUpAfterSeq` once ACKs reopen the window.\n */\nexport const onDurableEvents = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n head: SequenceNumber,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) {\n return stale;\n }\n\n let next = state;\n const frames: EDAWebSocketServerFrame[] = [];\n let batch: PositionedEvent[] = [];\n\n const flushBatch = (): EDAWebSocketDeliveryResult | undefined => {\n if (batch.length === 0) {\n return undefined;\n }\n const sent = sendEventsFrame(next, batch, nowMs);\n if (sent.close !== undefined) {\n return { ...sent, frames: [...frames, ...sent.frames] };\n }\n next = sent.state;\n frames.push(...sent.frames);\n batch = [];\n return undefined;\n };\n\n for (const event of events) {\n if (event.event.durability === \"durable\" && event.position.seq <= next.sentDurableThroughSeq) {\n continue;\n }\n if (batch.length === 0 && windowCapacity(next) <= 0) {\n break;\n }\n batch.push(event);\n if (batch.length >= next.policy.maxFrameEvents) {\n const closed = flushBatch();\n if (closed !== undefined) {\n return closed;\n }\n }\n }\n const closed = flushBatch();\n if (closed !== undefined) {\n return closed;\n }\n\n return {\n state: next,\n frames,\n ...(windowCapacity(next) > 0 && next.sentDurableThroughSeq < head\n ? { wantsCatchUpAfterSeq: next.sentDurableThroughSeq }\n : {}),\n };\n};\n\n/**\n * Deliver one live ephemeral event.\n *\n * Ephemeral events have no durable backing, so a bounded in-memory buffer\n * holds them while the ACK window is full; overflow lag-closes only this\n * subscriber, mirroring the previous streaming behavior.\n */\nexport const onEphemeralEvent = (\n state: EDAWebSocketDeliveryState,\n event: PositionedEvent,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) {\n return stale;\n }\n\n if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) {\n return sendEventsFrame(state, [event], nowMs);\n }\n\n const pendingEphemeral = [...state.pendingEphemeral, event];\n if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) {\n return laggedResult(state, \"buffer-overflow\");\n }\n return { state: { ...state, pendingEphemeral }, frames: [] };\n};\n\n/** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */\nexport const onClientAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const validated = state.coldRestored ? applyColdAck(state, ack) : applyWarmAck(state, ack);\n if (validated._tag === \"close\") {\n return validated.result;\n }\n if (validated._tag === \"ignore\") {\n return { state, frames: [] };\n }\n\n let next = validated.state;\n const frames: EDAWebSocketServerFrame[] = [];\n while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {\n const [head, ...rest] = next.pendingEphemeral;\n const sent = sendEventsFrame({ ...next, pendingEphemeral: rest }, [head!], nowMs);\n if (sent.close !== undefined) {\n return {\n ...sent,\n frames: [...frames, ...sent.frames],\n persistSeq: validated.persistSeq,\n };\n }\n next = sent.state;\n frames.push(...sent.frames);\n }\n\n const stale = staleAckResult(next, nowMs);\n if (stale !== undefined) {\n return { ...stale, frames: [...frames, ...stale.frames], persistSeq: validated.persistSeq };\n }\n\n return {\n state: next,\n frames,\n persistSeq: validated.persistSeq,\n ...(windowCapacity(next) > 0 && next.pendingEphemeral.length === 0\n ? { wantsCatchUpAfterSeq: next.sentDurableThroughSeq }\n : {}),\n };\n};\n\ntype AckValidation =\n | { readonly _tag: \"ignore\" }\n | { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult }\n | {\n readonly _tag: \"apply\";\n readonly state: EDAWebSocketDeliveryState;\n readonly persistSeq: SequenceNumber;\n };\n\nconst applyWarmAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n): AckValidation => {\n if (ack.frameId <= state.lastAckedFrameId) {\n return ack.durableThroughSeq > state.lastAckedSeq\n ? protocolClose(state, \"Duplicate ACK attempted to advance durable seq\")\n : { _tag: \"ignore\" };\n }\n if (ack.frameId > state.lastSentFrameId) {\n return protocolClose(state, \"ACK referenced an unsent frame\");\n }\n if (ack.durableThroughSeq < state.lastAckedSeq) {\n return protocolClose(state, \"ACK durable seq moved backwards\");\n }\n const acknowledged = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);\n if (acknowledged.length === 0) {\n return protocolClose(state, \"ACK referenced no in-flight frames\");\n }\n const allowedDurableSeq = SequenceNumber.make(\n acknowledged.reduce<number>(\n (max, frame) => Math.max(max, frame.durableThroughSeq),\n state.lastAckedSeq,\n ),\n );\n if (ack.durableThroughSeq > allowedDurableSeq) {\n return protocolClose(state, \"ACK durable seq exceeded sent frame boundary\");\n }\n return {\n _tag: \"apply\",\n persistSeq: ack.durableThroughSeq,\n state: {\n ...state,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n lastAckedFrameId: ack.frameId,\n lastAckedSeq: ack.durableThroughSeq,\n },\n };\n};\n\nconst applyColdAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n): AckValidation => {\n // Pre-eviction frame ids are unknowable, so only durable-cursor monotonicity\n // is enforced; stale re-ACKs are ignored instead of protocol-closed.\n if (ack.durableThroughSeq < state.lastAckedSeq) {\n return { _tag: \"ignore\" };\n }\n const lastAckedSeq = SequenceNumber.make(Math.max(state.lastAckedSeq, ack.durableThroughSeq));\n return {\n _tag: \"apply\",\n persistSeq: lastAckedSeq,\n state: {\n ...state,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n lastAckedFrameId: Math.max(state.lastAckedFrameId, ack.frameId),\n lastAckedSeq,\n // A late ACK can prove delivery beyond what this cold state has sent;\n // never re-send durable events the client has already acknowledged.\n sentDurableThroughSeq: SequenceNumber.make(\n Math.max(state.sentDurableThroughSeq, lastAckedSeq),\n ),\n },\n };\n};\n\nconst windowCapacity = (state: EDAWebSocketDeliveryState): number =>\n state.policy.maxInFlightFrames - state.inFlight.length;\n\nconst sendEventsFrame = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const frameId = FrameId.make(state.nextFrameId);\n const durableThroughSeq = SequenceNumber.make(\n events.reduce<number>(\n (max, event) =>\n event.event.durability === \"durable\" ? Math.max(max, event.position.seq) : max,\n state.sentDurableThroughSeq,\n ),\n );\n const frame = EDAWebSocketEventsFrame.make({\n _tag: \"events\",\n frameId,\n events: events as [PositionedEvent, ...PositionedEvent[]],\n durableThroughSeq,\n });\n const encodedBytes = new TextEncoder().encode(JSON.stringify(frame)).byteLength;\n if (encodedBytes > state.policy.maxFrameBytes) {\n const close = protocolClose(\n state,\n `Encoded WebSocket frame exceeded maxFrameBytes (${encodedBytes} > ${state.policy.maxFrameBytes})`,\n );\n return close.result;\n }\n return {\n state: {\n ...state,\n inFlight: [...state.inFlight, { frameId, durableThroughSeq, sentAtMs: nowMs }],\n lastSentFrameId: frameId,\n nextFrameId: frameId + 1,\n sentDurableThroughSeq: durableThroughSeq,\n },\n frames: [frame],\n };\n};\n\n/** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */\nconst staleAckResult = (\n state: EDAWebSocketDeliveryState,\n nowMs: number,\n): EDAWebSocketDeliveryResult | undefined => {\n const overdue = state.inFlight.some(\n (frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs,\n );\n return overdue ? laggedResult(state, \"ack-timeout\") : undefined;\n};\n\nconst laggedResult = (\n state: EDAWebSocketDeliveryState,\n reason: SubscriberLagReason,\n): EDAWebSocketDeliveryResult => ({\n state,\n frames: [\n EDAWebSocketLaggedFrame.make({\n _tag: \"lagged\",\n resumeSeq: state.lastAckedSeq,\n reason,\n }),\n ],\n close: { code: EDA_WS_CLOSE_LAGGED, reason: laggedCloseReason(state.lastAckedSeq) },\n});\n\nconst protocolClose = (\n state: EDAWebSocketDeliveryState,\n message: string,\n): { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult } => ({\n _tag: \"close\",\n result: {\n state,\n frames: [EDAWebSocketErrorFrame.make({ _tag: \"error\", message: message.slice(0, 120) })],\n close: { code: EDA_WS_CLOSE_PROTOCOL_ERROR, reason: \"protocol\" },\n },\n});\n"],"mappings":";;;;;AAqBA,M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,MAAM;EACjB;CACF,CAAC,CACH;CACA,OAAO;EAAE,MAAM;EAAqB,QAAQ,kBAAkB,MAAM,YAAY;CAAE;AACpF;AAEA,MAAM,iBACJ,OACA,aAC6E;CAC7E,MAAM;CACN,QAAQ;EACN;EACA,QAAQ,CAAC,uBAAuB,KAAK;GAAE,MAAM;GAAS,SAAS,QAAQ,MAAM,GAAG,GAAG;EAAE,CAAC,CAAC;EACvF,OAAO;GAAE,MAAM;GAA6B,QAAQ;EAAW;CACjE;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sink-registry-BbmoI9uv.js","names":[],"sources":["../src/services/live-event-bus.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/**\n * Push-delivery listener invoked inline as each event is published.\n *\n * Listeners let hibernation-capable hosts fan events out to accepted\n * WebSockets during the already-active turn instead of parking a resident\n * subscriber fiber on the pub/sub. Listeners must not fail; defects are\n * logged and never interrupt the publishing turn.\n */\nexport type LiveDeliveryListener = (event: PositionedEvent) => Effect.Effect<void>;\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 /** Register one push-delivery listener invoked inline on every published event. */\n readonly registerDeliveryListener: (listener: LiveDeliveryListener) => Effect.Effect<void>;\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 const listeners = yield* Ref.make<ReadonlyArray<LiveDeliveryListener>>([]);\n return makeLiveBus(pubsub, activeTurnReplay, listeners);\n }),\n );\n}\n\nconst makeLiveBus = (\n pubsub: PubSub.PubSub<PositionedEvent>,\n activeTurnReplay: Ref.Ref<ActiveTurnEphemeralReplay>,\n listeners: Ref.Ref<ReadonlyArray<LiveDeliveryListener>>,\n): LiveEventBusShape => ({\n publish: (event) =>\n updateActiveTurnReplay(activeTurnReplay, event).pipe(\n Effect.andThen(notifyDeliveryListeners(listeners, event)),\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 registerDeliveryListener: (listener) =>\n Ref.update(listeners, (current) => [...current, listener]),\n});\n\nconst notifyDeliveryListeners = (\n listeners: Ref.Ref<ReadonlyArray<LiveDeliveryListener>>,\n event: PositionedEvent,\n): Effect.Effect<void> =>\n Ref.get(listeners).pipe(\n Effect.flatMap((current) =>\n Effect.forEach(\n current,\n (listener) =>\n listener(event).pipe(\n Effect.catchCause((cause) =>\n Effect.logWarning(\"EDA live delivery listener defected\", cause),\n ),\n ),\n { discard: true },\n ),\n ),\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 Cause from \"effect/Cause\";\nimport * 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 * 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/** Durable sink definition backed by a checkpoint and an app-owned delivery policy. */\nexport interface EDADurableSinkDefinition {\n readonly interests?: ReadonlyArray<EventType | string>;\n readonly batchSize?: number;\n readonly process: (batch: EDASinkDurableBatch, ctx: EDASinkContext) => Effect.Effect<void, never>;\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, never>;\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. Sinks own retry and\n * terminal failure handling, so callbacks must have an infallible typed error\n * channel. An unexpected defect is logged and skipped before the durable checkpoint\n * advances. Ephemeral callbacks are best-effort and are only processed after the\n * durable prefix at their anchor sequence has 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 sinkCheckpointFormatVersion = 1;\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 const completed = yield* durable\n .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 .pipe(\n Effect.as(true),\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA durable sink violated its infallible contract\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }).pipe(Effect.as(false)),\n ),\n );\n if (completed && 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 processDurableBatchWithKeepAlive = (events: ReadonlyArray<CommittedDurableEvent>) =>\n keepAlive.withActiveWork(`sink:${sink.name}`, processDurableBatch(events));\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* processDurableBatchWithKeepAlive(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* processDurableBatchWithKeepAlive([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 return 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,oCAAoC;;AAmCjD,IAAa,eAAb,MAAa,qBAAqB,QAAQ,QAAyC,EACjF,oCACF,EAAE;CACA,OAAgB,OAAO,MAAM,OAC3B,cACA,OAAO,IAAI,aAAa;EAUtB,OAAO,YAAY,OATG,OAAO,eAC3B,OAAO,UAA2B,GAClC,OAAO,QACT,GAM2B,OALK,IAAI,KAAgC;GAClE,QAAQ,CAAC;GACT,YAAY;EACd,CAAC,GAE4C,OADpB,IAAI,KAA0C,CAAC,CAAC,CACnB;CACxD,CAAC,CACH;AACF;AAEA,MAAM,eACJ,QACA,kBACA,eACuB;CACvB,UAAU,UACR,uBAAuB,kBAAkB,KAAK,EAAE,KAC9C,OAAO,QAAQ,wBAAwB,WAAW,KAAK,CAAC,GACxD,OAAO,QAAQ,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAC9C;CACF,sBAAsB,OAAO,UAAU,MAAM;CAC7C,iBACE,OAAO,IAAI,OAAO,UAAU,MAAM,IAAI,iBACpC,OAAO,iBAAiB,OAAO,KAAK,YAAY,CAAC,CACnD;CACF,wBAAwB,IAAI,IAAI,gBAAgB;CAChD,2BAA2B,aACzB,IAAI,OAAO,YAAY,YAAY,CAAC,GAAG,SAAS,QAAQ,CAAC;AAC7D;AAEA,MAAM,2BACJ,WACA,UAEA,IAAI,IAAI,SAAS,EAAE,KACjB,OAAO,SAAS,YACd,OAAO,QACL,UACC,aACC,SAAS,KAAK,EAAE,KACd,OAAO,YAAY,UACjB,OAAO,WAAW,uCAAuC,KAAK,CAChE,CACF,GACF,EAAE,SAAS,KAAK,CACl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