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

projectCommands.test.ts

268 lines10.2 KB

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 SecureRandom from "effect/crypto/SecureRandom";
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 SecureRandom.SecureRandom,
111 SecureRandom.make((size) => new Uint8Array(size)),
112 ),
113 ),
114 );
115 const storedProject = Atom.make<EnvironmentProject | null>(null);
116 const commands = createProjectEnvironmentAtoms(runtime, {
117 projectAtom: (ref: ScopedProjectRef) =>
118 ref.environmentId === ENVIRONMENT_ID && ref.projectId === PROJECT_ID
119 ? storedProject
120 : Atom.make(null),
121 });
122 const registry = AtomRegistry.make();
123 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
124 registry.set(
125 sessions(ENVIRONMENT_ID),
126 AsyncResult.success({
127 authenticated: true,
128 auth: {
129 policy: "remote-reachable" as const,
130 bootstrapMethods: [],
131 sessionMethods: [],
132 sessionCookieName: "test",
133 },
134 scopes: [AuthFilesystemWriteScope],
135 permissions: [AuthFilesystemWriteScope],
136 }),
137 );
138 const openScratch = Effect.promise(() =>
139 commands.openScratch.run(registry, { environmentId: ENVIRONMENT_ID, input: {} }),
140 );
141 return { registry, storedProject, openScratch, commands, metadataRequests, readResponse };
142});
143​
144describe("writeFile metadata", () => {
145 it.effect("preserves optional read results without seeding metadata for an absent file", () =>
146 Effect.gen(function* () {
147 const h = yield* makeHarness();
148 h.readResponse.missing = true;
149 const input = { cwd: "/repo", relativePath: "foo", allowMissing: true };
150 expect.soft(decodeReadFileInput(input)).toEqual(input);
151 const result = yield* AtomRegistry.getResult(
152 h.registry,
153 h.commands.readFile({ environmentId: ENVIRONMENT_ID, input }),
154 { suspendOnWaiting: true },
155 );
156 expect.soft(result).toEqual({
157 relativePath: "foo",
158 byteLength: 0,
159 contents: "",
160 truncated: false,
161 exists: false,
162 });
163 const metadata = h.commands.fileMetadata({
164 environmentId: ENVIRONMENT_ID,
165 input: { path: "/repo/foo" },
166 });
167 expect(
168 yield* AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true }),
169 ).toBeNull();
170 expect(h.metadataRequests).toEqual([["/repo/foo"]]);
171 }).pipe(Effect.scoped),
172 );
173​
174 it.effect("does not restore old metadata from a read completed after a write", () =>
175 Effect.gen(function* () {
176 const h = yield* makeHarness();
177 const threadId = ThreadId.make("stale-read-thread");
178 h.registry.mount(h.commands.fileMetadataThread({ environmentId: ENVIRONMENT_ID, threadId }));
179 const metadata = h.commands.fileMetadata({
180 environmentId: ENVIRONMENT_ID,
181 input: { path: "/repo/foo", threadId },
182 });
183 h.registry.mount(metadata);
184 const readMetadata = () =>
185 AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true });
186 yield* readMetadata();
187 const started = yield* Deferred.make<void>();
188 const release = yield* Deferred.make<void>();
189 h.readResponse.wait = Deferred.succeed(started, undefined).pipe(
190 Effect.andThen(Deferred.await(release)),
191 );
192 const fileRead = yield* AtomRegistry.getResult(
193 h.registry,
194 h.commands.readFile({
195 environmentId: ENVIRONMENT_ID,
196 input: { cwd: "/repo", relativePath: "foo" },
197 }),
198 { suspendOnWaiting: true },
199 ).pipe(Effect.forkChild);
200 yield* Deferred.await(started);
201 const write = yield* Effect.promise(() =>
202 h.commands.writeFile.run(h.registry, {
203 environmentId: ENVIRONMENT_ID,
204 input: { cwd: "/repo", relativePath: "foo", contents: "new" },
205 }),
206 );
207 expect(write._tag).toBe("Success");
208 expect(yield* readMetadata()).toEqual({ kind: "file", byteLength: 10 });
209 yield* Deferred.succeed(release, undefined);
210 expect((yield* Fiber.join(fileRead)).byteLength).toBe(5);
211 h.registry.refresh(metadata);
212 expect(yield* readMetadata()).toEqual({ kind: "file", byteLength: 10 });
213 expect(h.metadataRequests).toHaveLength(2);
214 }).pipe(Effect.scoped),
215 );
216​
217 it.effect("refreshes retained canonical and original paths after an aliased write", () =>
218 Effect.gen(function* () {
219 const h = yield* makeHarness();
220 const threadId = ThreadId.make("write-metadata-thread");
221 h.registry.mount(h.commands.fileMetadataThread({ environmentId: ENVIRONMENT_ID, threadId }));
222 const atoms = ["/repo/foo", "/repo/./foo"].map((path) =>
223 h.commands.fileMetadata({ environmentId: ENVIRONMENT_ID, input: { path, threadId } }),
224 );
225 for (const atom of atoms) h.registry.mount(atom);
226 const read = () =>
227 Effect.forEach(
228 atoms,
229 (atom) => AtomRegistry.getResult(h.registry, atom, { suspendOnWaiting: true }),
230 { concurrency: "unbounded" },
231 );
232 expect(yield* read()).toEqual([
233 { kind: "file", byteLength: 5 },
234 { kind: "file", byteLength: 5 },
235 ]);
236 const result = yield* Effect.promise(() =>
237 h.commands.writeFile.run(h.registry, {
238 environmentId: ENVIRONMENT_ID,
239 input: { cwd: "/repo", relativePath: "./foo", contents: "new" },
240 }),
241 );
242 expect(result).toMatchObject({ _tag: "Success", value: { relativePath: "foo" } });
243 expect(yield* read()).toEqual([
244 { kind: "file", byteLength: 10 },
245 { kind: "file", byteLength: 10 },
246 ]);
247 expect(h.metadataRequests.flat()).toEqual([
248 "/repo/foo",
249 "/repo/./foo",
250 "/repo/foo",
251 "/repo/./foo",
252 ]);
253 }).pipe(Effect.scoped),
254 );
255});
256​
257describe("openScratch", () => {
258 it.effect("resolves once the created project reaches the client store", () =>
259 Effect.gen(function* () {
260 const { registry, storedProject, openScratch } = yield* makeHarness();
261 const opening = yield* Effect.forkChild(openScratch);
262 yield* Effect.yieldNow;
263 registry.set(storedProject, PROJECT);
264 const result = yield* Fiber.join(opening);
265 expect(result).toMatchObject({ _tag: "Success", value: PROJECT });
266 }).pipe(Effect.scoped),
267 );
268});