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("reuses a current file read without another metadata request", () =>
178 Effect.gen(function* () {
179 const h = yield* makeHarness();
180 yield* AtomRegistry.getResult(
181 h.registry,
182 h.commands.readFile({
183 environmentId: ENVIRONMENT_ID,
184 input: { cwd: "/repo", relativePath: "foo" },
185 }),
186 { suspendOnWaiting: true },
187 );
188 const metadata = h.commands.fileMetadata({
189 environmentId: ENVIRONMENT_ID,
190 input: { path: "/repo/foo" },
191 });
192 expect(
193 yield* AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true }),
194 ).toEqual({ kind: "file", byteLength: 5 });
195 expect(h.metadataRequests).toHaveLength(0);
196 }).pipe(Effect.scoped),
197 );
198
199 it.effect("does not restore old metadata from a read completed after a write", () =>
200 Effect.gen(function* () {
201 const h = yield* makeHarness();
202 const threadId = ThreadId.make("stale-read-thread");
203 h.registry.mount(h.commands.fileMetadataThread({ environmentId: ENVIRONMENT_ID, threadId }));
204 const metadata = h.commands.fileMetadata({
205 environmentId: ENVIRONMENT_ID,
206 input: { path: "/repo/foo", threadId },
207 });
208 h.registry.mount(metadata);
209 const readMetadata = () =>
210 AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true });
211 yield* readMetadata();
212 const started = yield* Deferred.make<void>();
213 const release = yield* Deferred.make<void>();
214 h.readResponse.wait = Deferred.succeed(started, undefined).pipe(
215 Effect.andThen(Deferred.await(release)),
216 );
217 const fileRead = yield* AtomRegistry.getResult(
218 h.registry,
219 h.commands.readFile({
220 environmentId: ENVIRONMENT_ID,
221 input: { cwd: "/repo", relativePath: "foo" },
222 }),
223 { suspendOnWaiting: true },
224 ).pipe(Effect.forkChild);
225 yield* Deferred.await(started);
226 const write = yield* Effect.promise(() =>
227 h.commands.writeFile.run(h.registry, {
228 environmentId: ENVIRONMENT_ID,
229 input: { cwd: "/repo", relativePath: "foo", contents: "new" },
230 }),
231 );
232 expect(write._tag).toBe("Success");
233 expect(yield* readMetadata()).toEqual({ kind: "file", byteLength: 10 });
234 yield* Deferred.succeed(release, undefined);
235 expect((yield* Fiber.join(fileRead)).byteLength).toBe(5);
236 h.registry.refresh(metadata);
237 expect(yield* readMetadata()).toEqual({ kind: "file", byteLength: 10 });
238 expect(h.metadataRequests).toHaveLength(2);
239 }).pipe(Effect.scoped),
240 );
241
242 it.effect("refreshes retained canonical and original paths after an aliased write", () =>
243 Effect.gen(function* () {
244 const h = yield* makeHarness();
245 const threadId = ThreadId.make("write-metadata-thread");
246 h.registry.mount(h.commands.fileMetadataThread({ environmentId: ENVIRONMENT_ID, threadId }));
247 const atoms = ["/repo/foo", "/repo/./foo"].map((path) =>
248 h.commands.fileMetadata({ environmentId: ENVIRONMENT_ID, input: { path, threadId } }),
249 );
250 for (const atom of atoms) h.registry.mount(atom);
251 const read = () =>
252 Effect.forEach(
253 atoms,
254 (atom) => AtomRegistry.getResult(h.registry, atom, { suspendOnWaiting: true }),
255 { concurrency: "unbounded" },
256 );
257 expect(yield* read()).toEqual([
258 { kind: "file", byteLength: 5 },
259 { kind: "file", byteLength: 5 },
260 ]);
261 const result = yield* Effect.promise(() =>
262 h.commands.writeFile.run(h.registry, {
263 environmentId: ENVIRONMENT_ID,
264 input: { cwd: "/repo", relativePath: "./foo", contents: "new" },
265 }),
266 );
267 expect(result).toMatchObject({ _tag: "Success", value: { relativePath: "foo" } });
268 expect(yield* read()).toEqual([
269 { kind: "file", byteLength: 10 },
270 { kind: "file", byteLength: 10 },
271 ]);
272 expect(h.metadataRequests.flat()).toEqual([
273 "/repo/foo",
274 "/repo/./foo",
275 "/repo/foo",
276 "/repo/./foo",
277 ]);
278 }).pipe(Effect.scoped),
279 );
280});
281
282describe("openScratch", () => {
283 it.effect("resolves once the created project reaches the client store", () =>
284 Effect.gen(function* () {
285 const { registry, storedProject, openScratch } = yield* makeHarness();
286 const opening = yield* Effect.forkChild(openScratch);
287 yield* Effect.yieldNow;
288 registry.set(storedProject, PROJECT);
289 const result = yield* Fiber.join(opening);
290 expect(result).toMatchObject({ _tag: "Success", value: PROJECT });
291 }).pipe(Effect.scoped),
292 );
293});