Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type {
3 EnvironmentId,
4 ProjectListEntriesResult,
5 ProjectReadFileResult,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import * as Data from "effect/Data";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import { AsyncResult, Atom } from "effect/unstable/reactivity";
12import { useCallback, useEffect } from "react";
13
14import { ensureEnvironmentApi } from "~/environmentApi";
15import { appAtomRegistry } from "~/rpc/atomRegistry";
16
17const PROJECT_QUERY_STALE_TIME_MS = 30_000;
18const PROJECT_QUERY_IDLE_TTL_MS = 5 * 60_000;
19const EMPTY_PROJECT_FILE_PATH = "";
20interface OptimisticProjectFile {
21 readonly data: ProjectReadFileResult;
22 readonly confirmed: boolean;
23}
24
25const optimisticProjectFiles = new Map<string, OptimisticProjectFile>();
26
27class ProjectQueryError extends Data.TaggedError("ProjectQueryError")<{
28 readonly message: string;
29 readonly cause?: unknown;
30}> {}
31
32function queryError(message: string, cause: unknown): ProjectQueryError {
33 return new ProjectQueryError({ message, cause });
34}
35
36function entriesKey(environmentId: EnvironmentId, cwd: string): string {
37 return [environmentId, cwd].map(encodeURIComponent).join("|");
38}
39
40function fileKey(environmentId: EnvironmentId, cwd: string, relativePath: string): string {
41 return [environmentId, cwd, relativePath].map(encodeURIComponent).join("|");
42}
43
44function keyParts(key: string): string[] {
45 return key.split("|").map(decodeURIComponent);
46}
47
48const projectEntriesQueryAtom = Atom.family((key: string) =>
49 Atom.make(
50 Effect.tryPromise({
51 try: () => {
52 const [environmentId, cwd] = keyParts(key) as [EnvironmentId, string];
53 return ensureEnvironmentApi(environmentId).projects.listEntries({ cwd });
54 },
55 catch: (cause) => queryError("Could not load workspace files.", cause),
56 }),
57 ).pipe(
58 Atom.swr({
59 staleTime: PROJECT_QUERY_STALE_TIME_MS,
60 revalidateOnMount: true,
61 }),
62 Atom.setIdleTTL(PROJECT_QUERY_IDLE_TTL_MS),
63 Atom.withLabel(`projects:entries:${key}`),
64 ),
65);
66
67const projectFileQueryAtom = Atom.family((key: string) =>
68 Atom.make(
69 Effect.tryPromise({
70 try: () => {
71 const [environmentId, cwd, relativePath] = keyParts(key) as [EnvironmentId, string, string];
72 if (relativePath === EMPTY_PROJECT_FILE_PATH) return Promise.resolve(null);
73 return ensureEnvironmentApi(environmentId).projects.readFile({ cwd, relativePath });
74 },
75 catch: (cause) => queryError("Could not read workspace file.", cause),
76 }),
77 ).pipe(
78 Atom.swr({
79 staleTime: PROJECT_QUERY_STALE_TIME_MS,
80 revalidateOnMount: true,
81 }),
82 Atom.setIdleTTL(PROJECT_QUERY_IDLE_TTL_MS),
83 Atom.withLabel(`projects:file:${key}`),
84 ),
85);
86
87interface ProjectQueryState<A> {
88 readonly data: A | null;
89 readonly error: string | null;
90 readonly isPending: boolean;
91 readonly refresh: () => void;
92}
93
94export function getProjectEntriesQueryAtom(environmentId: EnvironmentId, cwd: string) {
95 return projectEntriesQueryAtom(entriesKey(environmentId, cwd));
96}
97
98export function getProjectFileQueryAtom(
99 environmentId: EnvironmentId,
100 cwd: string,
101 relativePath: string | null,
102) {
103 return projectFileQueryAtom(fileKey(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH));
104}
105
106export function setProjectFileQueryData(
107 environmentId: EnvironmentId,
108 cwd: string,
109 relativePath: string,
110 contents: string,
111): void {
112 const key = fileKey(environmentId, cwd, relativePath);
113 optimisticProjectFiles.set(key, {
114 confirmed: false,
115 data: {
116 relativePath,
117 contents,
118 byteLength: new TextEncoder().encode(contents).byteLength,
119 truncated: false,
120 },
121 });
122}
123
124export function confirmProjectFileQueryData(
125 environmentId: EnvironmentId,
126 cwd: string,
127 relativePath: string,
128 contents: string,
129): boolean {
130 const key = fileKey(environmentId, cwd, relativePath);
131 const optimisticFile = optimisticProjectFiles.get(key);
132 if (optimisticFile?.data.contents !== contents) return false;
133
134 optimisticProjectFiles.set(key, { ...optimisticFile, confirmed: true });
135 appAtomRegistry.refresh(getProjectFileQueryAtom(environmentId, cwd, relativePath));
136 return true;
137}
138
139export function resolveProjectFileQueryData(
140 environmentId: EnvironmentId,
141 cwd: string,
142 relativePath: string | null,
143 data: ProjectReadFileResult | null,
144): ProjectReadFileResult | null {
145 if (relativePath === null) return data;
146 return optimisticProjectFiles.get(fileKey(environmentId, cwd, relativePath))?.data ?? data;
147}
148
149export function __resetProjectFileQueryDataForTests(): void {
150 optimisticProjectFiles.clear();
151}
152
153function errorMessage<A>(result: AsyncResult.AsyncResult<A, unknown>): string | null {
154 if (result._tag !== "Failure") return null;
155 const cause = Cause.squash(result.cause);
156 return cause instanceof Error ? cause.message : "Workspace query failed.";
157}
158
159export function useProjectEntriesQuery(
160 environmentId: EnvironmentId,
161 cwd: string,
162): ProjectQueryState<ProjectListEntriesResult> {
163 const atom = getProjectEntriesQueryAtom(environmentId, cwd);
164 const result = useAtomValue(atom);
165 const refresh = useCallback(() => appAtomRegistry.refresh(atom), [atom]);
166 return {
167 data: Option.getOrNull(AsyncResult.value(result)),
168 error: errorMessage(result),
169 isPending: result.waiting,
170 refresh,
171 };
172}
173
174export function useProjectFileQuery(
175 environmentId: EnvironmentId,
176 cwd: string,
177 relativePath: string | null,
178): ProjectQueryState<ProjectReadFileResult> {
179 const atom = getProjectFileQueryAtom(environmentId, cwd, relativePath);
180 const result = useAtomValue(atom);
181 const refresh = useCallback(() => appAtomRegistry.refresh(atom), [atom]);
182 const data = Option.getOrNull(AsyncResult.value(result));
183 const optimisticFile =
184 relativePath === null
185 ? undefined
186 : optimisticProjectFiles.get(fileKey(environmentId, cwd, relativePath));
187
188 useEffect(() => {
189 if (
190 relativePath === null ||
191 optimisticFile === undefined ||
192 !optimisticFile.confirmed ||
193 data?.contents !== optimisticFile.data.contents
194 ) {
195 return;
196 }
197 optimisticProjectFiles.delete(fileKey(environmentId, cwd, relativePath));
198 }, [cwd, data?.contents, environmentId, optimisticFile, relativePath]);
199
200 return {
201 data: optimisticFile?.data ?? data,
202 error: errorMessage(result),
203 isPending: result.waiting,
204 refresh,
205 };
206}