Open History to see the last commit
1import {
2 ORCHESTRATION_WS_METHODS,
3 type EnvironmentId as EnvironmentIdType,
4 type OrchestrationThread,
5 type OrchestrationThreadDetailSnapshot,
6 type OrchestrationThreadStreamItem,
7 type ThreadId as ThreadIdType,
8} from "@v12/contracts";
9import * as Cause from "effect/Cause";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Stream from "effect/Stream";
14import * as SubscriptionRef from "effect/SubscriptionRef";
15import { Atom } from "effect/unstable/reactivity";
16
17import { EnvironmentRegistry } from "../connection/registry.ts";
18import { connectionProjectionPhase } from "../connection/model.ts";
19import { EnvironmentSupervisor } from "../connection/supervisor.ts";
20import { EnvironmentCacheStore } from "../platform/persistence.ts";
21import { subscribe } from "../rpc/client.ts";
22import { ThreadSnapshotLoader } from "./threadSnapshotHttp.ts";
23import { parseThreadKey, threadKey } from "./entities.ts";
24import { applyThreadDetailEvent } from "./threadReducer.ts";
25import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
26import { followStreamInEnvironment } from "./runtime.ts";
27import {
28 EMPTY_ENVIRONMENT_THREAD_STATE,
29 type EnvironmentThreadState,
30 type EnvironmentThreadStatus,
31} from "./threadState.ts";
32
33function statusWithoutLiveData(data: Option.Option<OrchestrationThread>): EnvironmentThreadStatus {
34 return Option.isSome(data) ? "cached" : "empty";
35}
36
37function formatThreadError(cause: Cause.Cause<unknown>): string {
38 const error = Cause.squash(cause);
39 return error instanceof Error && error.message.trim().length > 0
40 ? error.message
41 : "Could not synchronize the thread.";
42}
43
44export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
45 threadId: ThreadIdType,
46) {
47 const supervisor = yield* EnvironmentSupervisor;
48 const cache = yield* EnvironmentCacheStore;
49 const snapshotLoader = yield* ThreadSnapshotLoader;
50 const environmentId = supervisor.target.environmentId;
51 const cached = yield* cache.loadThread(environmentId, threadId).pipe(
52 Effect.catch((error) =>
53 Effect.logWarning("Could not load cached thread.").pipe(
54 Effect.annotateLogs({
55 environmentId,
56 threadId,
57 error: error.message,
58 }),
59 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
60 ),
61 ),
62 );
63 const cachedThread = Option.map(cached, (snapshot) => snapshot.thread);
64 const state = yield* SubscriptionRef.make<EnvironmentThreadState>({
65 data: cachedThread,
66 status: statusWithoutLiveData(cachedThread),
67 error: Option.none(),
68 });
69 // Seed the resume cursor from the cached snapshot so a warm cache can catch up
70 // via `afterSequence` instead of re-downloading the full thread body.
71 const lastSequence = yield* SubscriptionRef.make(
72 Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }),
73 );
74 const persistence = yield* Queue.sliding<OrchestrationThreadDetailSnapshot>(1);
75
76 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
77 snapshot: OrchestrationThreadDetailSnapshot,
78 ) {
79 yield* cache.saveThread(environmentId, snapshot).pipe(
80 Effect.catch((error) =>
81 Effect.logWarning("Could not persist the thread cache.").pipe(
82 Effect.annotateLogs({
83 environmentId,
84 threadId,
85 error: error.message,
86 }),
87 ),
88 ),
89 );
90 });
91
92 yield* Stream.fromQueue(persistence).pipe(
93 Stream.debounce("500 millis"),
94 Stream.runForEach(persist),
95 Effect.forkScoped,
96 );
97
98 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
99 ...current,
100 status: "synchronizing" as const,
101 error: Option.none(),
102 }));
103 const setReady = SubscriptionRef.update(state, (current) =>
104 current.status === "live" || current.status === "deleted"
105 ? current
106 : {
107 ...current,
108 status: "synchronizing" as const,
109 error: Option.none(),
110 },
111 );
112 const setDisconnected = SubscriptionRef.update(state, (current) => ({
113 ...current,
114 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
115 }));
116 const setStreamError = (cause: Cause.Cause<unknown>) =>
117 SubscriptionRef.update(state, (current) => ({
118 ...current,
119 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
120 error: Option.some(formatThreadError(cause)),
121 }));
122
123 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
124 thread: OrchestrationThread,
125 ) {
126 yield* SubscriptionRef.set(state, {
127 data: Option.some(thread),
128 status: "live",
129 error: Option.none(),
130 });
131 // Persist the thread together with the sequence it reflects so the next warm
132 // cache can resume from exactly here.
133 const snapshotSequence = yield* SubscriptionRef.get(lastSequence);
134 yield* Queue.offer(persistence, { snapshotSequence, thread });
135 });
136
137 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
138 yield* SubscriptionRef.set(state, {
139 data: Option.none(),
140 status: "deleted",
141 error: Option.none(),
142 });
143 yield* cache.removeThread(environmentId, threadId).pipe(
144 Effect.catch((error) =>
145 Effect.logWarning("Could not remove the cached thread.").pipe(
146 Effect.annotateLogs({
147 environmentId,
148 threadId,
149 error: error.message,
150 }),
151 ),
152 ),
153 );
154 });
155
156 const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
157 item: OrchestrationThreadStreamItem,
158 ) {
159 if (item.kind === "snapshot") {
160 yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence);
161 yield* setThread(item.snapshot.thread);
162 return;
163 }
164
165 const sequence = yield* SubscriptionRef.get(lastSequence);
166 if (item.event.sequence <= sequence) {
167 return;
168 }
169 yield* SubscriptionRef.set(lastSequence, item.event.sequence);
170
171 const current = yield* SubscriptionRef.get(state);
172 if (Option.isNone(current.data)) {
173 if (item.event.type === "thread.deleted") {
174 yield* setDeleted();
175 }
176 return;
177 }
178 const result = applyThreadDetailEvent(current.data.value, item.event);
179 if (result.kind === "updated") {
180 yield* setThread(result.thread);
181 } else if (result.kind === "deleted") {
182 yield* setDeleted();
183 }
184 });
185
186 yield* SubscriptionRef.changes(supervisor.state).pipe(
187 Stream.runForEach((connectionState) => {
188 switch (connectionProjectionPhase(connectionState)) {
189 case "synchronizing":
190 return setSynchronizing;
191 case "disconnected":
192 return setDisconnected;
193 case "ready":
194 return setReady;
195 }
196 }),
197 Effect.forkScoped,
198 );
199
200 yield* setSynchronizing;
201 yield* Effect.forkScoped(
202 Effect.gen(function* () {
203 // Establish the base snapshot to resume from, minimizing bytes over the
204 // wire:
205 // - Warm cache: reuse the cached snapshot (zero network) and resume via
206 // `afterSequence` so we only receive events since the cached sequence.
207 // - Cold cache: load the full snapshot over HTTP (gzip-compressible, and
208 // off the socket), then resume via `afterSequence`.
209 // If no base can be established we fall back to the socket-embedded
210 // snapshot so the thread still synchronizes. Overlapping/replayed events
211 // are deduped by sequence in applyItem.
212 const base = Option.isSome(cached)
213 ? cached
214 : yield* Effect.gen(function* () {
215 // Cold cache only: wait for a prepared connection so we can
216 // authenticate the HTTP request; this mirrors the socket path, which
217 // likewise waits for a live session.
218 const prepared = yield* SubscriptionRef.changes(supervisor.prepared).pipe(
219 Stream.filter(Option.isSome),
220 Stream.map((current) => current.value),
221 Stream.runHead,
222 );
223 return Option.isSome(prepared)
224 ? yield* snapshotLoader.load(prepared.value, threadId)
225 : Option.none<OrchestrationThreadDetailSnapshot>();
226 });
227
228 if (Option.isSome(base)) {
229 yield* applyItem({ kind: "snapshot", snapshot: base.value });
230 }
231
232 const subscribeInput = Option.match(base, {
233 onNone: () => ({ threadId }),
234 onSome: (snapshot) => ({ threadId, afterSequence: snapshot.snapshotSequence }),
235 });
236
237 yield* subscribe(ORCHESTRATION_WS_METHODS.subscribeThread, subscribeInput, {
238 onExpectedFailure: setStreamError,
239 retryExpectedFailureAfter: "250 millis",
240 }).pipe(Stream.runForEach(applyItem));
241 }),
242 );
243
244 yield* Effect.addFinalizer(() =>
245 Effect.all([SubscriptionRef.get(state), SubscriptionRef.get(lastSequence)]).pipe(
246 Effect.flatMap(([current, snapshotSequence]) =>
247 Option.match(current.data, {
248 onNone: () => Effect.void,
249 onSome: (thread) => persist({ snapshotSequence, thread }),
250 }),
251 ),
252 ),
253 );
254
255 return state;
256});
257
258export function threadStateChanges(environmentId: EnvironmentIdType, threadId: ThreadIdType) {
259 return followStreamInEnvironment(
260 environmentId,
261 Stream.unwrap(makeEnvironmentThreadState(threadId).pipe(Effect.map(SubscriptionRef.changes))),
262 );
263}
264
265export function createEnvironmentThreadStateAtoms<R, E>(
266 runtime: Atom.AtomRuntime<
267 EnvironmentRegistry | EnvironmentCacheStore | ThreadSnapshotLoader | R,
268 E
269 >,
270) {
271 const family = Atom.family((key: string) => {
272 const { environmentId, threadId } = parseThreadKey(key);
273 return runtime
274 .atom(threadStateChanges(environmentId, threadId), {
275 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
276 })
277 .pipe(
278 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
279 Atom.withLabel(`environment-thread-state:${key}`),
280 );
281 });
282
283 return {
284 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
285 family(threadKey({ environmentId, threadId })),
286 };
287}
288
289export * from "./archivedThreads.ts";
290export * from "./checkpointDiff.ts";
291export * from "./threadSnapshotHttp.ts";
292export * from "./composerPathSearch.ts";
293export * from "./threadCommands.ts";
294export * from "./threadDetail.ts";
295export * from "./threadReducer.ts";
296export * from "./threadShell.ts";
297export * from "./threadState.ts";