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

projectCommands.test.ts

245 lines9.3 KB

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