effect-durable-agent-cloudflare 0.1.0-alpha.9 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/dist/anthropic.d.ts +44 -0
- package/dist/anthropic.js +66 -0
- package/dist/anthropic.js.map +1 -0
- package/dist/durable-object-DAQzdio7.js +622 -0
- package/dist/durable-object-DAQzdio7.js.map +1 -0
- package/dist/durable-object-storage-Dec6HWQ9.d.ts +136 -0
- package/dist/durable-object-store-yY_KaFtw.js +1231 -0
- package/dist/durable-object-store-yY_KaFtw.js.map +1 -0
- package/dist/durable-object.d.ts +2352 -55
- package/dist/durable-object.js +2 -193
- package/dist/index.d.ts +227 -6
- package/dist/index.js +6 -5
- package/dist/openai.d.ts +10 -5
- package/dist/openai.js +20 -48
- package/dist/openai.js.map +1 -1
- package/dist/providers.d.ts +53 -0
- package/dist/providers.js +221 -0
- package/dist/providers.js.map +1 -0
- package/dist/rpc-codec-B2aLiNqt.d.ts +44 -0
- package/dist/rpc-spec-BRNFIsY1.js +407 -0
- package/dist/rpc-spec-BRNFIsY1.js.map +1 -0
- package/dist/rpc-spec-O5conxmN.d.ts +8888 -0
- package/dist/rpc.d.ts +3 -16
- package/dist/rpc.js +2 -26
- package/dist/{session-controller-COHH8vA6.js → session-controller-BCtnyAEw.js} +689 -657
- package/dist/session-controller-BCtnyAEw.js.map +1 -0
- package/dist/{session-controller-Dp07FnPn.d.ts → session-controller-BZaYmBLr.d.ts} +107 -32
- package/dist/session-controller.d.ts +1 -1
- package/dist/session-controller.js +1 -1
- package/dist/storage.d.ts +1 -1
- package/dist/transport-BzgK07l4.js +205 -0
- package/dist/transport-BzgK07l4.js.map +1 -0
- package/package.json +29 -11
- package/dist/durable-object-storage-DCL2IyUe.d.ts +0 -41
- package/dist/durable-object.js.map +0 -1
- package/dist/rpc.js.map +0 -1
- package/dist/session-controller-COHH8vA6.js.map +0 -1
|
@@ -1,28 +1,35 @@
|
|
|
1
|
+
import { t as DurableObjectSessionStore } from "./durable-object-store-yY_KaFtw.js";
|
|
2
|
+
import "effect-durable-agent/services/prompt-projector";
|
|
3
|
+
import * as Layer from "effect/Layer";
|
|
1
4
|
import * as Effect from "effect/Effect";
|
|
5
|
+
import * as Exit from "effect/Exit";
|
|
2
6
|
import * as Schema from "effect/Schema";
|
|
3
|
-
import {
|
|
4
|
-
import { SequenceNumber, SessionId, SummaryId, durablePosition } from "effect-durable-agent/types/core";
|
|
7
|
+
import { SequenceNumber, SessionId } from "effect-durable-agent/types/core";
|
|
5
8
|
import { EDATraceMetadata, makeRootEDATraceMetadata } from "effect-durable-agent/types/tracing";
|
|
6
|
-
import {
|
|
7
|
-
import * as Layer from "effect/Layer";
|
|
8
|
-
import * as ManagedRuntime from "effect/ManagedRuntime";
|
|
9
|
+
import { EDASessionStoreError } from "effect-durable-agent/services/session-store";
|
|
9
10
|
import { EDARuntime } from "effect-durable-agent/services/runtime";
|
|
10
|
-
import {
|
|
11
|
+
import { defaultTranscriptSubscriptionPolicy, emptyTranscriptActiveContentState, foldTranscriptActiveContent, planTranscriptUpdate, readTranscriptSubscription, transcriptActiveContentOf, transcriptSubscriptionBaseOf } from "effect-durable-agent/transcript";
|
|
12
|
+
import { compactSpanAttributes, toEdaExternalSpan } from "effect-durable-agent/services/tracing";
|
|
13
|
+
import * as ManagedRuntime from "effect/ManagedRuntime";
|
|
11
14
|
import { SinkCheckpointStore } from "effect-durable-agent/services/sink-checkpoint-store";
|
|
12
|
-
import
|
|
13
|
-
import * as Option from "effect/Option";
|
|
14
|
-
import * as Stream from "effect/Stream";
|
|
15
|
-
import { CompactionSummaryArtifact } from "effect-durable-agent/domain/context-projection";
|
|
15
|
+
import { RunSchedulingWakeup } from "effect-durable-agent/services/run-scheduling-wakeup";
|
|
16
16
|
import "effect-durable-agent/services/compaction";
|
|
17
17
|
import { EDAKeepAlive } from "effect-durable-agent/services/keep-alive";
|
|
18
|
-
import "effect-durable-agent/services/prompt-projector";
|
|
19
18
|
import { EDAReducerRegistry } from "effect-durable-agent/services/reducer-registry";
|
|
20
19
|
import { makeEDARuntimeLayer } from "effect-durable-agent/services/runtime-layer";
|
|
21
20
|
import { SessionEventObserver } from "effect-durable-agent/services/session-event-observer";
|
|
22
|
-
import { EDAWebSocketDeliveryCheckpoint, EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE, EDA_WS_CLOSE_PROTOCOL_ERROR, EDA_WS_CLOSE_SEND_FAILED, SubscriberId, checkpointWebSocketDeliveryState, decodeEDAWebSocketClientMessage, defaultEDAWebSocketFlowControl, deliveryHelloFrame, encodeEDAWebSocketServerFrame, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent, onHostSuppressedFrame, restoreWebSocketDeliveryState } from "effect-durable-agent/websocket";
|
|
21
|
+
import { EDATranscriptClientFrame, EDATranscriptDeliveryCheckpoint, EDAWebSocketDeliveryCheckpoint, EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE, EDA_WEB_SOCKET_PROTOCOL_VERSION, EDA_WS_CLOSE_LAGGED, EDA_WS_CLOSE_PROTOCOL_ERROR, EDA_WS_CLOSE_SEND_FAILED, EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE, SubscriberId, checkpointTranscriptDelivery, checkpointWebSocketDeliveryState, decodeEDAWebSocketClientMessage, defaultEDATranscriptDeliveryLimits, defaultEDAWebSocketFlowControl, deliveryHelloFrame, edaTranscriptNegotiation, edaTranscriptUpdateFrameText, encodeEDATranscriptServerFrame, encodeEDATranscriptUpdate, encodeEDAWebSocketServerFrame, enqueueTranscriptRequest, laggedCloseReason, makeTranscriptDeliveryState, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent, onHostSuppressedFrame, onTranscriptAck, pumpTranscriptTransfer, restoreTranscriptDeliveryState, restoreWebSocketDeliveryState, startTranscriptUpdate, transcriptAckTimedOut, transcriptDeliveryCapacity, utf8ByteLength } from "effect-durable-agent/websocket";
|
|
23
22
|
/**
|
|
24
23
|
* Alarm-backed in-memory keepalive for a raw Durable Object host.
|
|
25
24
|
*
|
|
25
|
+
* Inbound events (requests, alarms) are what reliably keep an object resident: sessions streaming
|
|
26
|
+
* model responses and sandbox output were evicted 70-140 seconds after their last inbound event.
|
|
27
|
+
* The heartbeat therefore has to be delivered, not just scheduled: an armed alarm is never
|
|
28
|
+
* deleted or postponed when work is released, because finite work (model turns, sink catch-up)
|
|
29
|
+
* releases and re-acquires between steps, and moving the alarm on every step would keep it from
|
|
30
|
+
* ever firing. Only the alarm handler, finding no work left, or {@link shutdown} clears it, so a
|
|
31
|
+
* session that goes idle receives one final heartbeat.
|
|
32
|
+
*
|
|
26
33
|
* The active lease count is intentionally not durable: if the object is evicted
|
|
27
34
|
* or crashes, the fibers the leases represented are gone too, and normal EDA
|
|
28
35
|
* durable recovery must explain any escaped lifecycle boundaries.
|
|
@@ -34,6 +41,7 @@ var DurableObjectKeepAlive = class {
|
|
|
34
41
|
now;
|
|
35
42
|
onBackgroundError;
|
|
36
43
|
activeLeases = 0;
|
|
44
|
+
runSchedulingPending = false;
|
|
37
45
|
generation = 0;
|
|
38
46
|
scheduleTail = Promise.resolve();
|
|
39
47
|
shutdownRequested = false;
|
|
@@ -48,6 +56,11 @@ var DurableObjectKeepAlive = class {
|
|
|
48
56
|
get activeLeaseCount() {
|
|
49
57
|
return this.activeLeases;
|
|
50
58
|
}
|
|
59
|
+
/** Durable delivery work survives the release of every in-memory active lease. */
|
|
60
|
+
setRunSchedulingPending(pending) {
|
|
61
|
+
this.runSchedulingPending = pending;
|
|
62
|
+
return this.reschedule();
|
|
63
|
+
}
|
|
51
64
|
/** Acquire one active-work lease and arm the heartbeat if this is the first lease. */
|
|
52
65
|
acquire() {
|
|
53
66
|
if (this.shutdownRequested) return Promise.reject(/* @__PURE__ */ new Error("DurableObjectKeepAlive is shut down"));
|
|
@@ -106,16 +119,17 @@ var DurableObjectKeepAlive = class {
|
|
|
106
119
|
await this.trackFiber(fiber);
|
|
107
120
|
return fiber;
|
|
108
121
|
}
|
|
109
|
-
/** Handle the Durable Object `alarm()` callback
|
|
122
|
+
/** Handle the Durable Object `alarm()` callback: re-arm while work remains, else clear. */
|
|
110
123
|
alarm() {
|
|
111
|
-
return this.reschedule();
|
|
124
|
+
return this.reschedule(true);
|
|
112
125
|
}
|
|
113
126
|
/** Permanently stop the heartbeat and prevent later lease releases from re-arming it. */
|
|
114
127
|
shutdown() {
|
|
115
128
|
this.shutdownRequested = true;
|
|
116
129
|
this.generation += 1;
|
|
117
130
|
this.activeLeases = 0;
|
|
118
|
-
|
|
131
|
+
this.runSchedulingPending = false;
|
|
132
|
+
return this.reschedule(true);
|
|
119
133
|
}
|
|
120
134
|
/** Start a fresh lease generation after the host intentionally resets its durable state. */
|
|
121
135
|
restart() {
|
|
@@ -127,13 +141,14 @@ var DurableObjectKeepAlive = class {
|
|
|
127
141
|
return;
|
|
128
142
|
}
|
|
129
143
|
}
|
|
130
|
-
|
|
131
|
-
|
|
144
|
+
/** `clearWhenIdle`: only the alarm handler and shutdown may remove an idle object's alarm. */
|
|
145
|
+
reschedule(clearWhenIdle = false) {
|
|
146
|
+
this.scheduleTail = this.scheduleTail.catch(() => void 0).then(() => this.syncAlarm(clearWhenIdle));
|
|
132
147
|
return this.scheduleTail;
|
|
133
148
|
}
|
|
134
|
-
async syncAlarm() {
|
|
135
|
-
if (this.shutdownRequested || this.activeLeases === 0) {
|
|
136
|
-
await this.storage.deleteAlarm();
|
|
149
|
+
async syncAlarm(clearWhenIdle) {
|
|
150
|
+
if (this.shutdownRequested || this.activeLeases === 0 && !this.runSchedulingPending) {
|
|
151
|
+
if (clearWhenIdle || this.shutdownRequested) await this.storage.deleteAlarm();
|
|
137
152
|
return;
|
|
138
153
|
}
|
|
139
154
|
const desiredAt = this.now() + this.intervalMs;
|
|
@@ -214,644 +229,32 @@ const makeDurableObjectSinkCheckpointStore = (storage) => Effect.gen(function* (
|
|
|
214
229
|
});
|
|
215
230
|
const sinkCheckpointError = (operation, cause) => new EDASessionStoreError({ message: cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}` });
|
|
216
231
|
//#endregion
|
|
217
|
-
//#region src/durable-object-store.ts
|
|
218
|
-
/** Safe payload ceiling below the Durable Object SQLite 2 MB value limit. */
|
|
219
|
-
/** Conservative JSON limit below the Durable Object SQLite per-value ceiling. */
|
|
220
|
-
const durableObjectSerializedJsonHardCapBytes = 15e5;
|
|
221
|
-
const ProjectionPayload = Schema.Record(Schema.String, Schema.Unknown);
|
|
222
|
-
const AdmittedCommandProjection = Schema.Struct({
|
|
223
|
-
commandId: Schema.Unknown,
|
|
224
|
-
idempotencyKey: Schema.optionalKey(Schema.Unknown)
|
|
225
|
-
});
|
|
226
|
-
/** Single squashed schema version for the current pre-release DO store. */
|
|
227
|
-
const durableObjectSessionStoreSchemaVersion = 1;
|
|
228
|
-
const jsonEncoder = new TextEncoder();
|
|
229
|
-
/**
|
|
230
|
-
* Bound one synchronous DO SQLite event-log read/decode to a small CPU and memory slice.
|
|
231
|
-
*
|
|
232
|
-
* A single logical event can already approach the per-row JSON hard cap, and logical decode may
|
|
233
|
-
* touch sidecar rows. Sixteen rows keeps worst-case page memory materially below isolate limits
|
|
234
|
-
* while still amortizing SQL cursor setup for normal small framework events. Revisit with page
|
|
235
|
-
* duration/byte telemetry before increasing.
|
|
236
|
-
*/
|
|
237
|
-
const durableObjectEventReadPageRows = 16;
|
|
238
|
-
/**
|
|
239
|
-
* Durable Object SQLite-backed implementation of the semantic `EDASessionStore`.
|
|
240
|
-
*
|
|
241
|
-
* This adapter is the only place EDA framework storage code touches DO SQL. It
|
|
242
|
-
* translates domain append intent into synchronous SQLite writes while keeping
|
|
243
|
-
* `SessionState` and runners SQL-agnostic.
|
|
244
|
-
*/
|
|
245
|
-
var DurableObjectSessionStore = class DurableObjectSessionStore {
|
|
246
|
-
/** Run the single squashed framework migration for the current pre-release schema. */
|
|
247
|
-
static migrate = (storage) => migrateDurableObjectSessionStore(storage);
|
|
248
|
-
/** Build a session-scoped store after migrations have completed. */
|
|
249
|
-
static make = ({ sessionId, storage }) => Effect.gen(function* () {
|
|
250
|
-
yield* DurableObjectSessionStore.migrate(storage);
|
|
251
|
-
return makeDurableObjectSessionStore(sessionId, storage);
|
|
252
|
-
});
|
|
253
|
-
/** Layer constructor used by the Durable Object host runtime graph. */
|
|
254
|
-
static layer = (options) => Layer.effect(EDASessionStore, DurableObjectSessionStore.make(options));
|
|
255
|
-
};
|
|
256
|
-
/**
|
|
257
|
-
* Create all framework-owned tables in one idempotent startup step.
|
|
258
|
-
*
|
|
259
|
-
* The project is still pre-release, so this remains a squashed version-1 schema
|
|
260
|
-
* rather than a chain of compatibility migrations.
|
|
261
|
-
*/
|
|
262
|
-
const migrateDurableObjectSessionStore = (storage) => Effect.try({
|
|
263
|
-
try: () => storage.transactionSync(() => {
|
|
264
|
-
const { sql } = storage;
|
|
265
|
-
sql.exec(`
|
|
266
|
-
CREATE TABLE IF NOT EXISTS _eda_schema_migrations (
|
|
267
|
-
id INTEGER PRIMARY KEY,
|
|
268
|
-
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
269
|
-
)
|
|
270
|
-
`);
|
|
271
|
-
if ((sql.exec("SELECT COALESCE(MAX(id), 0) AS version FROM _eda_schema_migrations").one().version ?? 0) < durableObjectSessionStoreSchemaVersion) {
|
|
272
|
-
sql.exec(`
|
|
273
|
-
CREATE TABLE IF NOT EXISTS _eda_event_log (
|
|
274
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
275
|
-
event_id TEXT NOT NULL UNIQUE,
|
|
276
|
-
namespace TEXT NOT NULL,
|
|
277
|
-
type TEXT NOT NULL,
|
|
278
|
-
schema_version INTEGER NOT NULL,
|
|
279
|
-
created_at_ms INTEGER NOT NULL,
|
|
280
|
-
trace_json TEXT NOT NULL,
|
|
281
|
-
fact_json TEXT NOT NULL
|
|
282
|
-
)
|
|
283
|
-
`);
|
|
284
|
-
sql.exec(`
|
|
285
|
-
CREATE INDEX IF NOT EXISTS _eda_event_log_namespace_type_seq_idx
|
|
286
|
-
ON _eda_event_log(namespace, type, seq)
|
|
287
|
-
`);
|
|
288
|
-
sql.exec(`
|
|
289
|
-
CREATE TABLE IF NOT EXISTS _eda_command_state (
|
|
290
|
-
command_id TEXT PRIMARY KEY,
|
|
291
|
-
admitted_seq INTEGER NOT NULL,
|
|
292
|
-
status TEXT NOT NULL,
|
|
293
|
-
idempotency_key TEXT,
|
|
294
|
-
payload_json TEXT NOT NULL
|
|
295
|
-
)
|
|
296
|
-
`);
|
|
297
|
-
sql.exec(`
|
|
298
|
-
CREATE TABLE IF NOT EXISTS _eda_command_inputs (
|
|
299
|
-
command_id TEXT PRIMARY KEY,
|
|
300
|
-
admitted_seq INTEGER NOT NULL UNIQUE,
|
|
301
|
-
payload_json TEXT NOT NULL
|
|
302
|
-
)
|
|
303
|
-
`);
|
|
304
|
-
sql.exec(`
|
|
305
|
-
CREATE INDEX IF NOT EXISTS _eda_command_state_status_seq_idx
|
|
306
|
-
ON _eda_command_state(status, admitted_seq)
|
|
307
|
-
`);
|
|
308
|
-
sql.exec(`
|
|
309
|
-
CREATE UNIQUE INDEX IF NOT EXISTS _eda_command_state_idempotency_idx
|
|
310
|
-
ON _eda_command_state(idempotency_key) WHERE idempotency_key IS NOT NULL
|
|
311
|
-
`);
|
|
312
|
-
sql.exec(`
|
|
313
|
-
CREATE TABLE IF NOT EXISTS _eda_context_messages (
|
|
314
|
-
message_id TEXT PRIMARY KEY,
|
|
315
|
-
context_seq INTEGER NOT NULL UNIQUE,
|
|
316
|
-
payload_json TEXT NOT NULL
|
|
317
|
-
)
|
|
318
|
-
`);
|
|
319
|
-
sql.exec(`
|
|
320
|
-
CREATE INDEX IF NOT EXISTS _eda_context_messages_context_seq_idx
|
|
321
|
-
ON _eda_context_messages(context_seq)
|
|
322
|
-
`);
|
|
323
|
-
sql.exec(`
|
|
324
|
-
CREATE TABLE IF NOT EXISTS _eda_context_summaries (
|
|
325
|
-
summary_id TEXT PRIMARY KEY,
|
|
326
|
-
created_seq INTEGER NOT NULL UNIQUE,
|
|
327
|
-
payload_json TEXT NOT NULL
|
|
328
|
-
)
|
|
329
|
-
`);
|
|
330
|
-
sql.exec(`
|
|
331
|
-
CREATE INDEX IF NOT EXISTS _eda_context_summaries_created_seq_idx
|
|
332
|
-
ON _eda_context_summaries(created_seq)
|
|
333
|
-
`);
|
|
334
|
-
sql.exec(`
|
|
335
|
-
CREATE TABLE IF NOT EXISTS _eda_reducer_checkpoints (
|
|
336
|
-
reducer_name TEXT PRIMARY KEY,
|
|
337
|
-
schema_version INTEGER NOT NULL,
|
|
338
|
-
through_seq INTEGER NOT NULL,
|
|
339
|
-
payload_json TEXT NOT NULL,
|
|
340
|
-
updated_at_ms INTEGER NOT NULL
|
|
341
|
-
)
|
|
342
|
-
`);
|
|
343
|
-
sql.exec(`
|
|
344
|
-
CREATE TABLE IF NOT EXISTS _eda_sink_cursors (
|
|
345
|
-
sink_name TEXT PRIMARY KEY,
|
|
346
|
-
after_seq INTEGER NOT NULL,
|
|
347
|
-
payload_json TEXT NOT NULL
|
|
348
|
-
)
|
|
349
|
-
`);
|
|
350
|
-
sql.exec("INSERT INTO _eda_schema_migrations (id) VALUES (?)", durableObjectSessionStoreSchemaVersion);
|
|
351
|
-
}
|
|
352
|
-
}),
|
|
353
|
-
catch: (error) => durableStoreError("migrating DurableObjectSessionStore", error)
|
|
354
|
-
});
|
|
355
|
-
/**
|
|
356
|
-
* Interpret the semantic store API with native DO SQLite.
|
|
357
|
-
*
|
|
358
|
-
* All writes that affect durable ordering happen inside `transactionSync`; replay
|
|
359
|
-
* and lookup reads stay synchronous SQL wrapped in Effect boundaries.
|
|
360
|
-
*/
|
|
361
|
-
const makeDurableObjectSessionStore = (sessionId, storage) => {
|
|
362
|
-
const { sql } = storage;
|
|
363
|
-
const ensureSession = (event) => {
|
|
364
|
-
if (event.sessionId !== sessionId) throw new Error(`DurableObjectSessionStore is scoped to session ${sessionId}; received ${event.sessionId}`);
|
|
365
|
-
};
|
|
366
|
-
/**
|
|
367
|
-
* Insert one append entry or return its existing idempotent event position.
|
|
368
|
-
*
|
|
369
|
-
* The event row is the sequence allocator. Artifact/projection writes happen
|
|
370
|
-
* only for newly inserted events, preventing duplicate appends from advancing
|
|
371
|
-
* body rows or metadata.
|
|
372
|
-
*/
|
|
373
|
-
const insertOrRead = (entry) => {
|
|
374
|
-
const { event } = entry;
|
|
375
|
-
ensureSession(event);
|
|
376
|
-
const existing = readCommittedByEventIdOptional(sql, sessionId, event.eventId);
|
|
377
|
-
if (existing !== void 0) return existing;
|
|
378
|
-
const encoded = encodeEventLogRow(event);
|
|
379
|
-
sql.exec(`
|
|
380
|
-
INSERT INTO _eda_event_log (
|
|
381
|
-
event_id,
|
|
382
|
-
namespace,
|
|
383
|
-
type,
|
|
384
|
-
schema_version,
|
|
385
|
-
created_at_ms,
|
|
386
|
-
trace_json,
|
|
387
|
-
fact_json
|
|
388
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
389
|
-
`, encoded.eventId, encoded.namespace, encoded.type, encoded.schemaVersion, encoded.createdAtMs, encoded.traceJson, encoded.factJson);
|
|
390
|
-
const row = readEventLogRowByEventId(sql, event.eventId);
|
|
391
|
-
applySynchronousProjections(sql, entry, SequenceNumber.make(row.seq), encoded.factJson);
|
|
392
|
-
return rowToCommittedDurableEvent(sql, row, sessionId);
|
|
393
|
-
};
|
|
394
|
-
/** Execute an entire append batch as one synchronous SQLite transaction. */
|
|
395
|
-
const append = (batch) => Effect.try({
|
|
396
|
-
try: () => storage.transactionSync(() => batch.entries.map(insertOrRead)),
|
|
397
|
-
catch: (error) => durableStoreError("appending DurableObjectSessionStore batch", error)
|
|
398
|
-
}).pipe(Effect.tap((committed) => annotateEdaSpan(committedBatchAttributes(committed))));
|
|
399
|
-
return {
|
|
400
|
-
append,
|
|
401
|
-
eventsAfter: (afterSeq) => makeCommittedEventStream(sql, sessionId, afterSeq),
|
|
402
|
-
loadCommittedEventsBySeq: (seqs) => Effect.try({
|
|
403
|
-
try: () => uniqueSequenceNumbers(seqs).sort((left, right) => left - right).map((seq) => readCommittedBySeq(sql, sessionId, seq)),
|
|
404
|
-
catch: (error) => durableStoreError("loading DurableObjectSessionStore events by seq", error)
|
|
405
|
-
}),
|
|
406
|
-
findCommandAdmission: (input) => Effect.try({
|
|
407
|
-
try: () => {
|
|
408
|
-
const row = findCommandAdmissionRow(sql, input.commandId, input.idempotencyKey);
|
|
409
|
-
return row === void 0 ? void 0 : readCommittedBySeq(sql, sessionId, row.admitted_seq);
|
|
410
|
-
},
|
|
411
|
-
catch: (error) => durableStoreError("finding command admission", error)
|
|
412
|
-
}),
|
|
413
|
-
loadSummaryArtifact: (summaryId) => Effect.try({
|
|
414
|
-
try: () => readSummaryPayloadOptional(sql, summaryId),
|
|
415
|
-
catch: (error) => durableStoreError("loading DurableObjectSessionStore summary", error)
|
|
416
|
-
}),
|
|
417
|
-
loadReducerCheckpoint: (name) => Effect.try({
|
|
418
|
-
try: () => readReducerCheckpoint(sql, name),
|
|
419
|
-
catch: (error) => durableStoreError(`loading DurableObjectSessionStore reducer checkpoint ${name}`, error)
|
|
420
|
-
}),
|
|
421
|
-
saveReducerCheckpoint: (checkpoint) => Effect.try({
|
|
422
|
-
try: () => writeReducerCheckpoint(sql, checkpoint),
|
|
423
|
-
catch: (error) => durableStoreError(`saving DurableObjectSessionStore reducer checkpoint ${checkpoint.name}`, error)
|
|
424
|
-
}),
|
|
425
|
-
saveReducerCheckpoints: (checkpoints) => Effect.try({
|
|
426
|
-
try: () => storage.transactionSync(() => checkpoints.forEach((checkpoint) => writeReducerCheckpoint(sql, checkpoint))),
|
|
427
|
-
catch: (error) => durableStoreError("saving DurableObjectSessionStore reducer checkpoints", error)
|
|
428
|
-
})
|
|
429
|
-
};
|
|
430
|
-
};
|
|
431
|
-
const makeCommittedEventStream = (sql, sessionId, afterSeq) => Stream.fromPull(Effect.sync(() => {
|
|
432
|
-
let cursor = {
|
|
433
|
-
afterSeq,
|
|
434
|
-
throughSeq: void 0
|
|
435
|
-
};
|
|
436
|
-
let done = false;
|
|
437
|
-
return Effect.gen(function* () {
|
|
438
|
-
if (done) return yield* Cause.done();
|
|
439
|
-
yield* Effect.yieldNow;
|
|
440
|
-
const page = yield* readCommittedEventPage(sql, sessionId, cursor);
|
|
441
|
-
if (page.events.length === 0) {
|
|
442
|
-
done = true;
|
|
443
|
-
return yield* Cause.done();
|
|
444
|
-
}
|
|
445
|
-
if (Option.isSome(page.next)) cursor = page.next.value;
|
|
446
|
-
else done = true;
|
|
447
|
-
return page.events;
|
|
448
|
-
});
|
|
449
|
-
}));
|
|
450
|
-
const readCommittedEventPage = (sql, sessionId, cursor) => Effect.try({
|
|
451
|
-
try: () => {
|
|
452
|
-
const throughSeq = cursor.throughSeq ?? readEventLogHead(sql);
|
|
453
|
-
if (cursor.afterSeq >= throughSeq) return {
|
|
454
|
-
events: [],
|
|
455
|
-
next: Option.none()
|
|
456
|
-
};
|
|
457
|
-
const events = sql.exec(`
|
|
458
|
-
SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
|
|
459
|
-
FROM _eda_event_log
|
|
460
|
-
WHERE seq > ? AND seq <= ?
|
|
461
|
-
ORDER BY seq ASC
|
|
462
|
-
LIMIT ?
|
|
463
|
-
`, cursor.afterSeq, throughSeq, durableObjectEventReadPageRows).toArray().map((row) => rowToCommittedDurableEvent(sql, row, sessionId));
|
|
464
|
-
const lastSeq = events.at(-1)?.position.seq ?? cursor.afterSeq;
|
|
465
|
-
return {
|
|
466
|
-
events,
|
|
467
|
-
next: lastSeq < throughSeq ? Option.some({
|
|
468
|
-
afterSeq: lastSeq,
|
|
469
|
-
throughSeq
|
|
470
|
-
}) : Option.none()
|
|
471
|
-
};
|
|
472
|
-
},
|
|
473
|
-
catch: (error) => durableStoreError("replaying DurableObjectSessionStore events", error)
|
|
474
|
-
});
|
|
475
|
-
const readEventLogHead = (sql) => SequenceNumber.make(sql.exec(`
|
|
476
|
-
SELECT COALESCE(MAX(seq), 0) AS head
|
|
477
|
-
FROM _eda_event_log
|
|
478
|
-
`).one().head ?? 0);
|
|
479
|
-
const uniqueSequenceNumbers = (seqs) => Array.from(new Set(seqs.map((seq) => Number(seq)))).map((seq) => SequenceNumber.make(seq));
|
|
480
|
-
const readEventLogRowByEventId = (sql, eventId) => sql.exec(`
|
|
481
|
-
SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
|
|
482
|
-
FROM _eda_event_log
|
|
483
|
-
WHERE event_id = ?
|
|
484
|
-
`, eventId).one();
|
|
485
|
-
const readCommittedByEventIdOptional = (sql, sessionId, eventId) => {
|
|
486
|
-
const row = sql.exec(`
|
|
487
|
-
SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
|
|
488
|
-
FROM _eda_event_log
|
|
489
|
-
WHERE event_id = ?
|
|
490
|
-
`, eventId).toArray()[0];
|
|
491
|
-
return row === void 0 ? void 0 : rowToCommittedDurableEvent(sql, row, sessionId);
|
|
492
|
-
};
|
|
493
|
-
const readReducerCheckpoint = (sql, name) => {
|
|
494
|
-
const row = sql.exec(`
|
|
495
|
-
SELECT reducer_name, schema_version, through_seq, payload_json, updated_at_ms
|
|
496
|
-
FROM _eda_reducer_checkpoints
|
|
497
|
-
WHERE reducer_name = ?
|
|
498
|
-
`, name).toArray()[0];
|
|
499
|
-
return row === void 0 ? void 0 : {
|
|
500
|
-
name: row.reducer_name,
|
|
501
|
-
schemaVersion: row.schema_version,
|
|
502
|
-
throughSeq: SequenceNumber.make(row.through_seq),
|
|
503
|
-
payload: JSON.parse(row.payload_json),
|
|
504
|
-
updatedAtMs: row.updated_at_ms
|
|
505
|
-
};
|
|
506
|
-
};
|
|
507
|
-
const writeReducerCheckpoint = (sql, checkpoint) => {
|
|
508
|
-
sql.exec(`
|
|
509
|
-
INSERT INTO _eda_reducer_checkpoints (
|
|
510
|
-
reducer_name,
|
|
511
|
-
schema_version,
|
|
512
|
-
through_seq,
|
|
513
|
-
payload_json,
|
|
514
|
-
updated_at_ms
|
|
515
|
-
) VALUES (?, ?, ?, ?, ?)
|
|
516
|
-
ON CONFLICT(reducer_name) DO UPDATE SET
|
|
517
|
-
schema_version = excluded.schema_version,
|
|
518
|
-
through_seq = excluded.through_seq,
|
|
519
|
-
payload_json = excluded.payload_json,
|
|
520
|
-
updated_at_ms = excluded.updated_at_ms
|
|
521
|
-
`, checkpoint.name, checkpoint.schemaVersion, checkpoint.throughSeq, stringifyJsonForColumn(checkpoint.payload, "_eda_reducer_checkpoints.payload_json"), checkpoint.updatedAtMs);
|
|
522
|
-
};
|
|
523
|
-
const readMessagePayloadByContextSeq = (sql, contextSeq) => {
|
|
524
|
-
const message = sql.exec(`
|
|
525
|
-
SELECT context_seq, payload_json
|
|
526
|
-
FROM _eda_context_messages
|
|
527
|
-
WHERE context_seq = ?
|
|
528
|
-
`, contextSeq).toArray()[0];
|
|
529
|
-
if (message === void 0) throw new Error(`Context message at seq ${contextSeq} missing from _eda_context_messages`);
|
|
530
|
-
return message;
|
|
531
|
-
};
|
|
532
|
-
const readCommittedBySeq = (sql, sessionId, seq) => {
|
|
533
|
-
return rowToCommittedDurableEvent(sql, sql.exec(`
|
|
534
|
-
SELECT seq, event_id, namespace, type, schema_version, created_at_ms, trace_json, fact_json
|
|
535
|
-
FROM _eda_event_log
|
|
536
|
-
WHERE seq = ?
|
|
537
|
-
`, seq).one(), sessionId);
|
|
538
|
-
};
|
|
539
|
-
const rowToCommittedDurableEvent = (sql, row, sessionId) => CommittedDurableEvent.make({
|
|
540
|
-
position: durablePosition(SequenceNumber.make(row.seq)),
|
|
541
|
-
event: decodeDurableEvent({
|
|
542
|
-
namespace: row.namespace,
|
|
543
|
-
type: row.type,
|
|
544
|
-
schemaVersion: row.schema_version,
|
|
545
|
-
durability: "durable",
|
|
546
|
-
eventId: row.event_id,
|
|
547
|
-
sessionId,
|
|
548
|
-
createdAtMs: row.created_at_ms,
|
|
549
|
-
trace: JSON.parse(row.trace_json),
|
|
550
|
-
payload: readLogicalPayload(sql, row)
|
|
551
|
-
})
|
|
552
|
-
});
|
|
553
|
-
const decodeDurableEvent = (input) => {
|
|
554
|
-
const event = Schema.decodeUnknownSync(DurableEventEnvelope)(input);
|
|
555
|
-
return event.namespace === effectDurableAgentNamespace ? decodeUnknownEDADurableEventSync(event) : event;
|
|
556
|
-
};
|
|
557
|
-
const encodeEventLogRow = (event) => {
|
|
558
|
-
const encoded = Schema.encodeSync(DurableEventEnvelope)(event);
|
|
559
|
-
return {
|
|
560
|
-
eventId: encoded.eventId,
|
|
561
|
-
namespace: encoded.namespace,
|
|
562
|
-
type: encoded.type,
|
|
563
|
-
schemaVersion: encoded.schemaVersion,
|
|
564
|
-
createdAtMs: encoded.createdAtMs,
|
|
565
|
-
traceJson: stringifyJsonForColumn(encoded.trace, "_eda_event_log.trace_json"),
|
|
566
|
-
factJson: stringifyJsonForColumn(eventLogFactPayload(encoded.namespace, encoded.type, encoded.payload), "_eda_event_log.fact_json")
|
|
567
|
-
};
|
|
568
|
-
};
|
|
569
|
-
const readLogicalPayload = (sql, row) => {
|
|
570
|
-
if (row.namespace !== effectDurableAgentNamespace) return JSON.parse(row.fact_json);
|
|
571
|
-
if (row.type === commandAdmittedEventType) return { command: readCommandInputPayload(sql, readCommandIdFromFact(row)) };
|
|
572
|
-
if (contextMessageEventTypes.has(row.type)) return JSON.parse(readMessagePayloadByContextSeq(sql, row.seq).payload_json);
|
|
573
|
-
if (row.type === summaryCreatedEventType) return {
|
|
574
|
-
...JSON.parse(row.fact_json),
|
|
575
|
-
summary: readSummaryPayloadFromCreatedSeq(sql, row.seq)
|
|
576
|
-
};
|
|
577
|
-
return JSON.parse(row.fact_json);
|
|
578
|
-
};
|
|
579
|
-
const eventLogFactPayload = (namespace, type, payload) => {
|
|
580
|
-
if (namespace !== effectDurableAgentNamespace || typeof payload !== "object" || payload === null) return payload;
|
|
581
|
-
const record = payload;
|
|
582
|
-
switch (type) {
|
|
583
|
-
case commandAdmittedEventType: return { command: commandFact(record.command) };
|
|
584
|
-
case systemMessageCommittedEventType: return pick(record, ["messageId"]);
|
|
585
|
-
case userMessageCommittedEventType: return pick(record, ["commandId", "messageId"]);
|
|
586
|
-
case steeringMessageQueuedEventType: return pick(record, [
|
|
587
|
-
"commandId",
|
|
588
|
-
"messageId",
|
|
589
|
-
"runId"
|
|
590
|
-
]);
|
|
591
|
-
case assistantMessageCommittedEventType:
|
|
592
|
-
case assistantMessageImportedEventType: return pick(record, [
|
|
593
|
-
"messageId",
|
|
594
|
-
"runId",
|
|
595
|
-
"turnId",
|
|
596
|
-
"inferenceId"
|
|
597
|
-
]);
|
|
598
|
-
case assistantPartialCommittedEventType: return pick(record, [
|
|
599
|
-
"messageId",
|
|
600
|
-
"runId",
|
|
601
|
-
"turnId",
|
|
602
|
-
"inferenceId",
|
|
603
|
-
"reason"
|
|
604
|
-
]);
|
|
605
|
-
case summaryCreatedEventType: return pick(record, [
|
|
606
|
-
"compactionId",
|
|
607
|
-
"summaryId",
|
|
608
|
-
"sourceFromSeq",
|
|
609
|
-
"sourceToSeq"
|
|
610
|
-
]);
|
|
611
|
-
default: return payload;
|
|
612
|
-
}
|
|
613
|
-
};
|
|
614
|
-
const commandFact = (command) => {
|
|
615
|
-
if (typeof command !== "object" || command === null) return command;
|
|
616
|
-
const record = command;
|
|
617
|
-
return record._tag === "SubmitMessage" ? pick(record, [
|
|
618
|
-
"_tag",
|
|
619
|
-
"commandId",
|
|
620
|
-
"disposition",
|
|
621
|
-
"idempotencyKey"
|
|
622
|
-
]) : command;
|
|
623
|
-
};
|
|
624
|
-
const pick = (record, keys) => {
|
|
625
|
-
const out = {};
|
|
626
|
-
for (const key of keys) if (record[key] !== void 0) out[key] = record[key];
|
|
627
|
-
return out;
|
|
628
|
-
};
|
|
629
|
-
const readCommandIdFromFact = (row) => {
|
|
630
|
-
const commandId = JSON.parse(row.fact_json).command?.commandId;
|
|
631
|
-
if (typeof commandId !== "string") throw new Error(`CommandAdmitted fact at seq ${row.seq} missing command.commandId`);
|
|
632
|
-
return commandId;
|
|
633
|
-
};
|
|
634
|
-
const readCommandInputPayload = (sql, commandId) => {
|
|
635
|
-
const row = sql.exec(`
|
|
636
|
-
SELECT payload_json
|
|
637
|
-
FROM _eda_command_inputs
|
|
638
|
-
WHERE command_id = ?
|
|
639
|
-
`, commandId).toArray()[0];
|
|
640
|
-
if (row === void 0) throw new Error(`Command input ${commandId} missing from _eda_command_inputs`);
|
|
641
|
-
return JSON.parse(row.payload_json);
|
|
642
|
-
};
|
|
643
|
-
const readSummaryPayloadOptional = (sql, summaryId) => {
|
|
644
|
-
const row = sql.exec(`
|
|
645
|
-
SELECT payload_json
|
|
646
|
-
FROM _eda_context_summaries
|
|
647
|
-
WHERE summary_id = ?
|
|
648
|
-
`, summaryId).toArray()[0];
|
|
649
|
-
return row === void 0 ? void 0 : Schema.decodeUnknownSync(CompactionSummaryArtifact)(JSON.parse(row.payload_json));
|
|
650
|
-
};
|
|
651
|
-
const readSummaryPayloadFromCreatedSeq = (sql, createdSeq) => {
|
|
652
|
-
const row = sql.exec(`
|
|
653
|
-
SELECT payload_json
|
|
654
|
-
FROM _eda_context_summaries
|
|
655
|
-
WHERE created_seq = ?
|
|
656
|
-
`, createdSeq).toArray()[0];
|
|
657
|
-
if (row === void 0) throw new Error(`SummaryCreated at seq ${createdSeq} missing from _eda_context_summaries`);
|
|
658
|
-
return JSON.parse(row.payload_json);
|
|
659
|
-
};
|
|
660
|
-
/**
|
|
661
|
-
* Maintain bounded storage projections in the same transaction as the event.
|
|
662
|
-
*
|
|
663
|
-
* These rows are durability aids, not a second source of lifecycle truth: event
|
|
664
|
-
* order still comes from `_eda_event_log.seq`, while projections make command
|
|
665
|
-
* lookup and body-sidecar hydration bounded.
|
|
666
|
-
*/
|
|
667
|
-
const applySynchronousProjections = (sql, entry, seq, factJson) => {
|
|
668
|
-
const { event } = entry;
|
|
669
|
-
if (event.namespace !== effectDurableAgentNamespace) return;
|
|
670
|
-
writeCommandProjection(sql, event, seq, factJson);
|
|
671
|
-
writeCommandInputProjection(sql, event, seq);
|
|
672
|
-
writeMessageProjection(sql, event, seq);
|
|
673
|
-
writeSummaryProjection(sql, event, seq);
|
|
674
|
-
writeContextRebaseProjection(sql, event, seq);
|
|
675
|
-
};
|
|
676
|
-
const writeCommandProjection = (sql, event, seq, factJson) => {
|
|
677
|
-
const payload = Schema.decodeUnknownSync(ProjectionPayload)(event.payload);
|
|
678
|
-
switch (event.type) {
|
|
679
|
-
case commandAdmittedEventType: {
|
|
680
|
-
const command = Schema.decodeUnknownSync(AdmittedCommandProjection)(payload.command);
|
|
681
|
-
const commandId = command.commandId;
|
|
682
|
-
if (commandId === void 0) throw new Error("CommandAdmitted missing command.commandId");
|
|
683
|
-
sql.exec(`
|
|
684
|
-
INSERT INTO _eda_command_state (
|
|
685
|
-
command_id,
|
|
686
|
-
admitted_seq,
|
|
687
|
-
status,
|
|
688
|
-
idempotency_key,
|
|
689
|
-
payload_json
|
|
690
|
-
) VALUES (?, ?, ?, ?, ?)
|
|
691
|
-
ON CONFLICT(command_id) DO UPDATE SET
|
|
692
|
-
admitted_seq = excluded.admitted_seq,
|
|
693
|
-
status = excluded.status,
|
|
694
|
-
idempotency_key = excluded.idempotency_key,
|
|
695
|
-
payload_json = excluded.payload_json
|
|
696
|
-
`, commandId, seq, "admitted", command.idempotencyKey ?? null, factJson);
|
|
697
|
-
return;
|
|
698
|
-
}
|
|
699
|
-
case commandStartedEventType:
|
|
700
|
-
writeCommandStatus(sql, payload.commandId, seq, "started", factJson);
|
|
701
|
-
return;
|
|
702
|
-
case commandCompletedEventType:
|
|
703
|
-
writeCommandStatus(sql, payload.commandId, seq, "completed", factJson);
|
|
704
|
-
return;
|
|
705
|
-
case commandFailedEventType:
|
|
706
|
-
writeCommandStatus(sql, payload.commandId, seq, "failed", factJson);
|
|
707
|
-
return;
|
|
708
|
-
case commandCancelledEventType:
|
|
709
|
-
writeCommandStatus(sql, payload.commandId, seq, "cancelled", factJson);
|
|
710
|
-
return;
|
|
711
|
-
default: return;
|
|
712
|
-
}
|
|
713
|
-
};
|
|
714
|
-
const writeCommandStatus = (sql, commandId, seq, status, payloadJson) => {
|
|
715
|
-
if (commandId === void 0) throw new Error(`${status} command event missing commandId`);
|
|
716
|
-
sql.exec(`
|
|
717
|
-
INSERT INTO _eda_command_state (
|
|
718
|
-
command_id,
|
|
719
|
-
admitted_seq,
|
|
720
|
-
status,
|
|
721
|
-
idempotency_key,
|
|
722
|
-
payload_json
|
|
723
|
-
) VALUES (?, ?, ?, NULL, ?)
|
|
724
|
-
ON CONFLICT(command_id) DO UPDATE SET
|
|
725
|
-
status = excluded.status,
|
|
726
|
-
payload_json = excluded.payload_json
|
|
727
|
-
`, commandId, seq, status, payloadJson);
|
|
728
|
-
};
|
|
729
|
-
const writeCommandInputProjection = (sql, event, seq) => {
|
|
730
|
-
if (event.type !== commandAdmittedEventType) return;
|
|
731
|
-
const command = Schema.encodeSync(DurableEventEnvelope)(event).payload.command;
|
|
732
|
-
const commandId = command?.commandId;
|
|
733
|
-
if (commandId === void 0) throw new Error("CommandAdmitted missing command.commandId");
|
|
734
|
-
sql.exec(`
|
|
735
|
-
INSERT INTO _eda_command_inputs (
|
|
736
|
-
command_id,
|
|
737
|
-
admitted_seq,
|
|
738
|
-
payload_json
|
|
739
|
-
) VALUES (?, ?, ?)
|
|
740
|
-
ON CONFLICT(command_id) DO UPDATE SET
|
|
741
|
-
admitted_seq = excluded.admitted_seq,
|
|
742
|
-
payload_json = excluded.payload_json
|
|
743
|
-
`, commandId, seq, stringifyJsonForColumn(command, "_eda_command_inputs.payload_json"));
|
|
744
|
-
};
|
|
745
|
-
const contextMessageEventTypes = new Set([
|
|
746
|
-
systemMessageCommittedEventType,
|
|
747
|
-
userMessageCommittedEventType,
|
|
748
|
-
steeringMessageQueuedEventType,
|
|
749
|
-
assistantMessageCommittedEventType,
|
|
750
|
-
assistantMessageImportedEventType,
|
|
751
|
-
assistantPartialCommittedEventType
|
|
752
|
-
]);
|
|
753
|
-
/** Persist model-visible message bodies with the seq that exposed them to context. */
|
|
754
|
-
const writeMessageProjection = (sql, event, seq) => {
|
|
755
|
-
if (!contextMessageEventTypes.has(event.type)) return;
|
|
756
|
-
const encoded = Schema.encodeSync(DurableEventEnvelope)(event);
|
|
757
|
-
const messageId = encoded.payload.messageId;
|
|
758
|
-
if (messageId === void 0) throw new Error(`${event.type} missing messageId`);
|
|
759
|
-
sql.exec(`
|
|
760
|
-
INSERT INTO _eda_context_messages (
|
|
761
|
-
message_id,
|
|
762
|
-
context_seq,
|
|
763
|
-
payload_json
|
|
764
|
-
) VALUES (?, ?, ?)
|
|
765
|
-
ON CONFLICT(message_id) DO UPDATE SET
|
|
766
|
-
context_seq = excluded.context_seq,
|
|
767
|
-
payload_json = excluded.payload_json
|
|
768
|
-
`, messageId, seq, stringifyJsonForColumn(encoded.payload, "_eda_context_messages.payload_json"));
|
|
769
|
-
};
|
|
770
|
-
/**
|
|
771
|
-
* Persist a cumulative summary artifact without making it the active context.
|
|
772
|
-
*
|
|
773
|
-
* `ContextRebased` selects summaries in the framework reduced-state checkpoint;
|
|
774
|
-
* failed compactions can leave orphaned summaries without changing future context.
|
|
775
|
-
*/
|
|
776
|
-
const writeSummaryProjection = (sql, event, seq) => {
|
|
777
|
-
if (event.type !== summaryCreatedEventType) return;
|
|
778
|
-
const payload = event.payload;
|
|
779
|
-
const summaryId = payload.summaryId;
|
|
780
|
-
if (summaryId === void 0) throw new Error("SummaryCreated missing summaryId");
|
|
781
|
-
if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
|
|
782
|
-
const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
|
|
783
|
-
if (summary.summaryId !== summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
|
|
784
|
-
if (summary.compactionId !== payload.compactionId) throw new Error("SummaryCreated compactionId does not match summary payload");
|
|
785
|
-
sql.exec(`
|
|
786
|
-
INSERT INTO _eda_context_summaries (
|
|
787
|
-
summary_id,
|
|
788
|
-
created_seq,
|
|
789
|
-
payload_json
|
|
790
|
-
) VALUES (?, ?, ?)
|
|
791
|
-
ON CONFLICT(summary_id) DO UPDATE SET
|
|
792
|
-
created_seq = excluded.created_seq,
|
|
793
|
-
payload_json = excluded.payload_json
|
|
794
|
-
`, summaryId, seq, stringifyJsonForColumn(summary, "_eda_context_summaries.payload_json"));
|
|
795
|
-
};
|
|
796
|
-
/** Validate that `ContextRebased` points at a committed summary sidecar. */
|
|
797
|
-
const writeContextRebaseProjection = (sql, event, _seq) => {
|
|
798
|
-
if (event.type !== contextRebasedEventType) return;
|
|
799
|
-
const payload = event.payload;
|
|
800
|
-
if (payload.summaryId === void 0) throw new Error("ContextRebased missing summaryId");
|
|
801
|
-
const summary = readSummaryPayloadOptional(sql, SummaryId.make(String(payload.summaryId)));
|
|
802
|
-
if (summary === void 0) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
|
|
803
|
-
if (summary.compactionId !== payload.compactionId) throw new Error("ContextRebased summary compactionId does not match event payload");
|
|
804
|
-
if (summary.retainedFromContextSeq !== payload.retainedFromContextSeq) throw new Error("ContextRebased retained cursor does not match summary payload");
|
|
805
|
-
};
|
|
806
|
-
/**
|
|
807
|
-
* Lookup prior command admission through `_eda_command_state` instead of genesis replay.
|
|
808
|
-
*
|
|
809
|
-
* Idempotency key wins over explicit command id so caller-owned retry keys remain
|
|
810
|
-
* the stable dedupe surface for external ingress.
|
|
811
|
-
*/
|
|
812
|
-
const findCommandAdmissionRow = (sql, commandId, idempotencyKey) => {
|
|
813
|
-
if (idempotencyKey !== void 0) {
|
|
814
|
-
const row = sql.exec(`
|
|
815
|
-
SELECT admitted_seq
|
|
816
|
-
FROM _eda_command_state
|
|
817
|
-
WHERE idempotency_key = ?
|
|
818
|
-
`, idempotencyKey).toArray()[0];
|
|
819
|
-
if (row !== void 0) return row;
|
|
820
|
-
}
|
|
821
|
-
if (commandId === void 0) return;
|
|
822
|
-
return sql.exec(`
|
|
823
|
-
SELECT admitted_seq
|
|
824
|
-
FROM _eda_command_state
|
|
825
|
-
WHERE command_id = ?
|
|
826
|
-
`, commandId).toArray()[0];
|
|
827
|
-
};
|
|
828
|
-
/** Serialize and size-check one JSON column before it reaches DO SQLite. */
|
|
829
|
-
const stringifyJsonForColumn = (value, column) => {
|
|
830
|
-
const json = JSON.stringify(value);
|
|
831
|
-
if (json === void 0) throw new Error(`${column} value is not JSON serializable`);
|
|
832
|
-
const bytes = jsonEncoder.encode(json).byteLength;
|
|
833
|
-
if (bytes > 15e5) throw new Error(`${column} serialized JSON is ${bytes} bytes; hard cap is ${durableObjectSerializedJsonHardCapBytes} bytes`);
|
|
834
|
-
return json;
|
|
835
|
-
};
|
|
836
|
-
const durableStoreError = (operation, cause) => new EDASessionStoreError({ message: cause instanceof Error ? `${operation}: ${cause.message}` : `${operation}: ${String(cause)}` });
|
|
837
|
-
//#endregion
|
|
838
232
|
//#region src/runtime/runtime-layer.ts
|
|
839
233
|
/** Compose the platform-neutral runtime with Cloudflare persistence and lifecycle adapters. */
|
|
840
|
-
const makeEDADurableObjectRuntimeLayer = ({ config, compactionExecutorLayer, compactionPolicyLayer, keepAlive, modelResolverLayer, promptProjectorLayer, reducers, runSchedulerLayer, sessionEventObserverLayer, sessionId, sinks, storage, toolkit, toolRegistry, tracer }) => {
|
|
234
|
+
const makeEDADurableObjectRuntimeLayer = ({ appEvents, config, idGeneratorLayer, compactionExecutorLayer, compactionPolicyLayer, keepAlive, modelResolverLayer, promptProjectorLayer, reducers, runSchedulerLayer, sessionEventObserverLayer, sessionId, sinks, storage, toolkit, toolRegistry, tracer, transcript }) => {
|
|
235
|
+
const lifecycle = keepAlive ?? new DurableObjectKeepAlive(storage);
|
|
236
|
+
const keepAliveLayer = EDAKeepAlive.FromAcquire(() => lifecycle.acquire());
|
|
841
237
|
return makeEDARuntimeLayer({
|
|
238
|
+
appEvents,
|
|
842
239
|
config,
|
|
240
|
+
idGeneratorLayer,
|
|
843
241
|
compactionExecutorLayer,
|
|
844
242
|
compactionPolicyLayer,
|
|
845
|
-
keepAliveLayer
|
|
243
|
+
keepAliveLayer,
|
|
846
244
|
modelResolverLayer,
|
|
847
245
|
promptProjectorLayer,
|
|
848
246
|
runSchedulerLayer,
|
|
247
|
+
runSchedulingWakeupLayer: Layer.succeed(RunSchedulingWakeup, { setPending: (pending) => Effect.tryPromise({
|
|
248
|
+
try: () => lifecycle.setRunSchedulingPending(pending),
|
|
249
|
+
catch: (error) => new EDASessionStoreError({ message: `Persisting run scheduling wakeup: ${String(error)}` })
|
|
250
|
+
}) }),
|
|
849
251
|
reducerRegistryLayer: EDAReducerRegistry.Live(reducers ?? []),
|
|
850
252
|
sessionEventObserverLayer,
|
|
851
253
|
sessionId,
|
|
852
254
|
sessionStoreLayer: DurableObjectSessionStore.layer({
|
|
853
255
|
sessionId,
|
|
854
|
-
storage
|
|
256
|
+
storage,
|
|
257
|
+
...transcript === void 0 ? {} : { transcript }
|
|
855
258
|
}),
|
|
856
259
|
sinkCheckpointStoreLayer: DurableObjectSinkCheckpointStore.layer(storage),
|
|
857
260
|
sinks,
|
|
@@ -870,7 +273,7 @@ var EDASessionRuntime = class {
|
|
|
870
273
|
building;
|
|
871
274
|
constructor(options) {
|
|
872
275
|
this.options = options;
|
|
873
|
-
this.keepAlive = options.keepAlive ?? new DurableObjectKeepAlive(options.storage, options.background);
|
|
276
|
+
this.keepAlive = options.keepAlive ?? new DurableObjectKeepAlive(options.alarmStorage ?? options.storage, options.background);
|
|
874
277
|
}
|
|
875
278
|
static migrate = (storage) => Effect.gen(function* () {
|
|
876
279
|
yield* DurableObjectSessionStore.migrate(storage);
|
|
@@ -889,7 +292,7 @@ var EDASessionRuntime = class {
|
|
|
889
292
|
}
|
|
890
293
|
async alarm(sessionId) {
|
|
891
294
|
const resolved = sessionId ?? this.state?.sessionId;
|
|
892
|
-
if (resolved !== void 0) await this.
|
|
295
|
+
if (resolved !== void 0) await this.run(resolved, (runtime) => runtime.retryRunSchedulingDelivery());
|
|
893
296
|
await this.keepAlive.alarm();
|
|
894
297
|
}
|
|
895
298
|
async destroy() {
|
|
@@ -918,7 +321,9 @@ var EDASessionRuntime = class {
|
|
|
918
321
|
}
|
|
919
322
|
async build(sessionId) {
|
|
920
323
|
const runtime = ManagedRuntime.make(makeEDADurableObjectRuntimeLayer({
|
|
324
|
+
appEvents: this.options.appEvents,
|
|
921
325
|
config: this.options.config,
|
|
326
|
+
idGeneratorLayer: this.options.idGeneratorLayer,
|
|
922
327
|
compactionExecutorLayer: this.options.compactionExecutorLayer,
|
|
923
328
|
compactionPolicyLayer: this.options.compactionPolicyLayer,
|
|
924
329
|
keepAlive: this.keepAlive,
|
|
@@ -932,7 +337,8 @@ var EDASessionRuntime = class {
|
|
|
932
337
|
storage: this.options.storage,
|
|
933
338
|
toolkit: resolveFactory(this.options.toolkit, sessionId),
|
|
934
339
|
toolRegistry: resolveFactory(this.options.toolRegistry, sessionId),
|
|
935
|
-
tracer: resolveFactory(this.options.tracer, sessionId)
|
|
340
|
+
tracer: resolveFactory(this.options.tracer, sessionId),
|
|
341
|
+
transcript: resolveFactory(this.options.transcript, sessionId)
|
|
936
342
|
}));
|
|
937
343
|
const state = {
|
|
938
344
|
runtime,
|
|
@@ -967,13 +373,27 @@ const EDAWebSocketAttachment = Schema.Struct({
|
|
|
967
373
|
state: Schema.Unknown
|
|
968
374
|
}))
|
|
969
375
|
});
|
|
376
|
+
/**
|
|
377
|
+
* State required to resume a transcript-window socket after hibernation: the transport receipts,
|
|
378
|
+
* the applied cut, the subscription base and unanswered requests. Staged chunk data is never
|
|
379
|
+
* persisted; a checkpoint that names a transfer cannot resume it.
|
|
380
|
+
*/
|
|
381
|
+
const EDATranscriptWebSocketAttachment = Schema.Struct({
|
|
382
|
+
kind: Schema.Literal("eda-transcript-v1"),
|
|
383
|
+
sessionId: SessionId,
|
|
384
|
+
subscriberId: SubscriberId,
|
|
385
|
+
trace: EDATraceMetadata,
|
|
386
|
+
delivery: EDATranscriptDeliveryCheckpoint
|
|
387
|
+
});
|
|
388
|
+
/** Either socket kind an EDA Durable Object accepts. */
|
|
389
|
+
const EDAAnyWebSocketAttachment = Schema.Union([EDAWebSocketAttachment, EDATranscriptWebSocketAttachment]);
|
|
970
390
|
/** Decode and classify an attachment read from Cloudflare's structured-clone boundary. */
|
|
971
391
|
const decodeWebSocketAttachment = async (input) => {
|
|
972
392
|
if (input === null || input === void 0) return { _tag: "Missing" };
|
|
973
393
|
try {
|
|
974
394
|
return {
|
|
975
395
|
_tag: "Decoded",
|
|
976
|
-
attachment: await Effect.runPromise(Schema.decodeUnknownEffect(
|
|
396
|
+
attachment: await Effect.runPromise(Schema.decodeUnknownEffect(EDAAnyWebSocketAttachment)(input))
|
|
977
397
|
};
|
|
978
398
|
} catch {
|
|
979
399
|
return { _tag: "Malformed" };
|
|
@@ -981,6 +401,506 @@ const decodeWebSocketAttachment = async (input) => {
|
|
|
981
401
|
};
|
|
982
402
|
/** Encode before serialization so schema transformations cannot leak into attachments. */
|
|
983
403
|
const encodeWebSocketAttachment = (attachment) => Schema.encodeSync(EDAWebSocketAttachment)(attachment);
|
|
404
|
+
/** Encode a transcript socket attachment for Cloudflare's structured-clone boundary. */
|
|
405
|
+
const encodeTranscriptWebSocketAttachment = (attachment) => Schema.encodeSync(EDATranscriptWebSocketAttachment)(attachment);
|
|
406
|
+
//#endregion
|
|
407
|
+
//#region src/websocket/transcript-sockets.ts
|
|
408
|
+
const defaultActiveContentCadenceMs = 50;
|
|
409
|
+
/** Largest client frame accepted, in UTF-8 bytes; requests are persisted, so this bounds the attachment too. */
|
|
410
|
+
const maxClientFrameBytes = 2048;
|
|
411
|
+
const decodeClientFrame = Schema.decodeUnknownExit(EDATranscriptClientFrame);
|
|
412
|
+
/**
|
|
413
|
+
* Owns transcript-window sockets: the window data source beneath the frame encoder.
|
|
414
|
+
*
|
|
415
|
+
* Every subscriber is served strictly in order. Committed changes are coalesced to the complete
|
|
416
|
+
* boundary a store read returns; a request is answered by one read at one cut; and each update is
|
|
417
|
+
* sent from its own captured snapshot before the next is planned.
|
|
418
|
+
*
|
|
419
|
+
* **Publication fence.** Append publication, ephemeral publication and window capture share one
|
|
420
|
+
* fence: the active-content accumulator folds every published event in order, and a capture is
|
|
421
|
+
* served with live content only when the accumulator has folded exactly the window's cut. Durable
|
|
422
|
+
* commit precedes live publication, so a window read between the two would otherwise pair a
|
|
423
|
+
* committed inference with its stale live parts. A capture that would cross the fence waits for
|
|
424
|
+
* publication to catch up.
|
|
425
|
+
*/
|
|
426
|
+
var EDATranscriptSockets = class {
|
|
427
|
+
options;
|
|
428
|
+
sockets = /* @__PURE__ */ new Map();
|
|
429
|
+
active = emptyTranscriptActiveContentState;
|
|
430
|
+
timerArmed = false;
|
|
431
|
+
background = /* @__PURE__ */ new Set();
|
|
432
|
+
flowControl;
|
|
433
|
+
policy;
|
|
434
|
+
limits;
|
|
435
|
+
cadenceMs;
|
|
436
|
+
fenceWaitMs;
|
|
437
|
+
maxTotalStagedBytes;
|
|
438
|
+
schedule;
|
|
439
|
+
now;
|
|
440
|
+
constructor(options) {
|
|
441
|
+
this.options = options;
|
|
442
|
+
this.flowControl = options.flowControl ?? defaultEDAWebSocketFlowControl;
|
|
443
|
+
this.policy = options.subscriptionPolicy ?? defaultTranscriptSubscriptionPolicy;
|
|
444
|
+
this.limits = options.deliveryLimits ?? defaultEDATranscriptDeliveryLimits;
|
|
445
|
+
this.cadenceMs = options.activeContentCadenceMs ?? 50;
|
|
446
|
+
this.fenceWaitMs = options.fenceWaitMs ?? 1e3;
|
|
447
|
+
this.maxTotalStagedBytes = options.maxTotalStagedBytes ?? 33554432;
|
|
448
|
+
this.schedule = options.schedule ?? ((delayMs, run) => {
|
|
449
|
+
setTimeout(run, delayMs);
|
|
450
|
+
});
|
|
451
|
+
this.now = options.now ?? Date.now;
|
|
452
|
+
}
|
|
453
|
+
has(webSocket) {
|
|
454
|
+
return this.sockets.has(webSocket);
|
|
455
|
+
}
|
|
456
|
+
/** Transcript sockets this isolate holds, for hosts that cannot enumerate accepted sockets. */
|
|
457
|
+
webSockets() {
|
|
458
|
+
return [...this.sockets.keys()];
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Register a freshly accepted socket and greet it. Synchronous so the attachment exists before
|
|
462
|
+
* any platform callback can observe the socket.
|
|
463
|
+
*/
|
|
464
|
+
accept(input) {
|
|
465
|
+
const socket = {
|
|
466
|
+
sessionId: input.sessionId,
|
|
467
|
+
subscriberId: SubscriberId.make(crypto.randomUUID()),
|
|
468
|
+
trace: input.trace,
|
|
469
|
+
delivery: makeTranscriptDeliveryState(this.flowControl),
|
|
470
|
+
queue: Promise.resolve(),
|
|
471
|
+
dirty: false,
|
|
472
|
+
sentActiveRevision: void 0,
|
|
473
|
+
last: void 0,
|
|
474
|
+
fenceWaitingSinceMs: void 0,
|
|
475
|
+
scheduledDrain: void 0,
|
|
476
|
+
stagedBytes: 0,
|
|
477
|
+
activeSentAtMs: void 0,
|
|
478
|
+
cadenceDue: false
|
|
479
|
+
};
|
|
480
|
+
this.sockets.set(input.webSocket, socket);
|
|
481
|
+
if (!this.persist(input.webSocket, socket)) return;
|
|
482
|
+
this.sendText(input.webSocket, encodeEDATranscriptServerFrame({
|
|
483
|
+
_tag: "hello",
|
|
484
|
+
protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,
|
|
485
|
+
subscriberId: socket.subscriberId,
|
|
486
|
+
resumeSeq: 0,
|
|
487
|
+
flowControl: this.flowControl,
|
|
488
|
+
negotiation: edaTranscriptNegotiation
|
|
489
|
+
}));
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Adopt a socket that survived hibernation. A socket that was mid-transfer lost its staged
|
|
493
|
+
* chunks with the isolate: it is closed, and the client reconnects and resubscribes.
|
|
494
|
+
*/
|
|
495
|
+
restore(webSocket, attachment) {
|
|
496
|
+
const restored = restoreTranscriptDeliveryState(this.flowControl, attachment.delivery);
|
|
497
|
+
if (restored._tag === "TransferLost") {
|
|
498
|
+
this.close(webSocket, EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE, "transfer-lost");
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
this.sockets.set(webSocket, {
|
|
502
|
+
sessionId: attachment.sessionId,
|
|
503
|
+
subscriberId: attachment.subscriberId,
|
|
504
|
+
trace: attachment.trace,
|
|
505
|
+
delivery: restored.state,
|
|
506
|
+
queue: Promise.resolve(),
|
|
507
|
+
dirty: true,
|
|
508
|
+
sentActiveRevision: void 0,
|
|
509
|
+
last: void 0,
|
|
510
|
+
fenceWaitingSinceMs: void 0,
|
|
511
|
+
scheduledDrain: void 0,
|
|
512
|
+
stagedBytes: 0,
|
|
513
|
+
activeSentAtMs: void 0,
|
|
514
|
+
cadenceDue: false
|
|
515
|
+
});
|
|
516
|
+
return true;
|
|
517
|
+
}
|
|
518
|
+
closed(webSocket) {
|
|
519
|
+
this.sockets.delete(webSocket);
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Observe one published event, in publication order. Folds it into the active-content
|
|
523
|
+
* accumulator synchronously, then lets each listed subscriber act on it: a durable event
|
|
524
|
+
* schedules a read at the new boundary; changed live content is coalesced to the display
|
|
525
|
+
* cadence.
|
|
526
|
+
*
|
|
527
|
+
* Reads are scheduled, not awaited, so subscribers never hold the session's append gate. The
|
|
528
|
+
* fence does not need the gate: every capture is checked against the accumulator's folded head
|
|
529
|
+
* when its read resolves.
|
|
530
|
+
*/
|
|
531
|
+
onPublished(event, webSockets) {
|
|
532
|
+
const revision = this.active.revision;
|
|
533
|
+
this.active = foldTranscriptActiveContent(this.active, event);
|
|
534
|
+
if (event.event.durability !== "durable") {
|
|
535
|
+
if (this.active.revision !== revision) this.armCadence();
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
for (const webSocket of webSockets) {
|
|
539
|
+
const socket = this.sockets.get(webSocket);
|
|
540
|
+
if (socket === void 0) continue;
|
|
541
|
+
socket.dirty = true;
|
|
542
|
+
this.track(this.drain(webSocket, socket));
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/** Serve sockets restored from hibernation after a publication was folded. */
|
|
546
|
+
serveRestored(webSockets) {
|
|
547
|
+
for (const webSocket of webSockets) {
|
|
548
|
+
const socket = this.sockets.get(webSocket);
|
|
549
|
+
if (socket === void 0) continue;
|
|
550
|
+
socket.dirty = true;
|
|
551
|
+
this.track(this.drain(webSocket, socket));
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* The session's log was destroyed: live content belongs to a log that no longer exists and
|
|
556
|
+
* every subscription names its incarnation. Close the transcript sockets this isolate holds,
|
|
557
|
+
* and any listed still-hibernated socket, so clients resubscribe.
|
|
558
|
+
*/
|
|
559
|
+
reset(hibernated = []) {
|
|
560
|
+
this.active = emptyTranscriptActiveContentState;
|
|
561
|
+
for (const webSocket of /* @__PURE__ */ new Set([...this.sockets.keys(), ...hibernated])) this.close(webSocket, EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE, "session-reset");
|
|
562
|
+
}
|
|
563
|
+
async message(webSocket, message) {
|
|
564
|
+
const socket = this.sockets.get(webSocket);
|
|
565
|
+
if (socket === void 0) {
|
|
566
|
+
this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
if (message === EDA_WEB_SOCKET_PING_MESSAGE) {
|
|
570
|
+
this.sendText(webSocket, EDA_WEB_SOCKET_PONG_MESSAGE);
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
if (message.length > maxClientFrameBytes || utf8ByteLength(message) > maxClientFrameBytes) {
|
|
574
|
+
this.protocolError(webSocket, "Client frame too large");
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
let json;
|
|
578
|
+
try {
|
|
579
|
+
json = JSON.parse(message);
|
|
580
|
+
} catch {
|
|
581
|
+
this.protocolError(webSocket, "Malformed client frame");
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
const decoded = decodeClientFrame(json);
|
|
585
|
+
if (Exit.isFailure(decoded)) {
|
|
586
|
+
this.protocolError(webSocket, "Unknown client frame");
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
const frame = decoded.value;
|
|
590
|
+
if (frame._tag === "ping") return;
|
|
591
|
+
await this.enqueue(webSocket, socket, async () => {
|
|
592
|
+
if (frame._tag === "ack") {
|
|
593
|
+
const acked = onTranscriptAck(socket.delivery, frame);
|
|
594
|
+
if (acked._tag === "ProtocolError") {
|
|
595
|
+
this.protocolError(webSocket, acked.message);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
if (acked._tag === "Ignored") return;
|
|
599
|
+
socket.delivery = acked.state;
|
|
600
|
+
if (!this.persist(webSocket, socket)) return;
|
|
601
|
+
} else {
|
|
602
|
+
const queued = enqueueTranscriptRequest(socket.delivery, frame, this.limits);
|
|
603
|
+
if (queued === void 0) {
|
|
604
|
+
this.protocolError(webSocket, "Too many unanswered transcript requests");
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
socket.delivery = queued;
|
|
608
|
+
if (!this.persist(webSocket, socket)) return;
|
|
609
|
+
}
|
|
610
|
+
await this.drainNow(webSocket, socket);
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
/** Wait for scheduled reads and cadence flushes; for orderly shutdown and tests. */
|
|
614
|
+
async settled() {
|
|
615
|
+
while (this.background.size > 0) await Promise.all([...this.background]);
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Own scheduled subscriber work until it settles. Drains never reject: `enqueue` contains every
|
|
619
|
+
* failure and closes the socket.
|
|
620
|
+
*/
|
|
621
|
+
track(work) {
|
|
622
|
+
const tracked = work.finally(() => {
|
|
623
|
+
this.background.delete(tracked);
|
|
624
|
+
});
|
|
625
|
+
this.background.add(tracked);
|
|
626
|
+
}
|
|
627
|
+
armCadence() {
|
|
628
|
+
if (this.timerArmed) return;
|
|
629
|
+
this.timerArmed = true;
|
|
630
|
+
this.schedule(this.cadenceMs, () => {
|
|
631
|
+
this.timerArmed = false;
|
|
632
|
+
for (const [webSocket, socket] of this.sockets) {
|
|
633
|
+
socket.cadenceDue = true;
|
|
634
|
+
this.track(this.drain(webSocket, socket));
|
|
635
|
+
}
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Schedule one drain, coalescing with a drain that is scheduled but not yet running. A drain
|
|
640
|
+
* that is already running re-checks `dirty` before it returns, so nothing is missed.
|
|
641
|
+
*/
|
|
642
|
+
drain(webSocket, socket) {
|
|
643
|
+
if (socket.scheduledDrain !== void 0) return socket.scheduledDrain;
|
|
644
|
+
const scheduled = this.enqueue(webSocket, socket, () => {
|
|
645
|
+
socket.scheduledDrain = void 0;
|
|
646
|
+
return this.drainNow(webSocket, socket);
|
|
647
|
+
});
|
|
648
|
+
socket.scheduledDrain = scheduled;
|
|
649
|
+
return scheduled;
|
|
650
|
+
}
|
|
651
|
+
/** Send everything this subscriber is owed, one complete update at a time. */
|
|
652
|
+
async drainNow(webSocket, socket) {
|
|
653
|
+
for (;;) {
|
|
654
|
+
if (this.sockets.get(webSocket) !== socket) return;
|
|
655
|
+
const nowMs = this.now();
|
|
656
|
+
if (transcriptAckTimedOut(socket.delivery, nowMs)) {
|
|
657
|
+
this.sendText(webSocket, encodeEDATranscriptServerFrame({
|
|
658
|
+
_tag: "lagged",
|
|
659
|
+
resumeSeq: socket.delivery.appliedThroughSeq,
|
|
660
|
+
reason: "ack-timeout"
|
|
661
|
+
}));
|
|
662
|
+
this.close(webSocket, EDA_WS_CLOSE_LAGGED, laggedCloseReason(socket.delivery.appliedThroughSeq));
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
if (socket.delivery.transfer !== void 0) {
|
|
666
|
+
const pumped = pumpTranscriptTransfer(socket.delivery, nowMs);
|
|
667
|
+
if (pumped.frames.length === 0) return;
|
|
668
|
+
socket.delivery = pumped.state;
|
|
669
|
+
if (pumped.state.transfer === void 0) socket.stagedBytes = 0;
|
|
670
|
+
if (!this.persistAndSend(webSocket, socket, pumped.frames)) return;
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
if (transcriptDeliveryCapacity(socket.delivery) <= 0) return;
|
|
674
|
+
const request = socket.delivery.requests[0];
|
|
675
|
+
const base = socket.delivery.subscription;
|
|
676
|
+
if (request === void 0) {
|
|
677
|
+
if (base === void 0) return;
|
|
678
|
+
if (!socket.dirty) {
|
|
679
|
+
if (socket.sentActiveRevision === this.active.revision) {
|
|
680
|
+
socket.cadenceDue = false;
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
if (!(socket.cadenceDue || socket.activeSentAtMs === void 0 || nowMs - socket.activeSentAtMs >= this.cadenceMs)) {
|
|
684
|
+
this.armCadence();
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
const sent = await this.sendActiveOnly(webSocket, socket);
|
|
688
|
+
if (sent === "NeedsRead") {
|
|
689
|
+
socket.dirty = true;
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
if (sent === "Failed") return;
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
const subscriptionRequest = request === void 0 ? { _tag: "Refresh" } : toSubscriptionRequest(request);
|
|
697
|
+
socket.dirty = false;
|
|
698
|
+
const read = await Effect.runPromiseExit(readTranscriptSubscription(this.options.transcriptStore, base, subscriptionRequest, this.policy));
|
|
699
|
+
if (this.sockets.get(webSocket) !== socket) return;
|
|
700
|
+
if (Exit.isFailure(read)) {
|
|
701
|
+
await Effect.runPromise(Effect.logError("EDA transcript window read failed", {
|
|
702
|
+
cause: read.cause,
|
|
703
|
+
subscriberId: socket.subscriberId
|
|
704
|
+
}));
|
|
705
|
+
this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "read-failed");
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
const { window, patchBase } = read.value;
|
|
709
|
+
const active = this.active;
|
|
710
|
+
const fenced = !(window.readiness._tag === "Ready") || window.throughSeq === active.publishedThroughSeq || window.throughSeq > active.publishedThroughSeq && active.inference === void 0;
|
|
711
|
+
if (!fenced) {
|
|
712
|
+
socket.fenceWaitingSinceMs ??= nowMs;
|
|
713
|
+
if (nowMs - socket.fenceWaitingSinceMs < this.fenceWaitMs) {
|
|
714
|
+
socket.dirty = true;
|
|
715
|
+
this.armCadence();
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
socket.fenceWaitingSinceMs = void 0;
|
|
720
|
+
const update = planTranscriptUpdate({
|
|
721
|
+
patchBase,
|
|
722
|
+
window,
|
|
723
|
+
updateSeq: socket.delivery.nextUpdateSeq,
|
|
724
|
+
activeContent: fenced ? transcriptActiveContentOf(active) : [],
|
|
725
|
+
includeActiveContent: !fenced || socket.sentActiveRevision !== active.revision || window.readiness._tag === "Ready" && socket.last !== void 0 && socket.last.readiness._tag !== "Ready",
|
|
726
|
+
...request?.requestId === void 0 ? {} : { requestId: request.requestId }
|
|
727
|
+
});
|
|
728
|
+
const remaining = request === void 0 ? socket.delivery.requests : socket.delivery.requests.slice(1);
|
|
729
|
+
if (request === void 0 && this.isNoop(socket, update)) continue;
|
|
730
|
+
if (!await this.start(webSocket, socket, update, transcriptSubscriptionBaseOf(window), remaining)) return;
|
|
731
|
+
socket.sentActiveRevision = active.revision;
|
|
732
|
+
if (update.activeContent !== void 0) {
|
|
733
|
+
socket.cadenceDue = false;
|
|
734
|
+
socket.activeSentAtMs = this.now();
|
|
735
|
+
}
|
|
736
|
+
socket.last = {
|
|
737
|
+
readiness: window.readiness,
|
|
738
|
+
hasOlder: window.hasOlder,
|
|
739
|
+
hasNewer: window.hasNewer,
|
|
740
|
+
dependencyIds: update.dependencyIds
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Publish changed live content without a store read. Valid only while the accumulator has
|
|
746
|
+
* folded exactly the subscriber's last cut; otherwise a commit is pending and a read is needed.
|
|
747
|
+
*/
|
|
748
|
+
async sendActiveOnly(webSocket, socket) {
|
|
749
|
+
const base = socket.delivery.subscription;
|
|
750
|
+
const last = socket.last;
|
|
751
|
+
const active = this.active;
|
|
752
|
+
if (last !== void 0 && last.readiness._tag !== "Ready") {
|
|
753
|
+
socket.sentActiveRevision = active.revision;
|
|
754
|
+
return "Sent";
|
|
755
|
+
}
|
|
756
|
+
if (base === void 0 || last === void 0 || active.publishedThroughSeq !== base.throughSeq) return "NeedsRead";
|
|
757
|
+
const update = {
|
|
758
|
+
updateSeq: socket.delivery.nextUpdateSeq,
|
|
759
|
+
mode: "patch",
|
|
760
|
+
incarnation: base.incarnation,
|
|
761
|
+
version: base.version,
|
|
762
|
+
throughSeq: base.throughSeq,
|
|
763
|
+
...base.coverage === void 0 ? {} : { coverage: base.coverage },
|
|
764
|
+
hasOlder: last.hasOlder,
|
|
765
|
+
hasNewer: last.hasNewer,
|
|
766
|
+
readiness: last.readiness,
|
|
767
|
+
records: [],
|
|
768
|
+
dependencies: [],
|
|
769
|
+
dependencyIds: last.dependencyIds,
|
|
770
|
+
activeContent: transcriptActiveContentOf(active)
|
|
771
|
+
};
|
|
772
|
+
if (!await this.start(webSocket, socket, update, base, socket.delivery.requests)) return "Failed";
|
|
773
|
+
socket.sentActiveRevision = active.revision;
|
|
774
|
+
socket.cadenceDue = false;
|
|
775
|
+
socket.activeSentAtMs = this.now();
|
|
776
|
+
return "Sent";
|
|
777
|
+
}
|
|
778
|
+
/** A refresh that changes nothing the client holds is not sent. */
|
|
779
|
+
isNoop(socket, update) {
|
|
780
|
+
const base = socket.delivery.subscription;
|
|
781
|
+
const last = socket.last;
|
|
782
|
+
return base !== void 0 && last !== void 0 && update.mode === "patch" && update.records.length === 0 && update.dependencies.length === 0 && update.activeContent === void 0 && update.throughSeq === base.throughSeq && update.hasOlder === last.hasOlder && update.hasNewer === last.hasNewer && JSON.stringify(update.coverage) === JSON.stringify(base.coverage) && JSON.stringify(update.readiness) === JSON.stringify(last.readiness);
|
|
783
|
+
}
|
|
784
|
+
async start(webSocket, socket, update, subscription, requests) {
|
|
785
|
+
const encodedUpdate = encodeEDATranscriptUpdate(update);
|
|
786
|
+
const bytes = utf8ByteLength(encodedUpdate);
|
|
787
|
+
if (utf8ByteLength(edaTranscriptUpdateFrameText(socket.delivery.nextFrameId, encodedUpdate)) > this.flowControl.maxFrameBytes && this.stagedBytes() + bytes > this.maxTotalStagedBytes) {
|
|
788
|
+
this.close(webSocket, EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE, "staging-budget");
|
|
789
|
+
return false;
|
|
790
|
+
}
|
|
791
|
+
const started = startTranscriptUpdate({
|
|
792
|
+
...socket.delivery,
|
|
793
|
+
requests
|
|
794
|
+
}, {
|
|
795
|
+
update,
|
|
796
|
+
encodedUpdate,
|
|
797
|
+
subscription
|
|
798
|
+
}, this.limits, this.now());
|
|
799
|
+
if (started._tag === "TooLarge") {
|
|
800
|
+
await Effect.runPromise(Effect.logError("EDA transcript update exceeds the staging bound", {
|
|
801
|
+
bytes: started.bytes,
|
|
802
|
+
subscriberId: socket.subscriberId
|
|
803
|
+
}));
|
|
804
|
+
this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "update-too-large");
|
|
805
|
+
return false;
|
|
806
|
+
}
|
|
807
|
+
socket.delivery = started.state;
|
|
808
|
+
socket.stagedBytes = started.state.transfer === void 0 ? 0 : bytes;
|
|
809
|
+
return this.persistAndSend(webSocket, socket, started.frames);
|
|
810
|
+
}
|
|
811
|
+
/** Bytes of chunked updates still being transferred, across every socket of this object. */
|
|
812
|
+
stagedBytes() {
|
|
813
|
+
let total = 0;
|
|
814
|
+
for (const socket of this.sockets.values()) total += socket.stagedBytes;
|
|
815
|
+
return total;
|
|
816
|
+
}
|
|
817
|
+
/** Persist the checkpoint before any frame it accounts for becomes client-visible. */
|
|
818
|
+
persistAndSend(webSocket, socket, frames) {
|
|
819
|
+
if (!this.persist(webSocket, socket)) return false;
|
|
820
|
+
for (const frame of frames) if (!this.sendText(webSocket, frame)) return false;
|
|
821
|
+
return true;
|
|
822
|
+
}
|
|
823
|
+
persist(webSocket, socket) {
|
|
824
|
+
try {
|
|
825
|
+
webSocket.serializeAttachment(encodeTranscriptWebSocketAttachment(EDATranscriptWebSocketAttachment.make({
|
|
826
|
+
kind: "eda-transcript-v1",
|
|
827
|
+
sessionId: socket.sessionId,
|
|
828
|
+
subscriberId: socket.subscriberId,
|
|
829
|
+
trace: socket.trace,
|
|
830
|
+
delivery: checkpointTranscriptDelivery(socket.delivery)
|
|
831
|
+
})));
|
|
832
|
+
return true;
|
|
833
|
+
} catch (error) {
|
|
834
|
+
Effect.runSync(Effect.logError("EDA transcript socket attachment failed", {
|
|
835
|
+
error,
|
|
836
|
+
subscriberId: socket.subscriberId
|
|
837
|
+
}));
|
|
838
|
+
this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "attachment-failed");
|
|
839
|
+
return false;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
sendText(webSocket, text) {
|
|
843
|
+
try {
|
|
844
|
+
webSocket.send(text);
|
|
845
|
+
return true;
|
|
846
|
+
} catch (error) {
|
|
847
|
+
Effect.runSync(Effect.logWarning("EDA transcript socket send failed", { error }));
|
|
848
|
+
this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "send-failed");
|
|
849
|
+
return false;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
protocolError(webSocket, message) {
|
|
853
|
+
this.sendText(webSocket, encodeEDATranscriptServerFrame({
|
|
854
|
+
_tag: "error",
|
|
855
|
+
message: message.slice(0, 120)
|
|
856
|
+
}));
|
|
857
|
+
this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
|
|
858
|
+
}
|
|
859
|
+
enqueue(webSocket, socket, operation) {
|
|
860
|
+
const run = async () => {
|
|
861
|
+
try {
|
|
862
|
+
await operation();
|
|
863
|
+
} catch (error) {
|
|
864
|
+
await Effect.runPromise(Effect.logError("EDA transcript socket operation failed", {
|
|
865
|
+
error,
|
|
866
|
+
subscriberId: socket.subscriberId
|
|
867
|
+
}));
|
|
868
|
+
this.close(webSocket, EDA_WS_CLOSE_SEND_FAILED, "subscriber-failed");
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
const next = socket.queue.then(run);
|
|
872
|
+
socket.queue = next;
|
|
873
|
+
return next;
|
|
874
|
+
}
|
|
875
|
+
close(webSocket, code, reason) {
|
|
876
|
+
this.sockets.delete(webSocket);
|
|
877
|
+
try {
|
|
878
|
+
webSocket.close(code, reason);
|
|
879
|
+
} catch {}
|
|
880
|
+
}
|
|
881
|
+
};
|
|
882
|
+
const toSubscriptionRequest = (frame) => {
|
|
883
|
+
switch (frame._tag) {
|
|
884
|
+
case "subscribe": return {
|
|
885
|
+
_tag: "Subscribe",
|
|
886
|
+
tail: frame.tail ?? false,
|
|
887
|
+
...frame.range === void 0 ? {} : { range: frame.range },
|
|
888
|
+
...frame.since === void 0 ? {} : { since: frame.since },
|
|
889
|
+
...frame.count === void 0 ? {} : { count: frame.count }
|
|
890
|
+
};
|
|
891
|
+
case "page": return {
|
|
892
|
+
_tag: "Page",
|
|
893
|
+
direction: frame.direction,
|
|
894
|
+
cursor: frame.cursor,
|
|
895
|
+
count: frame.count
|
|
896
|
+
};
|
|
897
|
+
case "retain": return {
|
|
898
|
+
_tag: "Retain",
|
|
899
|
+
from: frame.from,
|
|
900
|
+
to: frame.to
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
};
|
|
984
904
|
//#endregion
|
|
985
905
|
//#region src/websocket/connection-manager.ts
|
|
986
906
|
/**
|
|
@@ -991,8 +911,60 @@ var EDAWebSocketConnectionManager = class {
|
|
|
991
911
|
options;
|
|
992
912
|
observerLayer = SessionEventObserver.FromHandler((event) => Effect.tryPromise(() => this.fanoutPublishedEvent(event)).pipe(Effect.catchCause((cause) => Effect.logError("EDA WebSocket event observer recovered from a host failure", { cause }))));
|
|
993
913
|
sockets = /* @__PURE__ */ new Map();
|
|
914
|
+
transcript;
|
|
994
915
|
constructor(options) {
|
|
995
916
|
this.options = options;
|
|
917
|
+
this.transcript = options.transcript === void 0 ? void 0 : new EDATranscriptSockets(options.transcript);
|
|
918
|
+
}
|
|
919
|
+
/** Whether this host serves transcript-window sockets. */
|
|
920
|
+
get supportsTranscript() {
|
|
921
|
+
return this.transcript !== void 0;
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Accept a transcript-window socket. Reads are storage-level, so this never prepares the
|
|
925
|
+
* session runtime. Call immediately after `ctx.acceptWebSocket()`.
|
|
926
|
+
*/
|
|
927
|
+
acceptTranscript(input) {
|
|
928
|
+
if (this.transcript === void 0) {
|
|
929
|
+
this.close(input.webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "unsupported");
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
this.transcript.accept(input);
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* The session's log was destroyed: drop live content and close every transcript socket,
|
|
936
|
+
* including those still hibernated, which a just-woken object has not restored yet. They are
|
|
937
|
+
* recognised by their attachment kind without being restored.
|
|
938
|
+
*/
|
|
939
|
+
/**
|
|
940
|
+
* Re-read every transcript socket, held or hibernated, at the current cut. The served version
|
|
941
|
+
* changed without a publication (a rebuilt version activated), so each subscriber receives a
|
|
942
|
+
* complete replacement (design §7 step 4, §9.4).
|
|
943
|
+
*/
|
|
944
|
+
async refreshTranscript() {
|
|
945
|
+
if (this.transcript === void 0) return;
|
|
946
|
+
const sockets = [...this.transcript.webSockets()];
|
|
947
|
+
for (const webSocket of this.options.getWebSockets?.() ?? []) {
|
|
948
|
+
if (this.sockets.has(webSocket) || this.transcript.has(webSocket)) continue;
|
|
949
|
+
const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());
|
|
950
|
+
if (decoded._tag !== "Decoded" || decoded.attachment.kind !== "eda-transcript-v1") continue;
|
|
951
|
+
if (this.transcript.has(webSocket) || this.transcript.restore(webSocket, decoded.attachment)) sockets.push(webSocket);
|
|
952
|
+
}
|
|
953
|
+
this.transcript.serveRestored(sockets);
|
|
954
|
+
}
|
|
955
|
+
async resetTranscript() {
|
|
956
|
+
if (this.transcript === void 0) return;
|
|
957
|
+
const hibernated = [];
|
|
958
|
+
for (const webSocket of this.options.getWebSockets?.() ?? []) {
|
|
959
|
+
if (this.sockets.has(webSocket) || this.transcript.has(webSocket)) continue;
|
|
960
|
+
const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());
|
|
961
|
+
if (decoded._tag === "Decoded" && decoded.attachment.kind === "eda-transcript-v1") hibernated.push(webSocket);
|
|
962
|
+
}
|
|
963
|
+
this.transcript.reset(hibernated);
|
|
964
|
+
}
|
|
965
|
+
/** Wait for scheduled transcript flushes; for orderly shutdown and tests. */
|
|
966
|
+
async settled() {
|
|
967
|
+
await this.transcript?.settled();
|
|
996
968
|
}
|
|
997
969
|
resolveProjection(id) {
|
|
998
970
|
if (id === void 0) return void 0;
|
|
@@ -1036,7 +1008,13 @@ var EDAWebSocketConnectionManager = class {
|
|
|
1036
1008
|
}
|
|
1037
1009
|
return;
|
|
1038
1010
|
}
|
|
1039
|
-
const
|
|
1011
|
+
const restored = await this.restore(webSocket);
|
|
1012
|
+
if (restored === "transcript") {
|
|
1013
|
+
await this.transcript?.message(webSocket, message);
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
if (restored === "closed") return;
|
|
1017
|
+
const state = restored;
|
|
1040
1018
|
if (state === void 0) {
|
|
1041
1019
|
this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
|
|
1042
1020
|
return;
|
|
@@ -1055,6 +1033,7 @@ var EDAWebSocketConnectionManager = class {
|
|
|
1055
1033
|
}
|
|
1056
1034
|
closed(webSocket) {
|
|
1057
1035
|
this.sockets.delete(webSocket);
|
|
1036
|
+
this.transcript?.closed(webSocket);
|
|
1058
1037
|
}
|
|
1059
1038
|
async flushDeferredCatchUp(sessionId) {
|
|
1060
1039
|
const deliveries = [];
|
|
@@ -1069,11 +1048,22 @@ var EDAWebSocketConnectionManager = class {
|
|
|
1069
1048
|
await Promise.all(deliveries);
|
|
1070
1049
|
}
|
|
1071
1050
|
async fanoutPublishedEvent(event) {
|
|
1072
|
-
const
|
|
1051
|
+
const heldTranscriptSockets = new Set(this.transcript?.webSockets() ?? []);
|
|
1052
|
+
this.transcript?.onPublished(event, [...heldTranscriptSockets]);
|
|
1053
|
+
const webSockets = /* @__PURE__ */ new Set([
|
|
1054
|
+
...this.options.getWebSockets?.() ?? [],
|
|
1055
|
+
...this.sockets.keys(),
|
|
1056
|
+
...this.transcript?.webSockets() ?? []
|
|
1057
|
+
]);
|
|
1073
1058
|
const deliveries = [];
|
|
1059
|
+
const transcriptSockets = [];
|
|
1074
1060
|
for (const webSocket of webSockets) {
|
|
1075
1061
|
const state = await this.restore(webSocket);
|
|
1076
|
-
if (state ===
|
|
1062
|
+
if (state === "transcript") {
|
|
1063
|
+
transcriptSockets.push(webSocket);
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
if (state === void 0 || state === "closed") continue;
|
|
1077
1067
|
deliveries.push(this.enqueue(webSocket, state, async () => {
|
|
1078
1068
|
if (event.event.durability !== "durable") {
|
|
1079
1069
|
await this.interpret(webSocket, state, onEphemeralEvent(state.delivery, event, Date.now()));
|
|
@@ -1092,16 +1082,28 @@ var EDAWebSocketConnectionManager = class {
|
|
|
1092
1082
|
await this.readAndDeliver(webSocket, state, state.delivery.sentDurableThroughSeq);
|
|
1093
1083
|
}));
|
|
1094
1084
|
}
|
|
1085
|
+
this.transcript?.serveRestored(transcriptSockets.filter((webSocket) => !heldTranscriptSockets.has(webSocket)));
|
|
1095
1086
|
await Promise.all(deliveries);
|
|
1096
1087
|
}
|
|
1097
1088
|
async restore(webSocket) {
|
|
1098
1089
|
const existing = this.sockets.get(webSocket);
|
|
1099
1090
|
if (existing !== void 0) return existing;
|
|
1091
|
+
if (this.transcript?.has(webSocket) === true) return "transcript";
|
|
1100
1092
|
const decoded = await decodeWebSocketAttachment(webSocket.deserializeAttachment());
|
|
1101
1093
|
if (decoded._tag !== "Decoded") {
|
|
1102
1094
|
this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
|
|
1103
1095
|
return;
|
|
1104
1096
|
}
|
|
1097
|
+
const restoredMeanwhile = this.sockets.get(webSocket);
|
|
1098
|
+
if (restoredMeanwhile !== void 0) return restoredMeanwhile;
|
|
1099
|
+
if (this.transcript?.has(webSocket) === true) return "transcript";
|
|
1100
|
+
if (decoded.attachment.kind === "eda-transcript-v1") {
|
|
1101
|
+
if (this.transcript === void 0) {
|
|
1102
|
+
this.close(webSocket, EDA_WS_CLOSE_PROTOCOL_ERROR, "protocol");
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
return this.transcript.restore(webSocket, decoded.attachment) ? "transcript" : "closed";
|
|
1106
|
+
}
|
|
1105
1107
|
const attachment = decoded.attachment;
|
|
1106
1108
|
const projectionState = attachment.projection === void 0 ? void 0 : await this.decodeProjectionState(attachment.projection.id, attachment.projection.state);
|
|
1107
1109
|
if (attachment.projection !== void 0 && projectionState === void 0) {
|
|
@@ -1309,7 +1311,8 @@ var EDASessionController = class {
|
|
|
1309
1311
|
"eda.seq.after": afterSeq
|
|
1310
1312
|
})))),
|
|
1311
1313
|
webSocketProjection: options.webSocketProjection,
|
|
1312
|
-
webSocketProtocol: options.webSocketProtocol
|
|
1314
|
+
webSocketProtocol: options.webSocketProtocol,
|
|
1315
|
+
...options.transcriptSockets === void 0 ? {} : { transcript: options.transcriptSockets }
|
|
1313
1316
|
});
|
|
1314
1317
|
this.runtime = new EDASessionRuntime({
|
|
1315
1318
|
...options,
|
|
@@ -1317,6 +1320,18 @@ var EDASessionController = class {
|
|
|
1317
1320
|
});
|
|
1318
1321
|
}
|
|
1319
1322
|
static migrate = EDASessionRuntime.migrate;
|
|
1323
|
+
/** Trusted reconciliation read; never submits or grants replacement work. */
|
|
1324
|
+
runRequestOutcome(input) {
|
|
1325
|
+
return this.run(input.sessionId, (eda) => eda.runRequestOutcome(input.requestId));
|
|
1326
|
+
}
|
|
1327
|
+
/** Trusted scheduler ingress. Hosts must authorize callers before invoking this method. */
|
|
1328
|
+
grantRun(input) {
|
|
1329
|
+
const parent = input.trace?.parent;
|
|
1330
|
+
return this.run(input.sessionId, (eda) => {
|
|
1331
|
+
const operation = eda.grantRun(input.command);
|
|
1332
|
+
return parent === void 0 || parent === null ? operation : operation.pipe(Effect.withParentSpan(toEdaExternalSpan(parent)));
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1320
1335
|
submit(input) {
|
|
1321
1336
|
const trace = input.trace ?? makeRootEDATraceMetadata();
|
|
1322
1337
|
return this.run(input.sessionId, (eda) => eda.submit(input.command).pipe(Effect.withSpan("agent.command.submit", hostSpanOptions(trace, {
|
|
@@ -1351,9 +1366,6 @@ var EDASessionController = class {
|
|
|
1351
1366
|
snapshot(input) {
|
|
1352
1367
|
return this.query(input, (eda) => eda.snapshot(), "agent.session.snapshot");
|
|
1353
1368
|
}
|
|
1354
|
-
messages(input) {
|
|
1355
|
-
return this.query(input, (eda) => eda.messages(), "agent.messages.list");
|
|
1356
|
-
}
|
|
1357
1369
|
acceptEventWebSocket(input) {
|
|
1358
1370
|
return this.acceptEventWebSocketUnhosted(input);
|
|
1359
1371
|
}
|
|
@@ -1384,6 +1396,25 @@ var EDASessionController = class {
|
|
|
1384
1396
|
acceptPreparedEventWebSocket(input) {
|
|
1385
1397
|
return this.webSockets.accept(input);
|
|
1386
1398
|
}
|
|
1399
|
+
/** The served transcript version changed: give every transcript socket a replacement. */
|
|
1400
|
+
refreshTranscriptWebSockets() {
|
|
1401
|
+
return this.webSockets.refreshTranscript();
|
|
1402
|
+
}
|
|
1403
|
+
/** Whether transcript-window sockets are served. */
|
|
1404
|
+
get supportsTranscriptWebSocket() {
|
|
1405
|
+
return this.webSockets.supportsTranscript;
|
|
1406
|
+
}
|
|
1407
|
+
/**
|
|
1408
|
+
* Register a transcript-window socket right after the host accepted it. Never prepares the
|
|
1409
|
+
* model runtime: windows are storage-level reads.
|
|
1410
|
+
*/
|
|
1411
|
+
acceptTranscriptWebSocket(input) {
|
|
1412
|
+
this.webSockets.acceptTranscript({
|
|
1413
|
+
sessionId: input.sessionId,
|
|
1414
|
+
trace: input.trace ?? makeRootEDATraceMetadata(),
|
|
1415
|
+
webSocket: input.webSocket
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1387
1418
|
webSocketMessage(webSocket, message) {
|
|
1388
1419
|
return this.webSockets.message(webSocket, message);
|
|
1389
1420
|
}
|
|
@@ -1395,6 +1426,7 @@ var EDASessionController = class {
|
|
|
1395
1426
|
}
|
|
1396
1427
|
async destroy(_input) {
|
|
1397
1428
|
await this.runtime.destroy();
|
|
1429
|
+
await this.webSockets.resetTranscript();
|
|
1398
1430
|
}
|
|
1399
1431
|
async alarm(input) {
|
|
1400
1432
|
if (input !== void 0) await this.prepareSession(input.sessionId);
|
|
@@ -1429,6 +1461,6 @@ const hostSpanOptions = (trace, attributes) => ({
|
|
|
1429
1461
|
...trace.parent === null ? {} : { parent: toEdaExternalSpan(trace.parent) }
|
|
1430
1462
|
});
|
|
1431
1463
|
//#endregion
|
|
1432
|
-
export {
|
|
1464
|
+
export { makeEDADurableObjectRuntimeLayer as i, defaultActiveContentCadenceMs as n, EDAWebSocketProjectionId as r, EDASessionController as t };
|
|
1433
1465
|
|
|
1434
|
-
//# sourceMappingURL=session-controller-
|
|
1466
|
+
//# sourceMappingURL=session-controller-BCtnyAEw.js.map
|