Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threads.ts

259 lines8.1 KB

1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type EnvironmentId as EnvironmentIdType,
4 type OrchestrationV2ThreadProjection,
5 type OrchestrationV2ThreadStreamItem,
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 { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.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<OrchestrationV2ThreadProjection>;
30 readonly status: EnvironmentThreadStatus;
31 readonly error: Option.Option<string>;
33​
34export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = {
35 data: Option.none(),
36 status: "empty",
37 error: Option.none(),
38};
39​
40function statusWithoutLiveData(
41 data: Option.Option<OrchestrationV2ThreadProjection>,
42): EnvironmentThreadStatus {
43 return Option.isSome(data) ? "cached" : "empty";
45​
46function formatThreadError(cause: Cause.Cause<unknown>): string {
47 const error = Cause.squash(cause);
48 return error instanceof Error && error.message.trim().length > 0
49 ? error.message
50 : "Could not synchronize the thread.";
52​
53export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make")(function* (
54 threadId: ThreadIdType,
55) {
56 const supervisor = yield* EnvironmentSupervisor;
57 const cache = yield* EnvironmentCacheStore;
58 const environmentId = supervisor.target.environmentId;
59 const cached = yield* cache.loadThread(environmentId, threadId).pipe(
60 Effect.catch((error) =>
61 Effect.logWarning("Could not load cached thread.").pipe(
62 Effect.annotateLogs({
63 environmentId,
64 threadId,
65 error: error.message,
66 }),
67 Effect.as(Option.none<OrchestrationV2ThreadProjection>()),
68 ),
69 ),
70 );
71 const state = yield* SubscriptionRef.make<EnvironmentThreadState>({
72 data: cached,
73 status: statusWithoutLiveData(cached),
74 error: Option.none(),
75 });
76 const lastSequence = yield* SubscriptionRef.make(0);
77 const persistence = yield* Queue.sliding<OrchestrationV2ThreadProjection>(1);
78​
79 const persist = Effect.fn("EnvironmentThreadState.persist")(function* (
80 thread: OrchestrationV2ThreadProjection,
81 ) {
82 yield* cache.saveThread(environmentId, thread).pipe(
83 Effect.catch((error) =>
84 Effect.logWarning("Could not persist the thread cache.").pipe(
85 Effect.annotateLogs({
86 environmentId,
87 threadId,
88 error: error.message,
89 }),
90 ),
91 ),
92 );
93 });
94​
95 yield* Stream.fromQueue(persistence).pipe(
96 Stream.debounce("500 millis"),
97 Stream.runForEach(persist),
98 Effect.forkScoped,
99 );
100​
101 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
102 ...current,
103 status: "synchronizing" as const,
104 error: Option.none(),
105 }));
106 const setReady = SubscriptionRef.update(state, (current) =>
107 current.status === "live" || current.status === "deleted"
108 ? current
109 : {
110 ...current,
111 status: "synchronizing" as const,
112 error: Option.none(),
113 },
114 );
115 const setDisconnected = SubscriptionRef.update(state, (current) => ({
116 ...current,
117 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
118 }));
119 const setStreamError = (cause: Cause.Cause<unknown>) =>
120 SubscriptionRef.update(state, (current) => ({
121 ...current,
122 status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
123 error: Option.some(formatThreadError(cause)),
124 }));
125​
126 const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* (
127 thread: OrchestrationV2ThreadProjection,
128 ) {
129 yield* SubscriptionRef.set(state, {
130 data: Option.some(thread),
131 status: "live",
132 error: Option.none(),
133 });
134 yield* Queue.offer(persistence, 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: OrchestrationV2ThreadStreamItem,
158 ) {
159 if (item.kind === "snapshot") {
160 yield* SubscriptionRef.set(lastSequence, item.snapshotSequence);
161 yield* setThread(item.projection);
162 return;
163 }
164​
165 const sequence = yield* SubscriptionRef.get(lastSequence);
166 if (item.sequence <= sequence) {
167 return;
168 }
169 yield* SubscriptionRef.set(lastSequence, item.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 if (item.event.type === "thread.deleted") {
179 yield* setDeleted();
180 return;
181 }
182 const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event);
183 if (next !== null) {
184 yield* setThread(next);
185 }
186 });
187​
188 yield* SubscriptionRef.changes(supervisor.state).pipe(
189 Stream.runForEach((connectionState) => {
190 switch (connectionProjectionPhase(connectionState)) {
191 case "synchronizing":
192 return setSynchronizing;
193 case "disconnected":
194 return setDisconnected;
195 case "ready":
196 return setReady;
197 }
198 }),
199 Effect.forkScoped,
200 );
201​
202 yield* setSynchronizing;
203 yield* subscribe(
204 ORCHESTRATION_V2_WS_METHODS.subscribeThread,
205 { threadId },
206 {
207 onExpectedFailure: setStreamError,
208 retryExpectedFailureAfter: "250 millis",
209 },
210 ).pipe(Stream.runForEach(applyItem), Effect.forkScoped);
211​
212 yield* Effect.addFinalizer(() =>
213 SubscriptionRef.get(state).pipe(
214 Effect.flatMap((current) =>
215 Option.match(current.data, {
216 onNone: () => Effect.void,
217 onSome: persist,
218 }),
219 ),
220 ),
221 );
222​
223 return state;
224});
225​
226export function threadStateChanges(environmentId: EnvironmentIdType, threadId: ThreadIdType) {
227 return followStreamInEnvironment(
228 environmentId,
229 Stream.unwrap(makeEnvironmentThreadState(threadId).pipe(Effect.map(SubscriptionRef.changes))),
230 );
232​
233export function createEnvironmentThreadStateAtoms<R, E>(
234 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
235) {
236 const family = Atom.family((key: string) => {
237 const { environmentId, threadId } = parseThreadKey(key);
238 return runtime
239 .atom(threadStateChanges(environmentId, threadId), {
240 initialValue: EMPTY_ENVIRONMENT_THREAD_STATE,
241 })
242 .pipe(
243 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
244 Atom.withLabel(`environment-thread-state:${key}`),
245 );
246 });
247​
248 return {
249 stateAtom: (environmentId: EnvironmentIdType, threadId: ThreadIdType) =>
250 family(threadKey({ environmentId, threadId })),
251 };
253​
254export * from "./archivedThreads.ts";
255export * from "./checkpointDiff.ts";
256export * from "./composerPathSearch.ts";
257export * from "./threadCommands.ts";
258export * from "./threadDetail.ts";
259export * from "./threadShell.ts";