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

ScratchWorkspace.test.ts

252 lines9.4 KB

1import { assert, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { CommandId, ProjectId, ThreadId } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9​
10import * as ServerConfig from "../config.ts";
11import * as GitWorkflow from "../git/GitWorkflowService.ts";
12import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts";
13import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
14import * as ProcessRunner from "../processRunner.ts";
15import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
16import * as VcsProcess from "../vcs/VcsProcess.ts";
17import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
18import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts";
19import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts";
20import * as ProjectService from "./ProjectService.ts";
21import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts";
22import * as ScratchWorkspace from "./ScratchWorkspace.ts";
23​
24// Real repository detection: the service only asks the Git workflow whether
25// the data dir is inside a checkout.
26const gitWorkflowLayer = Layer.unwrap(
27 Effect.gen(function* () {
28 const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
29 return Layer.mock(GitWorkflow.GitWorkflowService)({
30 isRepository: (cwd) =>
31 registry.detect({ cwd }).pipe(
32 Effect.map((handle) => handle?.kind === "git"),
33 Effect.orDie,
34 ),
35 });
36 }),
37).pipe(Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))));
38​
39const enrichmentLayer = ProjectEnrichmentService.layer.pipe(
40 Layer.provide(
41 Layer.mergeAll(
42 Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
43 resolve: () => Effect.succeed(null),
44 }),
45 Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, {
46 resolvePath: () => Effect.succeed(null),
47 }),
48 ),
49 ),
50);
51​
52/** The service over a real ProjectService, with its data dir at `baseDir`. */
53const makeLayer = (baseDir: string) =>
54 ScratchWorkspace.layer.pipe(
55 Layer.provideMerge(ProjectServiceLayerLive),
56 Layer.provideMerge(enrichmentLayer),
57 Layer.provideMerge(WorkspacePaths.layer),
58 Layer.provideMerge(gitWorkflowLayer),
59 Layer.provideMerge(SqlitePersistenceMemory),
60 Layer.provideMerge(ServerConfig.layerTest(baseDir, baseDir)),
61 Layer.provideMerge(NodeServices.layer),
62 );
63​
64/** Runs `body` with a data dir in a fresh temp folder, outside any checkout. */
65const withScratch = <A, E>(
66 body: (input: {
67 readonly baseDir: string;
68 }) => Effect.Effect<
69 A,
70 E,
71 | ScratchWorkspace.ScratchWorkspace
72 | ProjectService.ProjectService
73 | FileSystem.FileSystem
74 | Path.Path
75 >,
76) =>
77 Effect.gen(function* () {
78 const fileSystem = yield* FileSystem.FileSystem;
79 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-scratch-" });
80 return yield* body({ baseDir }).pipe(Effect.provide(makeLayer(baseDir)));
81 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
82​
83const git = (cwd: string, args: ReadonlyArray<string>) =>
84 ProcessRunner.ProcessRunner.pipe(
85 Effect.flatMap((runner) => runner.run({ command: "git", args: ["-C", cwd, ...args] })),
86 Effect.provide(ProcessRunner.layer),
87 );
88​
89const requireRoot = Effect.gen(function* () {
90 const scratch = yield* ScratchWorkspace.ScratchWorkspace;
91 return Option.getOrThrow(yield* scratch.root);
92});
93​
94it.effect("offers a Scratch folder under the data dir when it is outside a checkout", () =>
95 withScratch(({ baseDir }) =>
96 Effect.gen(function* () {
97 const path = yield* Path.Path;
98 assert.equal(yield* requireRoot, path.resolve(baseDir, "scratch"));
99 }),
100 ),
101);
102​
103it.effect("offers nothing when the data dir sits inside a Git checkout", () =>
104 Effect.gen(function* () {
105 const fileSystem = yield* FileSystem.FileSystem;
106 const path = yield* Path.Path;
107 const checkout = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-scratch-repo-" });
108 yield* git(checkout, ["init", "--quiet"]);
109 const baseDir = path.join(checkout, ".t3");
110 yield* fileSystem.makeDirectory(baseDir);
111 yield* Effect.gen(function* () {
112 const scratch = yield* ScratchWorkspace.ScratchWorkspace;
113 assert.isTrue(Option.isNone(yield* scratch.root));
114 const failure = yield* Effect.flip(scratch.ensureProject);
115 assert.equal(failure._tag, "ScratchWorkspaceUnavailableError");
116 }).pipe(Effect.provide(makeLayer(baseDir)));
117 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
118);
119​
120it.effect("creates one Scratch project, even for concurrent first requests", () =>
121 withScratch(() =>
122 Effect.gen(function* () {
123 const scratch = yield* ScratchWorkspace.ScratchWorkspace;
124 const projects = yield* ProjectService.ProjectService;
125 // Without handling the losing creates' conflicts, eight racers fail.
126 const racers = yield* Effect.all(
127 Array.from({ length: 8 }, () => scratch.ensureProject),
128 { concurrency: "unbounded" },
129 );
130 const again = yield* scratch.ensureProject;
131 assert.deepEqual(
132 new Set(racers.map((result) => result.projectId)),
133 new Set([again.projectId]),
134 );
135​
136 const snapshot = yield* projects.snapshot;
137 const root = yield* requireRoot;
138 const scratchProjects = snapshot.projects.filter((project) => project.workspaceRoot === root);
139 assert.lengthOf(scratchProjects, 1);
140 assert.equal(scratchProjects[0]?.title, "No project");
141 assert.deepEqual(scratchProjects[0]?.projectIcon, {
142 kind: "lucide",
143 name: "message-square-dashed",
144 color: "gray",
145 });
146 }),
147 ),
148);
149​
150it.effect("recreates the Scratch folder after it is deleted", () =>
151 withScratch(() =>
152 Effect.gen(function* () {
153 const scratch = yield* ScratchWorkspace.ScratchWorkspace;
154 const fileSystem = yield* FileSystem.FileSystem;
155 const { projectId } = yield* scratch.ensureProject;
156 const root = yield* requireRoot;
157 yield* fileSystem.remove(root, { recursive: true });
158​
159 assert.equal((yield* scratch.ensureProject).projectId, projectId);
160 assert.isTrue(yield* fileSystem.exists(root));
161​
162 yield* fileSystem.remove(root, { recursive: true });
163 const folder = yield* scratch.folderForThread({
164 projectId,
165 threadId: ThreadId.make("thread-after-delete"),
166 text: "Still works",
167 });
168 assert.isTrue(yield* fileSystem.exists(Option.getOrThrow(folder)));
169 }),
170 ),
171);
172​
173it.effect("gives each Scratch thread its own folder, named from its message", () =>
174 withScratch(() =>
175 Effect.gen(function* () {
176 const scratch = yield* ScratchWorkspace.ScratchWorkspace;
177 const fileSystem = yield* FileSystem.FileSystem;
178 const path = yield* Path.Path;
179 const { projectId } = yield* scratch.ensureProject;
180 const root = yield* requireRoot;
181 const text = "Convert these PNGs to WebP, please!";
182 // Two ids with the same tail would collide on the short name.
183 const first = Option.getOrThrow(
184 yield* scratch.folderForThread({
185 projectId,
186 threadId: ThreadId.make("thread:a:0123456789abcdef"),
187 text,
188 }),
189 );
190 const second = Option.getOrThrow(
191 yield* scratch.folderForThread({
192 projectId,
193 threadId: ThreadId.make("thread:b:0123456789abcdef"),
194 text,
195 }),
196 );
197​
198 // Ids that normalize to the same characters take both of its names.
199 const third = Option.getOrThrow(
200 yield* scratch.folderForThread({
201 projectId,
202 threadId: ThreadId.make("thread:b0123456789abcdef"),
203 text,
204 }),
205 );
206​
207 assert.equal(new Set([first, second, third]).size, 3);
208 for (const folder of [first, second, third]) {
209 assert.equal(path.dirname(folder), root);
210 assert.match(path.basename(folder), /^\d{4}-\d{2}-\d{2}-convert-these-pngs-to-webp-/);
211 assert.isTrue(yield* fileSystem.exists(folder));
212 }
213​
214 const pasted = Option.getOrThrow(
215 yield* scratch.folderForThread({
216 projectId,
217 threadId: ThreadId.make("thread-pasted"),
218 text: `${"word ".repeat(10_000)}../../etc`,
219 }),
220 );
221 assert.equal(path.dirname(pasted), root);
222 assert.isAtMost(path.basename(pasted).length, 80);
223 }),
224 ),
225);
226​
227it.effect("leaves threads in other projects alone", () =>
228 withScratch(({ baseDir }) =>
229 Effect.gen(function* () {
230 const scratch = yield* ScratchWorkspace.ScratchWorkspace;
231 const projects = yield* ProjectService.ProjectService;
232 const fileSystem = yield* FileSystem.FileSystem;
233 const path = yield* Path.Path;
234 yield* scratch.ensureProject;
235 const other = yield* projects.create({
236 commandId: CommandId.make("command:other"),
237 projectId: ProjectId.make("project:other"),
238 title: "Other",
239 workspaceRoot: path.join(baseDir, "other"),
240 createWorkspaceRootIfMissing: true,
241 });
242​
243 const folder = yield* scratch.folderForThread({
244 projectId: other.id,
245 threadId: ThreadId.make("thread-other"),
246 text: "Hello",
247 });
248 assert.isTrue(Option.isNone(folder));
249 assert.deepEqual(yield* fileSystem.readDirectory(yield* requireRoot), []);
250 }),
251 ),
252);