Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 AuthFilesystemWriteScope,
4 EnvironmentId,
5 ProjectId,
6 ProjectReadFileError,
7 ProjectReadFileInput,
8 ProjectReadFileResult,
9 ThreadId,
10 type AuthSessionState,
11 type ScopedProjectRef,
12 WS_METHODS,
13} from "@t3tools/contracts";
14import { vi } from "vite-plus/test";
15import * as SecureRandom from "effect/crypto/SecureRandom";
16import * as Effect from "effect/Effect";
17import * as Deferred from "effect/Deferred";
18import * as Fiber from "effect/Fiber";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Schema from "effect/Schema";
22import * as SubscriptionRef from "effect/SubscriptionRef";
23import * as Stream from "effect/Stream";
24import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
25import { AVAILABLE_CONNECTION_STATE, BearerConnectionTarget } from "../connection/model.ts";
26
27import * as EnvironmentRegistry from "../connection/registry.ts";
28import * as EnvironmentSupervisor from "../connection/supervisor.ts";
29import type { RpcSession } from "../rpc/session.ts";
30import type { EnvironmentProject } from "./models.ts";
31import { createProjectEnvironmentAtoms } from "./projectCommands.ts";
32
33const decodeReadFileInput = Schema.decodeUnknownSync(ProjectReadFileInput);
34const decodeReadFileResult = Schema.decodeUnknownSync(ProjectReadFileResult);
35const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
36vi.mock("./session.ts", () => ({
37 createEnvironmentSessionAtoms: () => ({ sessionStateAtom: sessions }),
38}));
39const sessions = Atom.family((_id: EnvironmentId) =>
40 Atom.make<AsyncResult.AsyncResult<AuthSessionState>>(AsyncResult.initial()),
41);
42const PROJECT_ID = ProjectId.make("scratch");
43const PROJECT = {
44 id: PROJECT_ID,
45 environmentId: ENVIRONMENT_ID,
46 workspaceRoot: "/scratch",
47} as EnvironmentProject;
48
49const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () {
50 const metadataRequests: string[][] = [];
51 const file = { byteLength: 5 };
52 const readResponse = {
53 wait: Effect.void as Effect.Effect<void, ProjectReadFileError>,
54 missing: false,
55 contents: "old",
56 };
57 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
58 target: new BearerConnectionTarget({
59 environmentId: ENVIRONMENT_ID,
60 label: "Test",
61 connectionId: "test",
62 }),
63 session: yield* SubscriptionRef.make(
64 Option.some({
65 client: {
66 [WS_METHODS.projectsEnsureScratch]: () => Effect.succeed({ projectId: PROJECT_ID }),
67 [WS_METHODS.projectsReadFile]: () =>
68 Effect.gen(function* () {
69 const byteLength = file.byteLength;
70 yield* readResponse.wait;
71 return decodeReadFileResult(
72 readResponse.missing
73 ? {
74 relativePath: "foo",
75 byteLength: 0,
76 contents: "",
77 truncated: false,
78 exists: false,
79 }
80 : {
81 relativePath: "foo",
82 byteLength,
83 contents: readResponse.contents,
84 truncated: false,
85 },
86 );
87 }),
88 [WS_METHODS.projectsWriteFile]: () =>
89 Effect.sync(() => {
90 file.byteLength = 10;
91 return { relativePath: "foo" };
92 }),
93 [WS_METHODS.filesystemGetMetadata]: (input: { paths: string[] }) =>
94 Effect.sync(() => {
95 metadataRequests.push(input.paths);
96 return {
97 entries: input.paths.map(() =>
98 readResponse.missing
99 ? null
100 : { kind: "file" as const, byteLength: file.byteLength },
101 ),
102 };
103 }),
104 },
105 } as unknown as RpcSession),
106 ),
107 state: yield* SubscriptionRef.make({
108 ...AVAILABLE_CONNECTION_STATE,
109 phase: "connected" as const,
110 }),
111 } as EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
112 const runtime = Atom.runtime(
113 Layer.mergeAll(
114 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, {
115 run: (_environmentId, effect) =>
116 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
117 followStream: (_environmentId, stream) =>
118 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
119 } as EnvironmentRegistry.EnvironmentRegistry["Service"]),
120 Layer.succeed(
121 SecureRandom.SecureRandom,
122 SecureRandom.make((size) => new Uint8Array(size)),
123 ),
124 ),
125 );
126 const storedProject = Atom.make<EnvironmentProject | null>(null);
127 const commands = createProjectEnvironmentAtoms(runtime, {
128 projectAtom: (ref: ScopedProjectRef) =>
129 ref.environmentId === ENVIRONMENT_ID && ref.projectId === PROJECT_ID
130 ? storedProject
131 : Atom.make(null),
132 });
133 const registry = AtomRegistry.make();
134 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
135 registry.set(
136 sessions(ENVIRONMENT_ID),
137 AsyncResult.success({
138 authenticated: true,
139 auth: {
140 policy: "remote-reachable" as const,
141 bootstrapMethods: [],
142 sessionMethods: [],
143 sessionCookieName: "test",
144 },
145 scopes: [AuthFilesystemWriteScope],
146 permissions: [AuthFilesystemWriteScope],
147 }),
148 );
149 const openScratch = Effect.exit(
150 commands.openScratch.run(registry, { environmentId: ENVIRONMENT_ID, input: {} }),
151 );
152 return { registry, storedProject, openScratch, commands, metadataRequests, readResponse };
153});
154
155describe("readFile", () => {
156 it.effect("reads the file afresh when it is reopened after another client changed it", () =>
157 Effect.gen(function* () {
158 const h = yield* makeHarness();
159 const query = h.commands.readFile({
160 environmentId: ENVIRONMENT_ID,
161 input: { cwd: "/repo", relativePath: "foo" },
162 });
163 // Stale-while-revalidate refreshes from a task on the registry scheduler;
164 // queue behind it so the read sees the revalidation instead of racing it.
165 const afterScheduledTasks = Effect.callback<void>((resume) => {
166 h.registry.schedulerAsync.makeDispatcher().scheduleTask(() => resume(Effect.void), 0);
167 });
168 const readContents = afterScheduledTasks.pipe(
169 Effect.andThen(AtomRegistry.getResult(h.registry, query, { suspendOnWaiting: true })),
170 Effect.map((result) => result.contents),
171 );
172
173 const closeFile = h.registry.mount(query);
174 expect(yield* readContents).toBe("old");
175 closeFile();
176 yield* afterScheduledTasks;
177
178 // Saved on another device; this client did not write it.
179 h.readResponse.contents = "saved elsewhere";
180 h.registry.mount(query);
181 expect(yield* readContents).toBe("saved elsewhere");
182 }),
183 );
184});
185
186describe("writeFile metadata", () => {
187 it.effect("retires a saved overlay after an equal read succeeds, preserving newer drafts", () =>
188 Effect.gen(function* () {
189 const h = yield* makeHarness();
190 const target = { environmentId: ENVIRONMENT_ID, cwd: "/repo", relativePath: "foo" };
191 const query = h.commands.readFile({
192 environmentId: ENVIRONMENT_ID,
193 input: { cwd: target.cwd, relativePath: target.relativePath },
194 });
195 h.registry.mount(query);
196 const read = () => AtomRegistry.getResult(h.registry, query, { suspendOnWaiting: true });
197 const original = yield* read();
198 const overlay = h.commands.optimisticFile(target);
199 h.registry.mount(overlay);
200 const saved = { ...original, contents: "saved" };
201 h.registry.set(overlay, { data: saved, saved: true, confirmingQuery: query });
202 h.readResponse.wait = Effect.fail(
203 new ProjectReadFileError({
204 cwd: "/repo",
205 relativePath: "foo",
206 failure: "operation_failed",
207 }),
208 );
209 h.registry.refresh(query);
210 yield* Effect.exit(read());
211 expect(h.registry.get(overlay)?.data.contents).toBe("saved");
212
213 h.readResponse.wait = Effect.void;
214 h.registry.refresh(query);
215 const refreshed = yield* read();
216 // The production query shares equal file values across this failed confirmation.
217 expect(refreshed).toBe(original);
218 expect(h.registry.get(overlay)).toBeNull();
219
220 h.registry.set(overlay, { data: { ...saved, contents: "newer draft" }, saved: false });
221 h.registry.refresh(query);
222 yield* read();
223 expect(h.registry.get(overlay)?.data.contents).toBe("newer draft");
224 }),
225 );
226
227 it.effect.each([true, false])(
228 "keeps a saved overlay when an older read uses different allowMissing options (confirmation: %s)",
229 (allowMissing) =>
230 Effect.gen(function* () {
231 const h = yield* makeHarness();
232 const target = { environmentId: ENVIRONMENT_ID, cwd: "/repo", relativePath: "foo" };
233 const query = h.commands.readFile({
234 environmentId: ENVIRONMENT_ID,
235 input: {
236 cwd: target.cwd,
237 relativePath: target.relativePath,
238 ...(allowMissing ? { allowMissing: true } : {}),
239 },
240 });
241 const otherQuery = h.commands.readFile({
242 environmentId: ENVIRONMENT_ID,
243 input: {
244 cwd: target.cwd,
245 relativePath: target.relativePath,
246 ...(!allowMissing ? { allowMissing: true } : {}),
247 },
248 });
249 const read = (atom: typeof query) =>
250 AtomRegistry.getResult(h.registry, atom, { suspendOnWaiting: true });
251 h.registry.mount(query);
252 const original = yield* read(query);
253 const overlay = h.commands.optimisticFile(target);
254 h.registry.mount(overlay);
255 const started = yield* Deferred.make<void>();
256 const release = yield* Deferred.make<void>();
257 h.readResponse.wait = Deferred.succeed(started, undefined).pipe(
258 Effect.andThen(Deferred.await(release)),
259 );
260 h.registry.mount(otherQuery);
261 const olderRead = yield* read(otherQuery).pipe(Effect.forkChild);
262 yield* Deferred.await(started);
263 h.registry.set(overlay, {
264 data: { ...original, contents: "saved" },
265 saved: true,
266 confirmingQuery: query,
267 });
268 h.readResponse.wait = Effect.fail(
269 new ProjectReadFileError({
270 cwd: target.cwd,
271 relativePath: target.relativePath,
272 failure: "operation_failed",
273 }),
274 );
275 h.registry.refresh(query);
276 yield* Effect.exit(read(query));
277 expect(h.registry.get(overlay)?.data.contents).toBe("saved");
278
279 yield* Deferred.succeed(release, undefined);
280 yield* Fiber.join(olderRead);
281 expect(h.registry.get(overlay)?.data.contents).toBe("saved");
282 expect(Option.getOrNull(AsyncResult.value(h.registry.get(query)))).toBe(original);
283
284 h.readResponse.wait = Effect.void;
285 h.registry.refresh(query);
286 expect(yield* read(query)).toBe(original);
287 expect(h.registry.get(overlay)).toBeNull();
288 }),
289 );
290
291 it.effect("preserves optional read results without seeding metadata for an absent file", () =>
292 Effect.gen(function* () {
293 const h = yield* makeHarness();
294 h.readResponse.missing = true;
295 const input = { cwd: "/repo", relativePath: "foo", allowMissing: true };
296 expect.soft(decodeReadFileInput(input)).toEqual(input);
297 const result = yield* AtomRegistry.getResult(
298 h.registry,
299 h.commands.readFile({ environmentId: ENVIRONMENT_ID, input }),
300 { suspendOnWaiting: true },
301 );
302 expect.soft(result).toEqual({
303 relativePath: "foo",
304 byteLength: 0,
305 contents: "",
306 truncated: false,
307 exists: false,
308 });
309 const metadata = h.commands.fileMetadata({
310 environmentId: ENVIRONMENT_ID,
311 input: { path: "/repo/foo" },
312 });
313 expect(
314 yield* AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true }),
315 ).toBeNull();
316 expect(h.metadataRequests).toEqual([["/repo/foo"]]);
317 }),
318 );
319
320 it.effect("does not restore old metadata from a read completed after a write", () =>
321 Effect.gen(function* () {
322 const h = yield* makeHarness();
323 const threadId = ThreadId.make("stale-read-thread");
324 h.registry.mount(h.commands.fileMetadataThread({ environmentId: ENVIRONMENT_ID, threadId }));
325 const metadata = h.commands.fileMetadata({
326 environmentId: ENVIRONMENT_ID,
327 input: { path: "/repo/foo", threadId },
328 });
329 h.registry.mount(metadata);
330 const readMetadata = () =>
331 AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true });
332 yield* readMetadata();
333 const started = yield* Deferred.make<void>();
334 const release = yield* Deferred.make<void>();
335 h.readResponse.wait = Deferred.succeed(started, undefined).pipe(
336 Effect.andThen(Deferred.await(release)),
337 );
338 const fileRead = yield* AtomRegistry.getResult(
339 h.registry,
340 h.commands.readFile({
341 environmentId: ENVIRONMENT_ID,
342 input: { cwd: "/repo", relativePath: "foo" },
343 }),
344 { suspendOnWaiting: true },
345 ).pipe(Effect.forkChild);
346 yield* Deferred.await(started);
347 const write = yield* Effect.exit(
348 h.commands.writeFile.run(h.registry, {
349 environmentId: ENVIRONMENT_ID,
350 input: { cwd: "/repo", relativePath: "foo", contents: "new" },
351 }),
352 );
353 expect(write._tag).toBe("Success");
354 expect(yield* readMetadata()).toEqual({ kind: "file", byteLength: 10 });
355 yield* Deferred.succeed(release, undefined);
356 expect((yield* Fiber.join(fileRead)).byteLength).toBe(5);
357 h.registry.refresh(metadata);
358 expect(yield* readMetadata()).toEqual({ kind: "file", byteLength: 10 });
359 expect(h.metadataRequests).toHaveLength(2);
360 }),
361 );
362
363 it.effect("refreshes retained canonical and original paths after an aliased write", () =>
364 Effect.gen(function* () {
365 const h = yield* makeHarness();
366 const threadId = ThreadId.make("write-metadata-thread");
367 h.registry.mount(h.commands.fileMetadataThread({ environmentId: ENVIRONMENT_ID, threadId }));
368 const atoms = ["/repo/foo", "/repo/./foo"].map((path) =>
369 h.commands.fileMetadata({ environmentId: ENVIRONMENT_ID, input: { path, threadId } }),
370 );
371 for (const atom of atoms) h.registry.mount(atom);
372 const read = () =>
373 Effect.forEach(
374 atoms,
375 (atom) => AtomRegistry.getResult(h.registry, atom, { suspendOnWaiting: true }),
376 { concurrency: "unbounded" },
377 );
378 expect(yield* read()).toEqual([
379 { kind: "file", byteLength: 5 },
380 { kind: "file", byteLength: 5 },
381 ]);
382 const result = yield* Effect.exit(
383 h.commands.writeFile.run(h.registry, {
384 environmentId: ENVIRONMENT_ID,
385 input: { cwd: "/repo", relativePath: "./foo", contents: "new" },
386 }),
387 );
388 expect(result).toMatchObject({ _tag: "Success", value: { relativePath: "foo" } });
389 expect(yield* read()).toEqual([
390 { kind: "file", byteLength: 10 },
391 { kind: "file", byteLength: 10 },
392 ]);
393 expect(h.metadataRequests.flat()).toEqual([
394 "/repo/foo",
395 "/repo/./foo",
396 "/repo/foo",
397 "/repo/./foo",
398 ]);
399 }),
400 );
401});
402
403describe("openScratch", () => {
404 it.effect("resolves once the created project reaches the client store", () =>
405 Effect.gen(function* () {
406 const { registry, storedProject, openScratch } = yield* makeHarness();
407 const opening = yield* Effect.forkChild(openScratch);
408 yield* Effect.yieldNow;
409 registry.set(storedProject, PROJECT);
410 const result = yield* Fiber.join(opening);
411 expect(result).toMatchObject({ _tag: "Success", value: PROJECT });
412 }),
413 );
414});