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

assets.test.ts

412 lines15.5 KB

1import { describe, expect, it } from "@effect/vitest";
2import {
3 type AssetCreateUrlResult,
4 AssetWorkspaceAssetNotFoundError,
5 AssetWorkspaceAssetInspectionError,
6 AssetWorkspaceContextNotFoundError,
7 EnvironmentAuthorizationError,
8 EnvironmentId,
9 ThreadId,
10 WS_METHODS,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Effect from "effect/Effect";
14import * as Stream from "effect/Stream";
15import * as SubscriptionRef from "effect/SubscriptionRef";
16import * as Option from "effect/Option";
17import * as Layer from "effect/Layer";
18import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
19​
20import { EnvironmentRegistry } from "../connection/registry.ts";
21import {
22 AVAILABLE_CONNECTION_STATE,
23 PrimaryConnectionTarget,
24 type PreparedConnection,
25 type SupervisorConnectionState,
26} from "../connection/model.ts";
27import { EnvironmentSupervisor } from "../connection/supervisor.ts";
28import type { RpcSession } from "../rpc/session.ts";
29import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
30import { createProjectFaviconCache } from "../projectFaviconCache.ts";
31import {
32 createAssetEnvironmentAtoms,
33 createProjectFaviconUrlAtomFamily,
34 InvalidAssetCollectionKeyError,
35 parseAssetCollectionKey,
36} from "./assets.ts";
37​
38describe("asset collection keys", () => {
39 it("preserves malformed JSON and its native cause", () => {
40 const key = "not-json";
41 let error: unknown;
42​
43 try {
44 parseAssetCollectionKey(key);
45 } catch (cause) {
46 error = cause;
47 }
48​
49 expect(error).toBeInstanceOf(InvalidAssetCollectionKeyError);
50 expect(error).toMatchObject({ key, cause: expect.any(SyntaxError) });
51 });
52​
53 it("rejects invalid asset collection shapes", () => {
54 const key = JSON.stringify(["environment-1", [{ _tag: "unknown" }]]);
55​
56 expect(() => parseAssetCollectionKey(key)).toThrowError(InvalidAssetCollectionKeyError);
57 });
58});
59​
60describe("createAssetEnvironmentAtoms", () => {
61 for (const scenario of [
62 { name: "missing video", path: "/tmp/clip.mp4", fallback: true },
63 { name: "literal filename characters", path: "/tmp/frame#one?two.png", fallback: true },
64 { name: "windows path", path: "C:\\Users\\demo\\clip.mp4", fallback: true },
65 { name: "inspection failure", path: "/tmp/clip.mp4", error: "inspection", fallback: true },
66 { name: "foreign thread", path: "/tmp/clip.mp4", error: "context", fallback: true },
67 { name: "remote success", path: "/tmp/clip.mp4", success: true },
68 { name: "relative path", path: "clip.mp4" },
69 { name: "no primary", path: "/tmp/clip.mp4", primary: "none" },
70 { name: "primary reconnect", path: "/tmp/frame.png", primary: "reconnecting" },
71 { name: "same environment", path: "/tmp/clip.mp4", primary: "same" },
72 { name: "non-media", path: "/tmp/report.html" },
73 { name: "authorization failure", path: "/tmp/clip.mp4", error: "auth" },
74 ]) {
75 it.effect(`uses the correct environment for ${scenario.name}`, () =>
76 Effect.gen(function* () {
77 const remoteId = EnvironmentId.make("remote");
78 const localId = EnvironmentId.make("local");
79 const resource = {
80 _tag: "media-file" as const,
81 threadId: ThreadId.make("foreign-thread"),
82 path: scenario.path,
83 };
84 const error =
85 scenario.error === "auth"
86 ? new EnvironmentAuthorizationError({
87 message: "denied",
88 requiredScope: "orchestration:read",
89 })
90 : scenario.error === "inspection"
91 ? new AssetWorkspaceAssetInspectionError({ resource, cause: new Error("unreadable") })
92 : scenario.error === "context"
93 ? new AssetWorkspaceContextNotFoundError({ resource })
94 : new AssetWorkspaceAssetNotFoundError({ resource });
95 const calls: EnvironmentId[] = [];
96 const supervisors = new Map<EnvironmentId, EnvironmentSupervisor["Service"]>();
97 for (const environmentId of [remoteId, localId]) {
98 const client = {
99 [WS_METHODS.assetsCreateUrl]: () => {
100 calls.push(environmentId);
101 return environmentId === remoteId && !scenario.success
102 ? Effect.fail(error)
103 : Effect.succeed({
104 relativeUrl: `/api/assets/${environmentId}/media`,
105 expiresAt: 999999,
106 });
107 },
108 } as unknown as WsRpcProtocolClient;
109 const session = { client } as RpcSession;
110 supervisors.set(
111 environmentId,
112 EnvironmentSupervisor.of({
113 target: new PrimaryConnectionTarget({
114 environmentId,
115 label: environmentId,
116 httpBaseUrl: `https://${environmentId}.test`,
117 wsBaseUrl: `wss://${environmentId}.test`,
118 }),
119 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
120 ...AVAILABLE_CONNECTION_STATE,
121 phase: "connected" as const,
122 }),
123 session: yield* SubscriptionRef.make(Option.some(session)),
124 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
125 connect: Effect.void,
126 disconnect: Effect.void,
127 retryNow: Effect.void,
128 }),
129 );
130 }
131 const environments = EnvironmentRegistry.of({
132 run: (id, effect) =>
133 Effect.provideService(effect, EnvironmentSupervisor, supervisors.get(id)!),
134 followStream: (id, stream) =>
135 Stream.provideService(stream, EnvironmentSupervisor, supervisors.get(id)!),
136 } as EnvironmentRegistry["Service"]);
137 const registry = AtomRegistry.make();
138 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
139 const localTarget = {
140 environmentId: scenario.primary === "same" ? remoteId : localId,
141 httpBaseUrl: "https://local.test",
142 };
143 const localEnvironment = Atom.make<typeof localTarget | null>(
144 scenario.primary === "none" || scenario.primary === "reconnecting" ? null : localTarget,
145 );
146 const assets = createAssetEnvironmentAtoms(
147 Atom.runtime(Layer.succeed(EnvironmentRegistry, environments)),
148 localEnvironment,
149 );
150 const query = assets.createUrl({ environmentId: remoteId, input: { resource } });
151 const result = AtomRegistry.getResult(registry, query, { suspendOnWaiting: true });
152 if (scenario.fallback || scenario.success) {
153 expect((yield* result).relativeUrl).toBe(
154 scenario.fallback
155 ? "https://local.test/api/assets/local/media"
156 : "/api/assets/remote/media",
157 );
158 } else {
159 expect(yield* Effect.flip(result)).toEqual(error);
160 }
161 expect(calls).toEqual(scenario.fallback ? [remoteId, localId] : [remoteId]);
162 if (scenario.primary === "reconnecting") {
163 registry.set(localEnvironment, localTarget);
164 expect((yield* result).relativeUrl).toBe("https://local.test/api/assets/local/media");
165 expect(calls).toEqual([remoteId, remoteId, localId]);
166 }
167 }).pipe(Effect.scoped),
168 );
169 }
170​
171 it("keys asset URL queries by environment and resource", () => {
172 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
173 EnvironmentRegistry,
174 never
175 >;
176 const assets = createAssetEnvironmentAtoms(runtime);
177 const environmentId = EnvironmentId.make("environment-1");
178 const originalTarget = {
179 environmentId,
180 input: {
181 resource: {
182 _tag: "project-favicon" as const,
183 cwd: "/repo/original",
184 },
185 },
186 };
187​
188 expect(assets.createUrl(originalTarget)).toBe(
189 assets.createUrl({
190 environmentId,
191 input: {
192 resource: {
193 _tag: "project-favicon",
194 cwd: "/repo/original",
195 },
196 },
197 }),
198 );
199 expect(
200 assets.createUrl({
201 environmentId,
202 input: {
203 resource: {
204 _tag: "project-favicon",
205 cwd: "/repo/next",
206 },
207 },
208 }),
209 ).not.toBe(assets.createUrl(originalTarget));
210 expect(
211 assets.createUrl({
212 environmentId,
213 input: {
214 resource: {
215 _tag: "project-favicon",
216 cwd: "/repo/original",
217 path: "brand/icon.svg",
218 },
219 },
220 }),
221 ).not.toBe(assets.createUrl(originalTarget));
222 expect(
223 assets.createUrl({
224 environmentId: EnvironmentId.make("environment-2"),
225 input: originalTarget.input,
226 }),
227 ).not.toBe(assets.createUrl(originalTarget));
228 });
229​
230 it("keys collections while preserving independent resource queries", () => {
231 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
232 EnvironmentRegistry,
233 never
234 >;
235 const assets = createAssetEnvironmentAtoms(runtime);
236 const environmentId = EnvironmentId.make("environment-1");
237 const resources = [
238 { _tag: "attachment" as const, attachmentId: "attachment-1" },
239 { _tag: "attachment" as const, attachmentId: "attachment-2" },
240 ];
241​
242 expect(assets.createUrls({ environmentId, resources })).toBe(
243 assets.createUrls({
244 environmentId,
245 resources: resources.map((resource) => ({ ...resource })),
246 }),
247 );
248 expect(
249 assets.createUrls({
250 environmentId,
251 resources: [...resources].toReversed(),
252 }),
253 ).not.toBe(assets.createUrls({ environmentId, resources }));
254 });
255});
256​
257describe("project favicon URL cache", () => {
258 it("renders a persisted thumbnail immediately in a fresh registry and refreshes it remotely", async () => {
259 const image = "data:image/png;base64,aWNvbg==";
260 const replacement = "data:image/png;base64,bmV3";
261 const records = new Map<string, unknown>();
262 const storage = {
263 list: async () => [...records.values()],
264 put: async (key: string, entry: unknown) => {
265 records.set(key, entry);
266 },
267 remove: async (key: string) => {
268 records.delete(key);
269 },
270 };
271 const target = { environmentId: EnvironmentId.make("remote"), cwd: "/workspace" };
272 const previousCache = createProjectFaviconCache({ storage, load: async () => image });
273 await previousCache.resolve(
274 target,
275 "https://remote.test/api/assets/old/v1-icon.png",
276 new AbortController().signal,
277 );
278 await previousCache.flush();
279 const cache = createProjectFaviconCache({ storage, load: async () => replacement });
280 await cache.hydrate();
281 const registry = AtomRegistry.make();
282 const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
283 AsyncResult.initial(),
284 );
285 const connection = Atom.make<Option.Option<{ httpBaseUrl: string }>>(Option.none());
286 const favicon = createProjectFaviconUrlAtomFamily({
287 createUrl: () => result,
288 preparedConnection: () => connection,
289 imageCache: cache,
290 })(target);
291 const unmount = registry.mount(favicon);
292 try {
293 expect(registry.get(favicon)).toBe(image);
294 let unsubscribe = () => {};
295 const refreshed = new Promise<void>((resolve) => {
296 unsubscribe = registry.subscribe(favicon, (value) => {
297 if (value === replacement) resolve();
298 });
299 });
300 registry.set(connection, Option.some({ httpBaseUrl: "https://remote.test" }));
301 registry.set(
302 result,
303 AsyncResult.success({
304 relativeUrl: "/api/assets/new/v2-icon.png",
305 expiresAt: 4_000_000_000_000,
306 }),
307 );
308 expect(registry.get(favicon)).toBe(image);
309 await refreshed;
310 unsubscribe();
311 expect(registry.get(favicon)).toBe(replacement);
312 registry.set(connection, Option.none());
313 registry.set(result, AsyncResult.failure(Cause.die("offline")));
314 expect(registry.get(favicon)).toBe(replacement);
315 } finally {
316 unmount();
317 registry.dispose();
318 }
319 });
320​
321 it("retains icons across outages and remounts, then accepts refreshed and missing icons", () => {
322 const registry = AtomRegistry.make();
323 const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
324 AsyncResult.initial(),
325 );
326 const connection = Atom.make(Option.some({ httpBaseUrl: "https://remote.test" }));
327 const favicon = createProjectFaviconUrlAtomFamily({
328 createUrl: () => result,
329 preparedConnection: () => connection,
330 })({ environmentId: EnvironmentId.make("remote"), cwd: "/workspace" });
331 let unmount = registry.mount(favicon);
332 try {
333 expect(registry.get(favicon)).toBeNull();
334 registry.set(
335 result,
336 AsyncResult.success({
337 expiresAt: 4_000_000_000_000,
338 relativeUrl: "/api/assets/token-a/icon.svg",
339 }),
340 );
341 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
342​
343 registry.set(connection, Option.none());
344 registry.set(result, AsyncResult.failure(Cause.die("disconnected")));
345 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
346 unmount();
347 unmount = registry.mount(favicon);
348 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
349​
350 registry.set(result, AsyncResult.initial());
351 registry.set(connection, Option.some({ httpBaseUrl: "https://reconnected.test" }));
352 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
353 registry.set(
354 result,
355 AsyncResult.success({
356 expiresAt: 4_000_000_000_000,
357 relativeUrl: "/api/assets/token-b/icon.svg",
358 }),
359 );
360 expect(registry.get(favicon)).toBe("https://reconnected.test/api/assets/token-b/icon.svg");
361​
362 registry.set(
363 result,
364 AsyncResult.success({
365 expiresAt: 4_000_000_000_000,
366 relativeUrl: "/api/assets/token-c/project-favicon-missing",
367 }),
368 );
369 expect(registry.get(favicon)).toBe(
370 "https://reconnected.test/api/assets/token-c/project-favicon-missing",
371 );
372 registry.set(connection, Option.none());
373 expect(registry.get(favicon)).toBe(
374 "https://reconnected.test/api/assets/token-c/project-favicon-missing",
375 );
376 } finally {
377 unmount();
378 registry.dispose();
379 }
380 });
381​
382 it("does not reuse another environment, workspace, or selected icon's cached URL", () => {
383 const registry = AtomRegistry.make();
384 const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
385 AsyncResult.success({
386 expiresAt: 4_000_000_000_000,
387 relativeUrl: "/api/assets/token/icon.svg",
388 }),
389 );
390 const favicon = createProjectFaviconUrlAtomFamily({
391 createUrl: () => result,
392 preparedConnection: () => Atom.make(Option.some({ httpBaseUrl: "https://remote.test" })),
393 });
394 const target = { environmentId: EnvironmentId.make("remote"), cwd: "/workspace" };
395 const unmount = registry.mount(favicon(target));
396 try {
397 expect(registry.get(favicon(target))).toBe("https://remote.test/api/assets/token/icon.svg");
398 registry.set(result, AsyncResult.failure(Cause.die("disconnected")));
399 expect(
400 registry.get(favicon({ ...target, environmentId: EnvironmentId.make("other") })),
401 ).toBeNull();
402 expect(registry.get(favicon({ ...target, cwd: "/other" }))).toBeNull();
403 expect(registry.get(favicon({ ...target, faviconPath: "brand.svg" }))).toBeNull();
404 expect(registry.get(favicon({ ...target, faviconPath: null }))).toBe(
405 "https://remote.test/api/assets/token/icon.svg",
406 );
407 } finally {
408 unmount();
409 registry.dispose();
410 }
411 });
412});