Open History to see the last commit
1import {
2 ORCHESTRATION_WS_METHODS,
3 type EnvironmentId as EnvironmentIdType,
4 type OrchestrationThread,
5 type OrchestrationThreadStreamItem,
6 type ThreadId as ThreadIdType,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Queue from "effect/Queue";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14import { Atom } from "effect/unstable/reactivity";
15
16import { EnvironmentRegistry } from "../connection/registry.ts";
17import { connectionProjectionPhase } from "../connection/model.ts";
18import { EnvironmentSupervisor } from "../connection/supervisor.ts";
19import { EnvironmentCacheStore } from "../platform/persistence.ts";
20import { subscribe } from "../rpc/client.ts";
21import { parseThreadKey, threadKey } from "./entities.ts";
22import { applyThreadDetailEvent } from "./threadReducer.ts";
23import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
24import { followStreamInEnvironment } from "./runtime.ts";
25
26export type EnvironmentThreadStatus = "empty" | "cached" | "synchronizing" | "live" | "deleted";
27
28export interface EnvironmentThreadState {
29 readonly data: Option.Option<OrchestrationThread>;
30 readonly status: EnvironmentThreadStatus;
31 readonly error: Option.Option<string>;
32}
33
34export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = {
35 data: Option.none(),
36 status: "empty",
37 error: Option.none(),
38};
39
40function statusWithoutLiveData(data: Option.Option<OrchestrationThread>): EnvironmentThreadStatus {
41 return Option.isSome(data) ? "cached" : "empty";
42}
43
44function formatThreadError(cause: Cause.Cause<unknown>): string {
45 const error = Cause.squash(cause);
46 return error instanceof Error && error.message.trim().length > 0
47 ? error.message
48 : "Could not synchronize the thread.";
49}
50
51export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
52 threadId: ThreadIdType,
53) {
54 const supervisor = yield* EnvironmentSupervisor;
55 const cache = yield* EnvironmentCacheStore;
56 const environmentId = supervisor.target.environmentId;
57 const cached = yield* cache.loadThread(environmentId, threadId).pipe(
58 Effect.catch((error) =>
59 Effect.logWarning("Could not load cached thread.").pipe(
60 Effect.annotateLogs({
61 environmentId,
62 threadId,
63 error: error.message,
64 }),
65 Effect.as(Option.none<OrchestrationThread>()),
66 ),
67 ),
68 );
69 const state = yield* SubscriptionRef.make<EnvironmentThreadState>({
70 data: cached,
71 status: statusWithoutLiveData(cached),
72 error: Option.none(),
73 });
74 const lastSequence = yield* SubscriptionRef.make(0);
75 const persistence = yield* Queue.sliding<OrchestrationThread>(1);
76
77 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
78 thread: OrchestrationThread,
79 ) {
80 yield* cache.saveThread(environmentId, thread).pipe(
81 Effect.catch((error) =>
82 Effect.logWarning("Could not persist the thread cache.").pipe(
83 Effect.annotateLogs({
84 environmentId,
85 threadId,
86 error: error.message,
87 }),
88 ),
89 ),
90 );
91 });
92
93 yield* Stream.fromQueue(persistence).pipe(
94 Stream.debounce("500 millis"),
95 Stream.runForEach(persist),
96 Effect.forkScoped,
97 );
98
99 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
100 ...current,
101 status: "synchronizing" as const,
102 error: Option.none(),
103 }));
104 const setReady = SubscriptionRef.update(state, (current) =>
105 current.status === "live" || current.status === "deleted"
106 ? current
107 : {
108 ...current,
109 status: "synchronizing" as const,
110 error: Option.none(),
111 },
112 );
113 const setDisconnected = SubscriptionRef.update(state, (current) => ({
114 ...current,
115 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
116 }));
117 const setStreamError = (cause: Cause.Cause<unknown>) =>
118 SubscriptionRef.update(state, (current) => ({
119 ...current,
120 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
121 error: Option.some(formatThreadError(cause)),
122 }));
123
124 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
125 thread: OrchestrationThread,
126 ) {
127 yield* SubscriptionRef.set(state, {
128 data: Option.some(thread),
129 status: "live",
130 error: Option.none(),
131 });
132 yield* Queue.offer(persistence, thread);
133 });
134
135 const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () {
136 yield* SubscriptionRef.set(state, {
137 data: Option.none(),
138 status: "deleted",
139 error: Option.none(),
140 });
141 yield* cache.removeThread(environmentId, threadId).pipe(
142 Effect.catch((error) =>
143 Effect.logWarning("Could not remove the cached thread.").pipe(
144 Effect.annotateLogs({
145 environmentId,
146 threadId,
147 error: error.message,
148 }),
149 ),
150 ),
151 );
152 });
153
154 const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* (
155 item: OrchestrationThreadStreamItem,
156 ) {
157 if (item.kind === "snapshot") {
158 yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence);
159 yield* setThread(item.snapshot.thread);
160 return;
161 }
162
163 const sequence = yield* SubscriptionRef.get(lastSequence);
164 if (item.event.sequence <= sequence) {
165 return;
166 }
167 yield* SubscriptionRef.set(lastSequence, item.event.sequence);
168
169 const current = yield* SubscriptionRef.get(state);
170 if (Option.isNone(current.data)) {
171 if (item.event.type === "thread.deleted") {
172 yield* setDeleted();
173 }
174 return;
175 }
176 const result = applyThreadDetailEvent(current.data.value, item.event);
177 if (result.kind === "updated") {
178 yield* setThread(result.thread);
179 } else if (result.kind === "deleted") {
180 yield* setDeleted();
181 }
182 });
183
184 yield* SubscriptionRef.changes(supervisor.state).pipe(
185 Stream.runForEach((connectionState) => {
186 switch (connectionProjectionPhase(connectionState)) {
187 case "synchronizing":
188 return setSynchronizing;
189 case "disconnected":
190 return setDisconnected;
191 case "ready":
192 return setReady;
193 }
194 }),
195 Effect.forkScoped,
196 );
197
198 yield* setSynchronizing;
199 yield* subscribe(
200 ORCHESTRATION_WS_METHODS.subscribeThread,
201 { threadId },
202 {
203 onExpectedFailure: setStreamError,
204 retryExpectedFailureAfter: "250 millis",
205 },
206 ).pipe(Stream.runForEach(applyItem), Effect.forkScoped);
207
208 yield* Effect.addFinalizer(() =>
209 SubscriptionRef.get(state).pipe(
210 Effect.flatMap((current) =>
211 Option.match(current.data, {
212 onNone: () => Effect.void,
213 onSome: persist,
214 }),
215 ),
216 ),
217 );
218
219 return state;
220});
221
222export function threadStateChanges(environmentId: EnvironmentIdType, threadId: ThreadIdType) {
223 return followStreamInEnvironment(
224 environmentId,
225 Stream.unwrap(makeEnvironmentThreadState(threadId).pipe(Effect.map(SubscriptionRef.changes))),
226 );
227}
228
229export function createEnvironmentThreadStateAtoms<R, E>(
230 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
231) {
232 const family = Atom.family((key: string) => {
233 const { environmentId, threadId } = parseThreadKey(key);
234 return runtime
235 .atom(threadStateChanges(environmentId, threadId), {
236 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
237 })
238 .pipe(
239 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
240 Atom.withLabel(`environment-thread-state:${key}`),
241 );
242 });
243
244 return {
245 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
246 family(threadKey({ environmentId, threadId })),
247 };
248}
249
250export * from "./archivedThreads.ts";
251export * from "./checkpointDiff.ts";
252export * from "./composerPathSearch.ts";
253export * from "./threadCommands.ts";
254export * from "./threadDetail.ts";
255export * from "./threadReducer.ts";
256export * from "./threadShell.ts";