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

checkpointDiffState.ts

313 lines9.4 KB

1import {
2 type EnvironmentId,
3 OrchestrationGetFullThreadDiffInput,
4 type OrchestrationGetFullThreadDiffResult,
5 OrchestrationGetTurnDiffInput,
6 type OrchestrationGetTurnDiffResult,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
14​
15export type CheckpointDiffResult =
16 | OrchestrationGetTurnDiffResult
17 | OrchestrationGetFullThreadDiffResult;
18​
19export interface CheckpointDiffState {
20 readonly data: CheckpointDiffResult | null;
21 readonly error: string | null;
22 readonly isPending: boolean;
24​
25export interface CheckpointDiffTarget {
26 readonly environmentId: EnvironmentId | null;
27 readonly threadId: ThreadId | null;
28 readonly fromTurnCount: number | null;
29 readonly toTurnCount: number | null;
30 readonly ignoreWhitespace: boolean;
31 readonly cacheScope?: string | null;
33​
34export interface CheckpointDiffClient {
35 readonly getTurnDiff: (
36 input: OrchestrationGetTurnDiffInput,
37 ) => Promise<OrchestrationGetTurnDiffResult>;
38 readonly getFullThreadDiff: (
39 input: OrchestrationGetFullThreadDiffInput,
40 ) => Promise<OrchestrationGetFullThreadDiffResult>;
42​
43export const EMPTY_CHECKPOINT_DIFF_STATE = Object.freeze<CheckpointDiffState>({
44 data: null,
45 error: null,
46 isPending: false,
47});
48​
49const INITIAL_CHECKPOINT_DIFF_STATE = Object.freeze<CheckpointDiffState>({
50 data: null,
51 error: null,
52 isPending: true,
53});
54​
55const knownCheckpointDiffKeys = new Set<string>();
56​
57export const checkpointDiffStateAtom = Atom.family((key: string) => {
58 knownCheckpointDiffKeys.add(key);
59 return Atom.make(INITIAL_CHECKPOINT_DIFF_STATE).pipe(
60 Atom.keepAlive,
61 Atom.withLabel(`checkpoint-diff:${key}`),
62 );
63});
64​
65export const EMPTY_CHECKPOINT_DIFF_ATOM = Atom.make(EMPTY_CHECKPOINT_DIFF_STATE).pipe(
66 Atom.keepAlive,
67 Atom.withLabel("checkpoint-diff:null"),
68);
69​
70const decodeFullThreadDiffInput = Schema.decodeUnknownOption(OrchestrationGetFullThreadDiffInput);
71const decodeTurnDiffInput = Schema.decodeUnknownOption(OrchestrationGetTurnDiffInput);
72​
73type CheckpointDiffRequest =
74 | {
75 readonly kind: "fullThreadDiff";
76 readonly input: OrchestrationGetFullThreadDiffInput;
77 }
78 | {
79 readonly kind: "turnDiff";
80 readonly input: OrchestrationGetTurnDiffInput;
81 };
82​
83export function getCheckpointDiffTargetKey(target: CheckpointDiffTarget): string | null {
84 const decoded = decodeCheckpointDiffRequest(target);
85 if (target.environmentId === null || decoded._tag === "None") {
86 return null;
87 }
88​
89 return [
90 target.environmentId,
91 target.threadId,
92 target.fromTurnCount,
93 target.toTurnCount,
94 target.ignoreWhitespace,
95 target.cacheScope ?? null,
96 ].join(":");
98​
99function decodeCheckpointDiffRequest(target: CheckpointDiffTarget) {
100 if (target.fromTurnCount === 0) {
101 return decodeFullThreadDiffInput({
102 threadId: target.threadId,
103 toTurnCount: target.toTurnCount,
104 ignoreWhitespace: target.ignoreWhitespace,
105 }).pipe(Option.map((input) => ({ kind: "fullThreadDiff" as const, input })));
106 }
107​
108 return decodeTurnDiffInput({
109 threadId: target.threadId,
110 fromTurnCount: target.fromTurnCount,
111 toTurnCount: target.toTurnCount,
112 ignoreWhitespace: target.ignoreWhitespace,
113 }).pipe(Option.map((input) => ({ kind: "turnDiff" as const, input })));
115​
116function asCheckpointErrorMessage(error: unknown): string {
117 if (error instanceof Error) {
118 return error.message;
119 }
120 if (typeof error === "string") {
121 return error;
122 }
123 return "";
125​
126export function normalizeCheckpointDiffErrorMessage(error: unknown): string {
127 const message = asCheckpointErrorMessage(error).trim();
128 if (message.length === 0) {
129 return "Failed to load checkpoint diff.";
130 }
131​
132 const lower = message.toLowerCase();
133 if (lower.includes("not a git repository")) {
134 return "Turn diffs are unavailable because this project is not a git repository.";
135 }
136​
137 if (
138 lower.includes("checkpoint unavailable for thread") ||
139 lower.includes("checkpoint invariant violation")
140 ) {
141 const separatorIndex = message.indexOf(":");
142 if (separatorIndex >= 0) {
143 const detail = message.slice(separatorIndex + 1).trim();
144 if (detail.length > 0) {
145 return detail;
146 }
147 }
148 }
149​
150 return message;
152​
153function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
154 const message = asCheckpointErrorMessage(error).toLowerCase();
155 return (
156 message.includes("exceeds current turn count") ||
157 message.includes("checkpoint is unavailable for turn") ||
158 message.includes("filesystem checkpoint is unavailable")
159 );
161​
162function defaultRetryDelay(attempt: number, error: unknown): Promise<void> {
163 const delayMs = isCheckpointTemporarilyUnavailable(error)
164 ? Math.min(5_000, 250 * 2 ** (attempt - 1))
165 : Math.min(1_000, 100 * 2 ** (attempt - 1));
166 return Effect.runPromise(Effect.sleep(Duration.millis(delayMs)));
168​
169export function createCheckpointDiffManager(config: {
170 readonly getRegistry: () => AtomRegistry.AtomRegistry;
171 readonly getClient: (environmentId: EnvironmentId) => CheckpointDiffClient | null;
172 readonly retryDelay?: (attempt: number, error: unknown) => Promise<void>;
173}) {
174 const inFlight = new Map<string, Promise<CheckpointDiffResult | null>>();
175 const versions = new Map<string, number>();
176​
177 function getVersion(targetKey: string): number {
178 return versions.get(targetKey) ?? 0;
179 }
180​
181 function bumpVersion(targetKey: string): void {
182 versions.set(targetKey, getVersion(targetKey) + 1);
183 }
184​
185 function setState(targetKey: string, state: CheckpointDiffState): void {
186 config.getRegistry().set(checkpointDiffStateAtom(targetKey), state);
187 }
188​
189 function markPending(targetKey: string): void {
190 const current = config.getRegistry().get(checkpointDiffStateAtom(targetKey));
191 setState(
192 targetKey,
193 current.data === null ? INITIAL_CHECKPOINT_DIFF_STATE : { ...current, isPending: true },
194 );
195 }
196​
197 function setError(targetKey: string, error: unknown): void {
198 const current = config.getRegistry().get(checkpointDiffStateAtom(targetKey));
199 setState(targetKey, {
200 data: current.data,
201 error: normalizeCheckpointDiffErrorMessage(error),
202 isPending: false,
203 });
204 }
205​
206 async function requestWithRetry(
207 client: CheckpointDiffClient,
208 request: CheckpointDiffRequest,
209 ): Promise<CheckpointDiffResult> {
210 let attempt = 0;
211 while (true) {
212 attempt += 1;
213 try {
214 if (request.kind === "fullThreadDiff") {
215 return await client.getFullThreadDiff(request.input);
216 }
217 return await client.getTurnDiff(request.input);
218 } catch (error) {
219 const maxAttempts = isCheckpointTemporarilyUnavailable(error) ? 13 : 4;
220 if (attempt >= maxAttempts) {
221 throw error;
222 }
223 await (config.retryDelay ?? defaultRetryDelay)(attempt, error);
224 }
225 }
226 }
227​
228 function load(
229 target: CheckpointDiffTarget,
230 client?: CheckpointDiffClient,
231 options?: { readonly force?: boolean },
232 ): Promise<CheckpointDiffResult | null> {
233 const targetKey = getCheckpointDiffTargetKey(target);
234 const decoded = decodeCheckpointDiffRequest(target);
235 if (targetKey === null || target.environmentId === null || decoded._tag === "None") {
236 return Promise.resolve(null);
237 }
238​
239 if (!options?.force) {
240 const current = config.getRegistry().get(checkpointDiffStateAtom(targetKey));
241 if (current.data !== null && current.error === null) {
242 return Promise.resolve(current.data);
243 }
244 }
245​
246 const existing = inFlight.get(targetKey);
247 if (existing) {
248 return existing;
249 }
250​
251 const resolved = client ?? config.getClient(target.environmentId);
252 if (!resolved) {
253 setError(targetKey, new Error("Remote connection is not ready."));
254 return Promise.resolve(config.getRegistry().get(checkpointDiffStateAtom(targetKey)).data);
255 }
256​
257 markPending(targetKey);
258 const version = getVersion(targetKey);
259 const promise = requestWithRetry(resolved, decoded.value).then(
260 (result) => {
261 if (getVersion(targetKey) === version) {
262 setState(targetKey, { data: result, error: null, isPending: false });
263 }
264 return result;
265 },
266 (error: unknown) => {
267 if (getVersion(targetKey) === version) {
268 setError(targetKey, error);
269 }
270 return config.getRegistry().get(checkpointDiffStateAtom(targetKey)).data;
271 },
272 );
273 inFlight.set(targetKey, promise);
274 void promise.finally(() => {
275 if (inFlight.get(targetKey) === promise) {
276 inFlight.delete(targetKey);
277 }
278 });
279 return promise;
280 }
281​
282 function getSnapshot(target: CheckpointDiffTarget): CheckpointDiffState {
283 const targetKey = getCheckpointDiffTargetKey(target);
284 return targetKey === null
285 ? EMPTY_CHECKPOINT_DIFF_STATE
286 : config.getRegistry().get(checkpointDiffStateAtom(targetKey));
287 }
288​
289 function invalidate(target?: CheckpointDiffTarget): void {
290 if (target) {
291 const targetKey = getCheckpointDiffTargetKey(target);
292 if (targetKey === null) {
293 return;
294 }
295 bumpVersion(targetKey);
296 inFlight.delete(targetKey);
297 setState(targetKey, INITIAL_CHECKPOINT_DIFF_STATE);
298 return;
299 }
300​
301 for (const key of knownCheckpointDiffKeys) {
302 bumpVersion(key);
303 setState(key, INITIAL_CHECKPOINT_DIFF_STATE);
304 }
305 inFlight.clear();
306 }
307​
308 return {
309 getSnapshot,
310 invalidate,
311 load,
312 };