effect-durable-agent 0.1.0-alpha.24 → 0.1.0-alpha.25

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/websocket.js CHANGED
@@ -1,510 +1,9 @@
1
- import { Position, SequenceNumber } from "./types/core.js";
2
- import { d as PositionedEvent, g as UnixEpochMillis, i as EventEnvelope } from "./envelope-BCzKUq_z.js";
3
- import { U as EDADurableEvent } from "./durable-CD__3ztN.js";
4
- import { EDAEphemeralEvent } from "./types/events.js";
1
+ import { SequenceNumber } from "./types/core.js";
5
2
  import { E as TranscriptOrder, _ as TranscriptCursor } from "./records-DWKEjuqb.js";
6
- import { c as transcriptCoverageOf, i as TranscriptUpdate, n as TranscriptRequestId, r as TranscriptSubscriptionBase, t as TranscriptCoverage } from "./subscription-g5W0Ggqx.js";
7
- import * as Effect from "effect/Effect";
3
+ import { c as transcriptCoverageOf, i as TranscriptUpdate, n as TranscriptRequestId, r as TranscriptSubscriptionBase, t as TranscriptCoverage } from "./subscription-Dzr5LqPX.js";
4
+ import { A as FrameId, B as EDAWebSocketWireFlowControl, C as EDAWebSocketServerFrame, D as EDA_WS_CLOSE_PROTOCOL_ERROR, E as EDA_WS_CLOSE_LAGGED, F as laggedCloseReason, G as EDAWebSocketWirePongFrame, H as EDAWebSocketWireHelloFrame, I as EDAFrameworkWebSocketEvent, J as EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION, K as EDA_WEB_SOCKET_PING_MESSAGE, L as EDAWebSocketWireAckFrame, M as decodeEDAWebSocketClientMessage, N as defaultEDAWebSocketFlowControl, O as EDA_WS_CLOSE_SEND_FAILED, P as encodeEDAWebSocketServerFrame, R as EDAWebSocketWireClientFrame, S as EDAWebSocketPongFrame, T as EDA_WS_CLOSE_GOING_AWAY, U as EDAWebSocketWireLaggedFrame, V as EDAWebSocketWireHeartbeatFrame, W as EDAWebSocketWirePingFrame, X as makeEDAWebSocketWireProtocol, Y as edaFrameworkWebSocketWireProtocol, _ as EDAWebSocketFlowControl, a as checkpointWebSocketDeliveryState, b as EDAWebSocketLaggedFrame, c as onClientAck, d as onHostSuppressedFrame, f as restoreWebSocketDeliveryState, g as EDAWebSocketEventsFrame, h as EDAWebSocketErrorFrame, i as SubscriberLagReason, j as SubscriberId, k as EDA_WS_CLOSE_UNSUPPORTED_DATA, l as onDurableEvents, m as EDAWebSocketClientFrame, n as EDAWebSocketInFlightFrame, o as deliveryHelloFrame, p as EDAWebSocketAckFrame, q as EDA_WEB_SOCKET_PONG_MESSAGE, r as EDAWebSocketSuppressedRange, s as makeWebSocketDeliveryState, t as EDAWebSocketDeliveryCheckpoint, u as onEphemeralEvent, v as EDAWebSocketHeartbeatFrame, w as EDA_WEB_SOCKET_PROTOCOL_VERSION, x as EDAWebSocketPingFrame, y as EDAWebSocketHelloFrame, z as EDAWebSocketWireErrorFrame } from "./delivery-Bb7pkQ9o.js";
8
5
  import * as Schema from "effect/Schema";
9
6
  import * as Exit from "effect/Exit";
10
- //#region src/websocket/protocol.ts
11
- const PositiveInt$2 = Schema.Int.check(Schema.isGreaterThan(0));
12
- const NonNegativeInt$2 = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
13
- /** Current EDA live-event WebSocket wire protocol version. */
14
- const EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION = 1;
15
- /** Flow-control policy announced by the server in the hello frame. */
16
- const EDAWebSocketWireFlowControl = Schema.Struct({
17
- ackTimeoutMs: PositiveInt$2,
18
- /** Deprecated: servers no longer send heartbeat frames. Kept so deployed clients can decode hello. */
19
- heartbeatIntervalMs: PositiveInt$2,
20
- maxFrameBytes: PositiveInt$2,
21
- maxFrameEvents: PositiveInt$2,
22
- maxInFlightFrames: PositiveInt$2,
23
- /** Suggested client-originated ping cadence; absent on servers that still send heartbeats. */
24
- pingIntervalMs: Schema.optionalKey(PositiveInt$2),
25
- subscriberBufferCapacityEvents: PositiveInt$2
26
- });
27
- /**
28
- * Canonical client liveness ping message.
29
- *
30
- * The exact string matters: hibernation-capable hosts register it with
31
- * WebSocket auto-response so the runtime answers without waking the object.
32
- */
33
- const EDA_WEB_SOCKET_PING_MESSAGE = "{\"_tag\":\"ping\"}";
34
- /** Canonical server pong message paired with {@link EDA_WEB_SOCKET_PING_MESSAGE}. */
35
- const EDA_WEB_SOCKET_PONG_MESSAGE = "{\"_tag\":\"pong\"}";
36
- /** Client liveness ping; hosts answer with a pong and never ACK-track it. */
37
- const EDAWebSocketWirePingFrame = Schema.Struct({ _tag: Schema.Literal("ping") });
38
- /** Server liveness pong; clients may ignore it and must not ACK it. */
39
- const EDAWebSocketWirePongFrame = Schema.Struct({ _tag: Schema.Literal("pong") });
40
- const EDAWebSocketWireHelloFrame = Schema.Struct({
41
- _tag: Schema.Literal("hello"),
42
- protocolVersion: Schema.Literal(1),
43
- subscriberId: Schema.NonEmptyString,
44
- resumeSeq: NonNegativeInt$2,
45
- flowControl: EDAWebSocketWireFlowControl
46
- });
47
- const EDAWebSocketWireHeartbeatFrame = Schema.Struct({
48
- _tag: Schema.Literal("heartbeat"),
49
- serverTimeMs: NonNegativeInt$2,
50
- durableThroughSeq: NonNegativeInt$2
51
- });
52
- const EDAWebSocketWireLaggedFrame = Schema.Struct({
53
- _tag: Schema.Literal("lagged"),
54
- resumeSeq: NonNegativeInt$2,
55
- reason: Schema.Literals(["buffer-overflow", "ack-timeout"])
56
- });
57
- const EDAWebSocketWireErrorFrame = Schema.Struct({
58
- _tag: Schema.Literal("error"),
59
- message: Schema.String
60
- });
61
- /**
62
- * Client acknowledgement. `frameId` is the transport receipt: it cumulatively frees flow-control
63
- * capacity. On a transcript socket `appliedUpdateSeq` is the client's applied cut, the last
64
- * transcript update it applied completely, and `durableThroughSeq` is that update's
65
- * `throughSeq`; both advance only on complete updates, never on a partial chunked transfer.
66
- * Raw event sockets ignore `appliedUpdateSeq`.
67
- */
68
- const EDAWebSocketWireAckFrame = Schema.Struct({
69
- _tag: Schema.Literal("ack"),
70
- frameId: PositiveInt$2,
71
- durableThroughSeq: NonNegativeInt$2,
72
- appliedUpdateSeq: Schema.optionalKey(NonNegativeInt$2)
73
- });
74
- const EDAWebSocketWireClientFrame = Schema.Union([EDAWebSocketWireAckFrame, EDAWebSocketWirePingFrame]);
75
- /** Complete framework-owned event union present on every EDA WebSocket. */
76
- const EDAFrameworkWebSocketEvent = Schema.Union([EDADurableEvent, EDAEphemeralEvent]);
77
- const makeEDAWebSocketDomainSchemas = (event) => {
78
- const positionedEvent = Schema.Struct({
79
- position: Position,
80
- event
81
- });
82
- const eventsFrame = Schema.Struct({
83
- _tag: Schema.Literal("events"),
84
- frameId: PositiveInt$2,
85
- events: Schema.NonEmptyArray(positionedEvent),
86
- durableThroughSeq: NonNegativeInt$2
87
- });
88
- return {
89
- event,
90
- positionedEvent,
91
- eventsFrame,
92
- serverFrame: Schema.Union([
93
- EDAWebSocketWireHelloFrame,
94
- eventsFrame,
95
- EDAWebSocketWireHeartbeatFrame,
96
- EDAWebSocketWirePongFrame,
97
- EDAWebSocketWireLaggedFrame,
98
- EDAWebSocketWireErrorFrame
99
- ])
100
- };
101
- };
102
- makeEDAWebSocketDomainSchemas(EventEnvelope);
103
- const makeEDAWebSocketWireProtocolFromEventSchema = (event) => {
104
- const domain = makeEDAWebSocketDomainSchemas(event);
105
- const encodeDomainServerFrame = Schema.encodeSync(domain.serverFrame);
106
- const encodeUnknownDomainServerFrame = Schema.encodeUnknownSync(domain.serverFrame);
107
- const encodeServerFrame = (frame) => JSON.stringify(encodeDomainServerFrame(frame));
108
- return {
109
- domain,
110
- wire: {
111
- event: Schema.toEncoded(domain.event),
112
- positionedEvent: Schema.toEncoded(domain.positionedEvent),
113
- eventsFrame: Schema.toEncoded(domain.eventsFrame),
114
- serverFrame: Schema.toEncoded(domain.serverFrame),
115
- clientFrame: EDAWebSocketWireClientFrame
116
- },
117
- encodeServerFrame,
118
- host: { encodeServerFrame: (frame) => JSON.stringify(encodeUnknownDomainServerFrame(frame)) }
119
- };
120
- };
121
- /** Strict framework-only protocol used when an app registers no custom events. */
122
- const edaFrameworkWebSocketWireProtocol = makeEDAWebSocketWireProtocolFromEventSchema(EDAFrameworkWebSocketEvent);
123
- /**
124
- * Bind the generic EDA WebSocket transport to one app's custom event schema.
125
- *
126
- * Framework durable and ephemeral events are included automatically. Future EDA
127
- * apps register only their custom events. Servers use the returned domain schemas
128
- * and typed encoder; external consumers decode with the wire schemas. Pass the
129
- * returned `host` adapter to the selected host package.
130
- */
131
- const makeEDAWebSocketWireProtocol = (options) => makeEDAWebSocketWireProtocolFromEventSchema(Schema.Union([EDAFrameworkWebSocketEvent, options.appEvents]));
132
- //#endregion
133
- //#region src/websocket/messages.ts
134
- /** Current EDA live-event WebSocket protocol version. */
135
- const EDA_WEB_SOCKET_PROTOCOL_VERSION = 1;
136
- /** WebSocket close code used when a subscriber cannot keep up with live delivery. */
137
- const EDA_WS_CLOSE_LAGGED = 4008;
138
- /** WebSocket close code used for normal host-driven shutdown. */
139
- const EDA_WS_CLOSE_GOING_AWAY = 1001;
140
- /** WebSocket close code used for malformed client protocol messages. */
141
- const EDA_WS_CLOSE_PROTOCOL_ERROR = 1002;
142
- /** WebSocket close code used when the host cannot send a frame. */
143
- const EDA_WS_CLOSE_SEND_FAILED = 1011;
144
- /** WebSocket close code used for unsupported binary messages. */
145
- const EDA_WS_CLOSE_UNSUPPORTED_DATA = 1003;
146
- /** Live subscriber identity persisted in WebSocket attachments. */
147
- const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand("SubscriberId"));
148
- /** Per-connection monotonically increasing server frame id. */
149
- const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(Schema.brand("FrameId"));
150
- /** Flow-control policy announced by the server in the hello frame. */
151
- const EDAWebSocketFlowControl = EDAWebSocketWireFlowControl;
152
- /** Default bounded policy sized for fast model deltas and large durable tool/message events. */
153
- const defaultEDAWebSocketFlowControl = {
154
- ackTimeoutMs: 3e4,
155
- heartbeatIntervalMs: 1e4,
156
- maxFrameBytes: 262144,
157
- maxFrameEvents: 1,
158
- maxInFlightFrames: 16,
159
- pingIntervalMs: 3e4,
160
- subscriberBufferCapacityEvents: 2048
161
- };
162
- /** First server frame; announces protocol and flow-control policy. */
163
- const EDAWebSocketHelloFrame = Schema.Struct({
164
- ...EDAWebSocketWireHelloFrame.fields,
165
- subscriberId: SubscriberId,
166
- resumeSeq: SequenceNumber
167
- });
168
- /** Ordered positioned events delivered to the client. */
169
- const EDAWebSocketEventsFrame = Schema.Struct({
170
- _tag: Schema.Literal("events"),
171
- frameId: FrameId,
172
- events: Schema.NonEmptyArray(PositionedEvent),
173
- durableThroughSeq: SequenceNumber
174
- });
175
- /**
176
- * Deprecated idle server keepalive frame.
177
- *
178
- * Servers no longer send heartbeats; the schema remains so deployed clients
179
- * keep decoding the server frame union. Liveness is client-originated via
180
- * {@link EDAWebSocketPingFrame} and the host-level auto-response pong.
181
- */
182
- const EDAWebSocketHeartbeatFrame = Schema.Struct({
183
- ...EDAWebSocketWireHeartbeatFrame.fields,
184
- serverTimeMs: UnixEpochMillis,
185
- durableThroughSeq: SequenceNumber
186
- });
187
- /** Client liveness ping; hosts answer with a pong and never ACK-track it. */
188
- const EDAWebSocketPingFrame = EDAWebSocketWirePingFrame;
189
- /** Server liveness pong; clients may ignore it and must not ACK it. */
190
- const EDAWebSocketPongFrame = EDAWebSocketWirePongFrame;
191
- /** Optional final frame sent before a lag-close. */
192
- const EDAWebSocketLaggedFrame = Schema.Struct({
193
- ...EDAWebSocketWireLaggedFrame.fields,
194
- resumeSeq: SequenceNumber
195
- });
196
- /** Optional final frame sent before a protocol/internal close. */
197
- const EDAWebSocketErrorFrame = EDAWebSocketWireErrorFrame;
198
- /** Server-to-client application frame union. */
199
- const EDAWebSocketServerFrame = Schema.Union([
200
- EDAWebSocketHelloFrame,
201
- EDAWebSocketEventsFrame,
202
- EDAWebSocketHeartbeatFrame,
203
- EDAWebSocketPongFrame,
204
- EDAWebSocketLaggedFrame,
205
- EDAWebSocketErrorFrame
206
- ]);
207
- /** Client acknowledgement after applying a server frame. */
208
- const EDAWebSocketAckFrame = Schema.Struct({
209
- ...EDAWebSocketWireAckFrame.fields,
210
- frameId: FrameId,
211
- durableThroughSeq: SequenceNumber
212
- });
213
- /** Client-to-server application frame union. */
214
- const EDAWebSocketClientFrame = Schema.Union([EDAWebSocketAckFrame, EDAWebSocketPingFrame]);
215
- /** Serialize a server frame for a text WebSocket message. */
216
- const encodeEDAWebSocketServerFrame = (frame, protocol) => (protocol ?? edaFrameworkWebSocketWireProtocol.host).encodeServerFrame(frame);
217
- /** Decode an inbound text WebSocket message at the host boundary. */
218
- const decodeEDAWebSocketClientMessage = (input) => Effect.try({
219
- try: () => JSON.parse(input),
220
- catch: (error) => error
221
- }).pipe(Effect.flatMap((json) => Schema.decodeUnknownEffect(EDAWebSocketWireClientFrame)(json)), Effect.flatMap((frame) => Schema.decodeUnknownEffect(EDAWebSocketClientFrame)(frame)));
222
- /** Short close reason that fits the WebSocket protocol reason limit. */
223
- const laggedCloseReason = (seq) => `lag;seq=${seq}`;
224
- //#endregion
225
- //#region src/websocket/delivery.ts
226
- /** Slow subscriber reasons that intentionally close only the lagging socket. */
227
- const SubscriberLagReason = Schema.Literals(["buffer-overflow", "ack-timeout"]);
228
- /** One sent-but-unacknowledged events frame. */
229
- const EDAWebSocketInFlightFrame = Schema.Struct({
230
- frameId: FrameId,
231
- durableThroughSeq: SequenceNumber,
232
- sentAtMs: Schema.Number
233
- });
234
- /** Compact consecutive host-suppressed receipts blocked by a visible ACK. */
235
- const EDAWebSocketSuppressedRange = Schema.Struct({
236
- fromFrameId: FrameId,
237
- throughFrameId: FrameId,
238
- durableThroughSeq: SequenceNumber
239
- });
240
- /** Complete delivery bookkeeping persisted in the WebSocket attachment. */
241
- const EDAWebSocketDeliveryCheckpoint = Schema.Struct({
242
- lastAckedSeq: SequenceNumber,
243
- lastAckedFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
244
- lastSentFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
245
- nextFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
246
- sentDurableThroughSeq: SequenceNumber,
247
- inFlight: Schema.Array(EDAWebSocketInFlightFrame),
248
- /** Host-projected receipts waiting behind an earlier client-visible ACK. */
249
- suppressed: Schema.optionalKey(Schema.Array(EDAWebSocketSuppressedRange))
250
- });
251
- /** Build delivery state for a newly accepted connection. */
252
- const makeWebSocketDeliveryState = (input) => ({
253
- subscriberId: input.subscriberId,
254
- policy: input.policy,
255
- lastAckedSeq: input.resumeSeq,
256
- lastAckedFrameId: 0,
257
- lastSentFrameId: 0,
258
- nextFrameId: 1,
259
- sentDurableThroughSeq: input.resumeSeq,
260
- inFlight: [],
261
- suppressed: [],
262
- pendingEphemeral: []
263
- });
264
- /** Rebuild exact ACK bookkeeping from a hibernating WebSocket attachment. */
265
- const restoreWebSocketDeliveryState = (input) => ({
266
- subscriberId: input.subscriberId,
267
- policy: input.policy,
268
- ...input.checkpoint,
269
- pendingEphemeral: [],
270
- suppressed: input.checkpoint.suppressed ?? []
271
- });
272
- /** Project in-memory delivery state into the attachment-safe checkpoint. */
273
- const checkpointWebSocketDeliveryState = (state) => ({
274
- lastAckedSeq: state.lastAckedSeq,
275
- lastAckedFrameId: state.lastAckedFrameId,
276
- lastSentFrameId: state.lastSentFrameId,
277
- nextFrameId: state.nextFrameId,
278
- sentDurableThroughSeq: state.sentDurableThroughSeq,
279
- inFlight: state.inFlight,
280
- ...state.suppressed.length === 0 ? {} : { suppressed: state.suppressed }
281
- });
282
- /** First frame for a freshly accepted connection. Restores never re-send hello. */
283
- const deliveryHelloFrame = (state) => EDAWebSocketHelloFrame.make({
284
- _tag: "hello",
285
- protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,
286
- subscriberId: state.subscriberId,
287
- resumeSeq: state.lastAckedSeq,
288
- flowControl: state.policy
289
- });
290
- /** Deliver committed durable events read from the store. */
291
- const onDurableEvents = (state, events, head, nowMs) => {
292
- const stale = staleAckResult(state, nowMs);
293
- if (stale !== void 0) return stale;
294
- let next = state;
295
- const frames = [];
296
- let batch = [];
297
- const flushBatch = () => {
298
- if (batch.length === 0) return;
299
- const sent = sendEventsFrame(next, batch, nowMs);
300
- next = sent.state;
301
- frames.push(sent.frame);
302
- batch = [];
303
- };
304
- for (const event of events) {
305
- if (event.event.durability === "durable" && event.position.seq <= next.sentDurableThroughSeq) continue;
306
- if (batch.length === 0 && windowCapacity(next) <= 0) break;
307
- batch.push(event);
308
- if (batch.length >= next.policy.maxFrameEvents) flushBatch();
309
- }
310
- flushBatch();
311
- return sentResult(next, frames, windowCapacity(next) > 0 && next.sentDurableThroughSeq < head ? next.sentDurableThroughSeq : void 0);
312
- };
313
- /** Deliver one live ephemeral event, buffering only while this isolate is active. */
314
- const onEphemeralEvent = (state, event, nowMs) => {
315
- const stale = staleAckResult(state, nowMs);
316
- if (stale !== void 0) return stale;
317
- if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) {
318
- const sent = sendEventsFrame(state, [event], nowMs);
319
- return sentResult(sent.state, [sent.frame]);
320
- }
321
- const pendingEphemeral = [...state.pendingEphemeral, event];
322
- if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) return laggedResult(state, "buffer-overflow");
323
- return {
324
- state: {
325
- ...state,
326
- pendingEphemeral
327
- },
328
- actions: []
329
- };
330
- };
331
- /** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */
332
- const onClientAck = (state, ack, nowMs) => {
333
- const validated = applyAck(state, ack);
334
- if (validated._tag === "close") return validated.result;
335
- if (validated._tag === "ignore") return {
336
- state,
337
- actions: []
338
- };
339
- return reopenDeliveryWindow(validated.state, nowMs);
340
- };
341
- /**
342
- * Apply one exact host-suppressed receipt without cumulatively ACKing any
343
- * earlier client-visible frame.
344
- */
345
- const onHostSuppressedFrame = (state, frame, nowMs) => {
346
- const receipt = state.inFlight.find((candidate) => candidate.frameId === frame.frameId);
347
- if (receipt === void 0 || receipt.durableThroughSeq !== frame.durableThroughSeq) return protocolClose(state, "Host suppressed an unknown frame receipt").result;
348
- const next = advanceSuppressedReceipts({
349
- ...state,
350
- inFlight: state.inFlight.filter((candidate) => candidate.frameId !== frame.frameId),
351
- suppressed: insertSuppressedReceipt(state.suppressed, receipt)
352
- });
353
- return reopenDeliveryWindow(next, nowMs);
354
- };
355
- const reopenDeliveryWindow = (state, nowMs) => {
356
- let next = state;
357
- const frames = [];
358
- while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {
359
- const [head, ...rest] = next.pendingEphemeral;
360
- if (head === void 0) break;
361
- const sent = sendEventsFrame({
362
- ...next,
363
- pendingEphemeral: rest
364
- }, [head], nowMs);
365
- next = sent.state;
366
- frames.push(sent.frame);
367
- }
368
- const stale = staleAckResult(next, nowMs);
369
- if (stale !== void 0) return stale;
370
- return sentResult(next, frames, windowCapacity(next) > 0 && next.pendingEphemeral.length === 0 ? next.sentDurableThroughSeq : void 0, true);
371
- };
372
- const applyAck = (state, ack) => {
373
- if (ack.frameId <= state.lastAckedFrameId) return ack.durableThroughSeq > state.lastAckedSeq ? protocolClose(state, "Duplicate ACK attempted to advance durable seq") : { _tag: "ignore" };
374
- if (ack.frameId > state.lastSentFrameId) return protocolClose(state, "ACK referenced an unsent frame");
375
- if (ack.durableThroughSeq < state.lastAckedSeq) return protocolClose(state, "ACK durable seq moved backwards");
376
- const acknowledgedVisible = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);
377
- if (acknowledgedVisible.length === 0) return protocolClose(state, "ACK referenced no in-flight frames");
378
- if (state.suppressed.some((range) => range.fromFrameId <= ack.frameId && ack.frameId <= range.throughFrameId)) return protocolClose(state, "ACK referenced a host-suppressed frame");
379
- const acknowledgedSuppressed = state.suppressed.filter((range) => range.throughFrameId <= ack.frameId);
380
- const acknowledged = [...acknowledgedVisible, ...acknowledgedSuppressed];
381
- const allowedDurableSeq = SequenceNumber.make(acknowledged.reduce((max, receipt) => Math.max(max, receipt.durableThroughSeq), state.lastAckedSeq));
382
- if (ack.durableThroughSeq > allowedDurableSeq) return protocolClose(state, "ACK durable seq exceeded sent frame boundary");
383
- return {
384
- _tag: "apply",
385
- state: advanceSuppressedReceipts({
386
- ...state,
387
- inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),
388
- lastAckedFrameId: ack.frameId,
389
- lastAckedSeq: ack.durableThroughSeq,
390
- suppressed: state.suppressed.filter((range) => range.throughFrameId > ack.frameId)
391
- })
392
- };
393
- };
394
- const advanceSuppressedReceipts = (state) => {
395
- let lastAckedFrameId = state.lastAckedFrameId;
396
- let lastAckedSeq = state.lastAckedSeq;
397
- let consumed = 0;
398
- for (const range of state.suppressed) {
399
- if (range.fromFrameId !== lastAckedFrameId + 1) break;
400
- lastAckedFrameId = range.throughFrameId;
401
- lastAckedSeq = SequenceNumber.make(Math.max(lastAckedSeq, range.durableThroughSeq));
402
- consumed += 1;
403
- }
404
- return consumed === 0 ? state : {
405
- ...state,
406
- lastAckedFrameId,
407
- lastAckedSeq,
408
- suppressed: state.suppressed.slice(consumed)
409
- };
410
- };
411
- const insertSuppressedReceipt = (ranges, receipt) => {
412
- const inserted = [...ranges, EDAWebSocketSuppressedRange.make({
413
- fromFrameId: receipt.frameId,
414
- throughFrameId: receipt.frameId,
415
- durableThroughSeq: receipt.durableThroughSeq
416
- })].sort((left, right) => left.fromFrameId - right.fromFrameId);
417
- const compacted = [];
418
- for (const range of inserted) {
419
- const previous = compacted.at(-1);
420
- if (previous === void 0 || range.fromFrameId > previous.throughFrameId + 1) {
421
- compacted.push(range);
422
- continue;
423
- }
424
- compacted[compacted.length - 1] = EDAWebSocketSuppressedRange.make({
425
- fromFrameId: previous.fromFrameId,
426
- throughFrameId: FrameId.make(Math.max(previous.throughFrameId, range.throughFrameId)),
427
- durableThroughSeq: SequenceNumber.make(Math.max(previous.durableThroughSeq, range.durableThroughSeq))
428
- });
429
- }
430
- return compacted;
431
- };
432
- const windowCapacity = (state) => state.policy.maxInFlightFrames - state.inFlight.length;
433
- const sendEventsFrame = (state, events, nowMs) => {
434
- const [first, ...rest] = events;
435
- if (first === void 0) throw new Error("Cannot send an empty events frame");
436
- const frameId = FrameId.make(state.nextFrameId);
437
- const durableThroughSeq = SequenceNumber.make(events.reduce((max, event) => event.event.durability === "durable" ? Math.max(max, event.position.seq) : max, state.sentDurableThroughSeq));
438
- const frame = EDAWebSocketEventsFrame.make({
439
- _tag: "events",
440
- frameId,
441
- events: [first, ...rest],
442
- durableThroughSeq
443
- });
444
- return {
445
- state: {
446
- ...state,
447
- inFlight: [...state.inFlight, {
448
- frameId,
449
- durableThroughSeq,
450
- sentAtMs: nowMs
451
- }],
452
- lastSentFrameId: frameId,
453
- nextFrameId: frameId + 1,
454
- sentDurableThroughSeq: durableThroughSeq
455
- },
456
- frame
457
- };
458
- };
459
- const sentResult = (state, frames, catchUpAfterSeq, stateChanged = frames.length > 0) => ({
460
- state,
461
- actions: [
462
- ...stateChanged ? [{ _tag: "Persist" }] : [],
463
- ...frames.length > 0 ? [{
464
- _tag: "Send",
465
- frames
466
- }] : [],
467
- ...catchUpAfterSeq === void 0 ? [] : [{
468
- _tag: "ReadEventPage",
469
- afterSeq: catchUpAfterSeq
470
- }]
471
- ]
472
- });
473
- /** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */
474
- const staleAckResult = (state, nowMs) => state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs) ? laggedResult(state, "ack-timeout") : void 0;
475
- const laggedResult = (state, reason) => ({
476
- state,
477
- actions: [{
478
- _tag: "Send",
479
- frames: [EDAWebSocketLaggedFrame.make({
480
- _tag: "lagged",
481
- resumeSeq: state.lastAckedSeq,
482
- reason
483
- })]
484
- }, {
485
- _tag: "Close",
486
- code: EDA_WS_CLOSE_LAGGED,
487
- reason: laggedCloseReason(state.lastAckedSeq)
488
- }]
489
- });
490
- const protocolClose = (state, message) => ({
491
- _tag: "close",
492
- result: {
493
- state,
494
- actions: [{
495
- _tag: "Send",
496
- frames: [EDAWebSocketErrorFrame.make({
497
- _tag: "error",
498
- message: message.slice(0, 120)
499
- })]
500
- }, {
501
- _tag: "Close",
502
- code: EDA_WS_CLOSE_PROTOCOL_ERROR,
503
- reason: "protocol"
504
- }]
505
- }
506
- });
507
- //#endregion
508
7
  //#region src/websocket/transcript.ts
509
8
  const PositiveInt$1 = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
510
9
  const NonNegativeInt$1 = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));