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

projectCommands.ts

233 lines8.4 KB

1import {
2 type EnvironmentId,
3 ProjectId,
4 type ProjectReadFileResult,
5 type ScopedProjectRef,
6 WS_METHODS,
7} from "@t3tools/contracts";
8import * as Crypto from "effect/Crypto";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Predicate from "effect/Predicate";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import { Atom, AtomRegistry } from "effect/reactivity";
15​
16import {
17 type EnvironmentRpcInput,
18 type EnvironmentRpcSuccess,
19 request,
20 requestGuarded,
21} from "../rpc/client.ts";
22import type { EnvironmentProject } from "./models.ts";
23import {
24 createAtomCommandScheduler,
25 createEnvironmentCommand,
26 createEnvironmentRpcCommand,
27 createEnvironmentRpcQueryAtomFamily,
28} from "./runtime.ts";
29import {
30 type CreateProjectInput,
31 type DeleteProjectInput,
32 type UpdateProjectInput,
33 createProject,
34 deleteProject,
35 updateProject,
36} from "../operations/commands.ts";
37import type { EnvironmentRegistry } from "../connection/registry.ts";
38import { createFileMetadataAtoms } from "./fileMetadata.ts";
39import { resolveWorkspaceFilePath } from "@t3tools/shared/path";
40​
41export type {
42 CreateProjectInput,
43 DeleteProjectInput,
44 UpdateProjectInput,
45} from "../operations/commands.ts";
46​
47export interface OptimisticProjectFile {
48 readonly data: ProjectReadFileResult;
49 readonly confirmedAgainst: object | null | undefined;
51​
52export interface OptimisticProjectFileTarget {
53 readonly environmentId: EnvironmentId;
54 readonly cwd: string;
55 readonly relativePath: string;
57​
58function optimisticProjectFileKey(target: OptimisticProjectFileTarget): string {
59 return JSON.stringify([target.environmentId, target.cwd, target.relativePath]);
61​
62function writtenFilePaths(
63 input: EnvironmentRpcInput<typeof WS_METHODS.projectsWriteFile>,
64 result: EnvironmentRpcSuccess<typeof WS_METHODS.projectsWriteFile>,
65) {
66 return new Set(
67 [result.relativePath, input.relativePath].map((path) =>
68 resolveWorkspaceFilePath(path, input.cwd),
69 ),
70 );
72​
73export class ScratchProjectNotLoadedError extends Schema.TaggedError<ScratchProjectNotLoadedError>()(
74 "ScratchProjectNotLoadedError",
75 { projectId: ProjectId },
76) {
77 override get message(): string {
78 return "The folder for threads without a project has not reached this device yet. Try again.";
79 }
81​
82export function createProjectEnvironmentAtoms<R, E>(
83 runtime: Atom.AtomRuntime<EnvironmentRegistry | Crypto.Crypto | R, E>,
84 options: {
85 readonly projectAtom: (ref: ScopedProjectRef) => Atom.Atom<EnvironmentProject | null>;
86 },
87) {
88 const fileMetadata = createFileMetadataAtoms(runtime);
89 const projectScheduler = createAtomCommandScheduler();
90 const fileScheduler = createAtomCommandScheduler();
91 const optimisticFileFamily = Atom.family((key: string) =>
92 Atom.make<OptimisticProjectFile | null>(null).pipe(
93 Atom.withLabel(`environment-data:projects:optimistic-file:${key}`),
94 ),
95 );
96 const projectConcurrency = {
97 mode: "serial" as const,
98 key: ({ environmentId, input }: { environmentId: string; input: { projectId: string } }) =>
99 JSON.stringify([environmentId, input.projectId]),
100 };
101 return {
102 fileMetadata: fileMetadata.metadata,
103 fileMetadataThread: fileMetadata.retainThread,
104 invalidateFileMetadata: createEnvironmentCommand(runtime, {
105 label: "environment-data:filesystem:invalidate-metadata",
106 execute: (input: { paths: ReadonlyArray<string> }, registry, environmentId) =>
107 Effect.forEach([...new Set(input.paths)], (path) =>
108 fileMetadata
109 .invalidate(path)
110 .pipe(
111 Effect.tap(() =>
112 Effect.sync(() => fileMetadata.refreshPath(environmentId, path, registry)),
113 ),
114 ),
115 ),
116 }),
117 searchEntries: createEnvironmentRpcQueryAtomFamily(runtime, {
118 label: "environment-data:projects:search-entries",
119 tag: WS_METHODS.projectsSearchEntries,
120 staleTimeMs: 15_000,
121 execute: (input) =>
122 fileMetadata.seedAfterRead(
123 request(WS_METHODS.projectsSearchEntries, input),
124 (result, isCurrent) => fileMetadata.rememberEntries(input.cwd, result.entries, isCurrent),
125 ),
126 }),
127 listEntries: createEnvironmentRpcQueryAtomFamily(runtime, {
128 label: "environment-data:projects:list-entries",
129 tag: WS_METHODS.projectsListEntries,
130 staleTimeMs: 30_000,
131 idleTtlMs: 5 * 60_000,
132 execute: (input) =>
133 fileMetadata.seedAfterRead(
134 request(WS_METHODS.projectsListEntries, input),
135 (result, isCurrent) => fileMetadata.rememberEntries(input.cwd, result.entries, isCurrent),
136 ),
137 }),
138 listIgnoredFiles: createEnvironmentRpcQueryAtomFamily(runtime, {
139 label: "environment-data:projects:list-ignored-files",
140 tag: WS_METHODS.projectsListIgnoredFiles,
141 staleTimeMs: 15_000,
142 }),
143 readFile: createEnvironmentRpcQueryAtomFamily(runtime, {
144 label: "environment-data:projects:read-file",
145 tag: WS_METHODS.projectsReadFile,
146 staleTimeMs: 30_000,
147 idleTtlMs: 5 * 60_000,
148 execute: (input) =>
149 fileMetadata.seedAfterRead(
150 request(WS_METHODS.projectsReadFile, input),
151 (result, isCurrent) =>
152 result.exists === false
153 ? Effect.void
154 : fileMetadata.rememberFile(input.cwd, result, isCurrent),
155 ),
156 }),
157 optimisticFile: (target: OptimisticProjectFileTarget) =>
158 optimisticFileFamily(optimisticProjectFileKey(target)),
159 create: createEnvironmentCommand(runtime, {
160 label: "environment-data:commands:project:create",
161 execute: (input: CreateProjectInput) => createProject(input),
162 scheduler: projectScheduler,
163 concurrency: projectConcurrency,
164 }),
165 update: createEnvironmentCommand(runtime, {
166 label: "environment-data:commands:project:update",
167 execute: (input: UpdateProjectInput) => updateProject(input),
168 scheduler: projectScheduler,
169 concurrency: projectConcurrency,
170 }),
171 delete: createEnvironmentCommand(runtime, {
172 label: "environment-data:commands:project:delete",
173 execute: (input: DeleteProjectInput) => deleteProject(input),
174 scheduler: projectScheduler,
175 concurrency: projectConcurrency,
176 }),
177 // Finds or creates the environment's Scratch project and resolves once the
178 // project is in the client store, since drafts key off its stored path.
179 openScratch: createEnvironmentCommand(runtime, {
180 label: "environment-data:projects:open-scratch",
181 execute: (
182 input: EnvironmentRpcInput<typeof WS_METHODS.projectsEnsureScratch>,
183 registry,
184 environmentId,
185 ) =>
186 request(WS_METHODS.projectsEnsureScratch, input).pipe(
187 Effect.flatMap(({ projectId }) =>
188 AtomRegistry.toStream(registry, options.projectAtom({ environmentId, projectId })).pipe(
189 Stream.filter(Predicate.isNotNull),
190 Stream.runHead,
191 Effect.timeoutOption("10 seconds"),
192 Effect.map(Option.flatten),
193 Effect.flatMap(
194 Option.match({
195 onSome: Effect.succeed,
196 onNone: () => Effect.fail(new ScratchProjectNotLoadedError({ projectId })),
197 }),
198 ),
199 ),
200 ),
201 ),
202 scheduler: projectScheduler,
203 concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
204 }),
205 createNew: createEnvironmentRpcCommand(runtime, {
206 label: "environment-data:projects:create-new",
207 tag: WS_METHODS.projectsCreateNew,
208 scheduler: projectScheduler,
209 concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
210 }),
211 writeFile: createEnvironmentRpcCommand(runtime, {
212 label: "environment-data:projects:write-file",
213 tag: WS_METHODS.projectsWriteFile,
214 scheduler: fileScheduler,
215 concurrency: {
216 mode: "serial",
217 key: ({ environmentId, input }) =>
218 JSON.stringify([environmentId, input.cwd, input.relativePath]),
219 },
220 execute: (input) =>
221 requestGuarded(WS_METHODS.projectsWriteFile, input).pipe(
222 Effect.tap((result) =>
223 Effect.forEach(writtenFilePaths(input, result), fileMetadata.invalidate),
224 ),
225 ),
226 onSuccess: ({ environmentId, input }, registry, result) =>
227 Effect.sync(() => {
228 for (const path of writtenFilePaths(input, result))
229 fileMetadata.refreshPath(environmentId, path, registry);
230 }),
231 }),
232 };