Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 AuthFilesystemWriteScope,
4 EnvironmentId,
5 ProjectId,
6 ProjectReadFileInput,
7 ProjectReadFileResult,
8 ThreadId,
9 type AuthSessionState,
10 type ScopedProjectRef,
11 WS_METHODS,
12} from "@t3tools/contracts";
13import { vi } from "vite-plus/test";
14import * as Crypto from "effect/Crypto";
15import * as Effect from "effect/Effect";
16import * as Deferred from "effect/Deferred";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Schema from "effect/Schema";
21import * as SubscriptionRef from "effect/SubscriptionRef";
22import * as Stream from "effect/Stream";
23import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
24import { AVAILABLE_CONNECTION_STATE } from "../connection/model.ts";
25
26import * as EnvironmentRegistry from "../connection/registry.ts";
27import * as EnvironmentSupervisor from "../connection/supervisor.ts";
28import type { RpcSession } from "../rpc/session.ts";
29import type { EnvironmentProject } from "./models.ts";
30import { createProjectEnvironmentAtoms } from "./projectCommands.ts";
31
32const decodeReadFileInput = Schema.decodeUnknownSync(ProjectReadFileInput);
33const decodeReadFileResult = Schema.decodeUnknownSync(ProjectReadFileResult);
34const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
35vi.mock("./session.ts", () => ({
36 createEnvironmentSessionAtoms: () => ({ sessionStateAtom: sessions }),
37}));
38const sessions = Atom.family((_id: EnvironmentId) =>
39 Atom.make<AsyncResult.AsyncResult<AuthSessionState>>(AsyncResult.initial()),
40);
41const PROJECT_ID = ProjectId.make("scratch");
42const PROJECT = {
43 id: PROJECT_ID,
44 environmentId: ENVIRONMENT_ID,
45 workspaceRoot: "/scratch",
46} as EnvironmentProject;
47
48const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () {
49 const metadataRequests: string[][] = [];
50 const file = { byteLength: 5 };
51 const readResponse = {
52 wait: Effect.void as Effect.Effect<void>,
53 missing: false,
54 };
55 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
56 target: { environmentId: ENVIRONMENT_ID },
57 session: yield* SubscriptionRef.make(
58 Option.some({
59 client: {
60 [WS_METHODS.projectsEnsureScratch]: () => Effect.succeed({ projectId: PROJECT_ID }),
61 [WS_METHODS.projectsReadFile]: () =>
62 Effect.gen(function* () {
63 const byteLength = file.byteLength;
64 yield* readResponse.wait;
65 return decodeReadFileResult(
66 readResponse.missing
67 ? {
68 relativePath: "foo",
69 byteLength: 0,
70 contents: "",
71 truncated: false,
72 exists: false,
73 }
74 : { relativePath: "foo", byteLength, contents: "old", truncated: false },
75 );
76 }),
77 [WS_METHODS.projectsWriteFile]: () =>
78 Effect.sync(() => {
79 file.byteLength = 10;
80 return { relativePath: "foo" };
81 }),
82 [WS_METHODS.filesystemGetMetadata]: (input: { paths: string[] }) =>
83 Effect.sync(() => {
84 metadataRequests.push(input.paths);
85 return {
86 entries: input.paths.map(() =>
87 readResponse.missing
88 ? null
89 : { kind: "file" as const, byteLength: file.byteLength },
90 ),
91 };
92 }),
93 },
94 } as unknown as RpcSession),
95 ),
96 state: yield* SubscriptionRef.make({
97 ...AVAILABLE_CONNECTION_STATE,
98 phase: "connected" as const,
99 }),
100 } as EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
101 const runtime = Atom.runtime(
102 Layer.mergeAll(
103 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, {
104 run: (_environmentId, effect) =>
105 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
106 followStream: (_environmentId, stream) =>
107 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
108 } as EnvironmentRegistry.EnvironmentRegistry["Service"]),
109 Layer.succeed(
110 Crypto.Crypto,
111 Crypto.make({
112 randomBytes: (size) => new Uint8Array(size),
113 digest: (_algorithm, data) => Effect.succeed(data),
114 }),
115 ),
116 ),
117 );
118 const storedProject = Atom.make<EnvironmentProject | null>(null);
119 const commands = createProjectEnvironmentAtoms(runtime, {
120 projectAtom: (ref: ScopedProjectRef) =>
121 ref.environmentId === ENVIRONMENT_ID && ref.projectId === PROJECT_ID
122 ? storedProject
123 : Atom.make(null),
124 });
125 const registry = AtomRegistry.make();
126 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
127 registry.set(
128 sessions(ENVIRONMENT_ID),
129 AsyncResult.success({
130 authenticated: true,
131 auth: {
132 policy: "remote-reachable" as const,
133 bootstrapMethods: [],
134 sessionMethods: [],
135 sessionCookieName: "test",
136 },
137 scopes: [AuthFilesystemWriteScope],
138 permissions: [AuthFilesystemWriteScope],
139 }),
140 );
141 const openScratch = Effect.promise(() =>
142 commands.openScratch.run(registry, { environmentId: ENVIRONMENT_ID, input: {} }),
143 );
144 return { registry, storedProject, openScratch, commands, metadataRequests, readResponse };
145});
146
147describe("writeFile metadata", () => {
148 it.effect("preserves optional read results without seeding metadata for an absent file", () =>
149 Effect.gen(function* () {
150 const h = yield* makeHarness();
151 h.readResponse.missing = true;
152 const input = { cwd: "/repo", relativePath: "foo", allowMissing: true };
153 expect.soft(decodeReadFileInput(input)).toEqual(input);
154 const result = yield* AtomRegistry.getResult(
155 h.registry,
156 h.commands.readFile({ environmentId: ENVIRONMENT_ID, input }),
157 { suspendOnWaiting: true },
158 );
159 expect.soft(result).toEqual({
160 relativePath: "foo",
161 byteLength: 0,
162 contents: "",
163 truncated: false,
164 exists: false,
165 });
166 const metadata = h.commands.fileMetadata({
167 environmentId: ENVIRONMENT_ID,
168 input: { path: "/repo/foo" },
169 });
170 expect(
171 yield* AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true }),
172 ).toBeNull();
173 expect(h.metadataRequests).toEqual([["/repo/foo"]]);
174 }).pipe(Effect.scoped),
175 );
176
177 it.effect("does not restore old metadata from a read completed after a write", () =>
178 Effect.gen(function* () {
179 const h = yield* makeHarness();
180 const threadId = ThreadId.make("stale-read-thread");
181 h.registry.mount(h.commands.fileMetadataThread({ environmentId: ENVIRONMENT_ID, threadId }));
182 const metadata = h.commands.fileMetadata({
183 environmentId: ENVIRONMENT_ID,
184 input: { path: "/repo/foo", threadId },
185 });
186 h.registry.mount(metadata);
187 const readMetadata = () =>
188 AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true });
189 yield* readMetadata();
190 const started = yield* Deferred.make<void>();
191 const release = yield* Deferred.make<void>();
192 h.readResponse.wait = Deferred.succeed(started, undefined).pipe(
193 Effect.andThen(Deferred.await(release)),
194 );
195 const fileRead = yield* AtomRegistry.getResult(
196 h.registry,
197 h.commands.readFile({
198 environmentId: ENVIRONMENT_ID,
199 input: { cwd: "/repo", relativePath: "foo" },
200 }),
201 { suspendOnWaiting: true },
202 ).pipe(Effect.forkChild);
203 yield* Deferred.await(started);
204 const write = yield* Effect.promise(() =>
205 h.commands.writeFile.run(h.registry, {
206 environmentId: ENVIRONMENT_ID,
207 input: { cwd: "/repo", relativePath: "foo", contents: "new" },
208 }),
209 );
210 expect(write._tag).toBe("Success");
211 expect(yield* readMetadata()).toEqual({ kind: "file", byteLength: 10 });
212 yield* Deferred.succeed(release, undefined);
213 expect((yield* Fiber.join(fileRead)).byteLength).toBe(5);
214 h.registry.refresh(metadata);
215 expect(yield* readMetadata()).toEqual({ kind: "file", byteLength: 10 });
216 expect(h.metadataRequests).toHaveLength(2);
217 }).pipe(Effect.scoped),
218 );
219
220 it.effect("refreshes retained canonical and original paths after an aliased write", () =>
221 Effect.gen(function* () {
222 const h = yield* makeHarness();
223 const threadId = ThreadId.make("write-metadata-thread");
224 h.registry.mount(h.commands.fileMetadataThread({ environmentId: ENVIRONMENT_ID, threadId }));
225 const atoms = ["/repo/foo", "/repo/./foo"].map((path) =>
226 h.commands.fileMetadata({ environmentId: ENVIRONMENT_ID, input: { path, threadId } }),
227 );
228 for (const atom of atoms) h.registry.mount(atom);
229 const read = () =>
230 Effect.forEach(
231 atoms,
232 (atom) => AtomRegistry.getResult(h.registry, atom, { suspendOnWaiting: true }),
233 { concurrency: "unbounded" },
234 );
235 expect(yield* read()).toEqual([
236 { kind: "file", byteLength: 5 },
237 { kind: "file", byteLength: 5 },
238 ]);
239 const result = yield* Effect.promise(() =>
240 h.commands.writeFile.run(h.registry, {
241 environmentId: ENVIRONMENT_ID,
242 input: { cwd: "/repo", relativePath: "./foo", contents: "new" },
243 }),
244 );
245 expect(result).toMatchObject({ _tag: "Success", value: { relativePath: "foo" } });
246 expect(yield* read()).toEqual([
247 { kind: "file", byteLength: 10 },
248 { kind: "file", byteLength: 10 },
249 ]);
250 expect(h.metadataRequests.flat()).toEqual([
251 "/repo/foo",
252 "/repo/./foo",
253 "/repo/foo",
254 "/repo/./foo",
255 ]);
256 }).pipe(Effect.scoped),
257 );
258});
259
260describe("openScratch", () => {
261 it.effect("resolves once the created project reaches the client store", () =>
262 Effect.gen(function* () {
263 const { registry, storedProject, openScratch } = yield* makeHarness();
264 const opening = yield* Effect.forkChild(openScratch);
265 yield* Effect.yieldNow;
266 registry.set(storedProject, PROJECT);
267 const result = yield* Fiber.join(opening);
268 expect(result).toMatchObject({ _tag: "Success", value: PROJECT });
269 }).pipe(Effect.scoped),
270 );
271});