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

assets.test.ts

488 lines17.3 KB

1import { describe, expect, it } from "@effect/vitest";
2import {
3 type AssetCreateUrlResult,
4 type AssetResource,
5 AssetWorkspaceAssetNotFoundError,
6 EnvironmentId,
7 ThreadId,
8 WS_METHODS,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Queue from "effect/Queue";
15import * as Stream from "effect/Stream";
16import * as SubscriptionRef from "effect/SubscriptionRef";
17import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
18​
19import {
20 AVAILABLE_CONNECTION_STATE,
21 type PreparedConnection,
22 PrimaryConnectionTarget,
23 type SupervisorConnectionState,
24} from "../connection/model.ts";
25import * as EnvironmentRegistry from "../connection/registry.ts";
26import * as EnvironmentSupervisor from "../connection/supervisor.ts";
27import { resolveMediaSource } from "../mediaSource.ts";
28import type * as RpcSession from "../rpc/session.ts";
29import {
30 ASSET_URL_MAX_IN_FLIGHT,
31 createAssetEnvironmentAtoms,
32 createProjectFaviconUrlAtomFamily,
33 makeRevisionedAssetUrlFamily,
34} from "./assets.ts";
35​
36describe("project favicon URL cache", () => {
37 it("does not reuse another environment, workspace, or selected icon's cached URL", () => {
38 const registry = AtomRegistry.make();
39 const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
40 AsyncResult.success({
41 expiresAt: 4_000_000_000_000,
42 relativeUrl: "/api/assets/token/icon.svg",
43 }),
44 );
45 const favicon = createProjectFaviconUrlAtomFamily({
46 createUrl: () => result,
47 preparedConnection: () => Atom.make(Option.some({ httpBaseUrl: "https://remote.test" })),
48 });
49 const target = { environmentId: EnvironmentId.make("remote"), cwd: "/workspace" };
50 const unmount = registry.mount(favicon(target));
51 try {
52 expect(registry.get(favicon(target))).toBe("https://remote.test/api/assets/token/icon.svg");
53 registry.set(result, AsyncResult.failure(Cause.die("disconnected")));
54 expect(
55 registry.get(favicon({ ...target, environmentId: EnvironmentId.make("other") })),
56 ).toBeNull();
57 expect(registry.get(favicon({ ...target, cwd: "/other" }))).toBeNull();
58 expect(registry.get(favicon({ ...target, faviconPath: "brand.svg" }))).toBeNull();
59 expect(registry.get(favicon({ ...target, faviconPath: null }))).toBe(
60 "https://remote.test/api/assets/token/icon.svg",
61 );
62 } finally {
63 unmount();
64 registry.dispose();
65 }
66 });
67});
68​
69/**
70 * Environments whose `assets.createUrl` never answers until the test releases a call.
71 * `started` receives the environment of each call as it begins, and `inFlight` counts
72 * calls that have begun and not yet been released or interrupted.
73 */
74const makeAssetUrlHarness = Effect.fn("TestAssetUrl.makeHarness")(function* (
75 environmentIds: ReadonlyArray<EnvironmentId>,
76) {
77 const started = yield* Queue.unbounded<EnvironmentId>();
78 const inFlight = new Map<EnvironmentId, number>();
79 const maxInFlight = new Map<EnvironmentId, number>();
80 const releases = new Map<EnvironmentId, Queue.Queue<void>>();
81 const supervisors = new Map<
82 EnvironmentId,
83 EnvironmentSupervisor.EnvironmentSupervisor["Service"]
84 >();
85 const sessions = new Map<
86 EnvironmentId,
87 SubscriptionRef.SubscriptionRef<Option.Option<RpcSession.RpcSession>>
88 >();
89 const makeSession = (environmentId: EnvironmentId) =>
90 ({
91 client: {
92 [WS_METHODS.assetsCreateUrl]: () =>
93 Effect.gen(function* () {
94 const now = (inFlight.get(environmentId) ?? 0) + 1;
95 inFlight.set(environmentId, now);
96 maxInFlight.set(environmentId, Math.max(maxInFlight.get(environmentId) ?? 0, now));
97 yield* Queue.offer(started, environmentId);
98 yield* Queue.take(releases.get(environmentId)!);
99 return { relativeUrl: "/api/assets/token/image.png", expiresAt: 4_000_000_000_000 };
100 }).pipe(
101 Effect.ensuring(
102 Effect.sync(() =>
103 inFlight.set(environmentId, (inFlight.get(environmentId) ?? 1) - 1),
104 ),
105 ),
106 ),
107 },
108 }) as unknown as RpcSession.RpcSession;
109 for (const environmentId of environmentIds) {
110 releases.set(environmentId, yield* Queue.unbounded<void>());
111 const session = yield* SubscriptionRef.make(Option.some(makeSession(environmentId)));
112 sessions.set(environmentId, session);
113 supervisors.set(
114 environmentId,
115 EnvironmentSupervisor.EnvironmentSupervisor.of({
116 target: new PrimaryConnectionTarget({
117 environmentId,
118 label: environmentId,
119 httpBaseUrl: "https://assets.example.test",
120 wsBaseUrl: "wss://assets.example.test",
121 }),
122 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
123 ...AVAILABLE_CONNECTION_STATE,
124 desired: true,
125 network: "online",
126 phase: "connected",
127 attempt: 1,
128 generation: 1,
129 }),
130 session,
131 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none()),
132 connect: Effect.void,
133 disconnect: Effect.void,
134 retryNow: Effect.void,
135 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]),
136 );
137 }
138 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (environmentId, effect) =>
139 Effect.provideService(
140 effect,
141 EnvironmentSupervisor.EnvironmentSupervisor,
142 supervisors.get(environmentId)!,
143 );
144 const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
145 environmentId,
146 stream,
147 ) =>
148 Stream.provideService(
149 stream,
150 EnvironmentSupervisor.EnvironmentSupervisor,
151 supervisors.get(environmentId)!,
152 );
153 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
154 run,
155 followStream,
156 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
157 const registry = AtomRegistry.make();
158 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
159 const atoms = createAssetEnvironmentAtoms(
160 Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry)),
161 );
162 return {
163 started,
164 inFlight: (environmentId: EnvironmentId) => inFlight.get(environmentId) ?? 0,
165 maxInFlight: (environmentId: EnvironmentId) => maxInFlight.get(environmentId) ?? 0,
166 release: (environmentId: EnvironmentId) => Queue.offer(releases.get(environmentId)!, undefined),
167 replaceSession: (environmentId: EnvironmentId) =>
168 SubscriptionRef.set(sessions.get(environmentId)!, Option.some(makeSession(environmentId))),
169 mountImages: (environmentId: EnvironmentId, count: number) => {
170 for (let index = 0; index < count; index += 1) {
171 registry.mount(
172 atoms.createUrl({
173 environmentId,
174 input: { resource: { _tag: "attachment", attachmentId: `image-${index}` } },
175 }),
176 );
177 }
178 },
179 };
180});
181​
182describe("asset URL requests", () => {
183 const remote = EnvironmentId.make("asset-remote");
184 const other = EnvironmentId.make("asset-other");
185​
186 it.effect("keeps a thread of images from flooding one environment with requests", () =>
187 Effect.scoped(
188 Effect.gen(function* () {
189 const harness = yield* makeAssetUrlHarness([remote]);
190 const total = ASSET_URL_MAX_IN_FLIGHT * 3;
191 harness.mountImages(remote, total);
192​
193 for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
194 yield* Queue.take(harness.started);
195 }
196 expect(harness.inFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
197​
198 // Each answer admits the next waiting request.
199 for (let call = 0; call < total; call += 1) {
200 yield* harness.release(remote);
201 if (call < total - ASSET_URL_MAX_IN_FLIGHT) yield* Queue.take(harness.started);
202 }
203 expect(harness.maxInFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
204 }),
205 ),
206 );
207​
208 it.effect("limits each environment on its own", () =>
209 Effect.scoped(
210 Effect.gen(function* () {
211 const harness = yield* makeAssetUrlHarness([remote, other]);
212 harness.mountImages(remote, ASSET_URL_MAX_IN_FLIGHT + 2);
213 for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
214 yield* Queue.take(harness.started);
215 }
216 harness.mountImages(other, 1);
217 expect(yield* Queue.take(harness.started)).toBe(other);
218 expect(harness.inFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
219 }),
220 ),
221 );
222​
223 it.effect("frees the limit when the session behind the requests is replaced", () =>
224 Effect.scoped(
225 Effect.gen(function* () {
226 const harness = yield* makeAssetUrlHarness([remote]);
227 harness.mountImages(remote, ASSET_URL_MAX_IN_FLIGHT * 2);
228 for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
229 yield* Queue.take(harness.started);
230 }
231​
232 yield* harness.replaceSession(remote);
233 for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
234 yield* Queue.take(harness.started);
235 }
236 expect(harness.maxInFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
237 }),
238 ),
239 );
240});
241​
242describe("desktop-local media fallback", () => {
243 const remote = EnvironmentId.make("media-remote");
244 const local = EnvironmentId.make("media-local");
245 const threadId = ThreadId.make("remote-thread");
246​
247 // The remote is missing every file; the desktop has one at every absolute path.
248 const makeFallback = Effect.fn("TestAssetUrl.makeFallback")(function* () {
249 const calls: Array<EnvironmentId> = [];
250 const supervisor = (environmentId: EnvironmentId) =>
251 Effect.gen(function* () {
252 const session = {
253 client: {
254 [WS_METHODS.assetsCreateUrl]: ({ resource }: { resource: AssetResource }) =>
255 Effect.suspend(() => {
256 calls.push(environmentId);
257 return environmentId === remote
258 ? Effect.fail(new AssetWorkspaceAssetNotFoundError({ resource }))
259 : Effect.succeed({ relativeUrl: "/api/assets/t/local.png", expiresAt: 4e12 });
260 }),
261 },
262 } as unknown as RpcSession.RpcSession;
263 return EnvironmentSupervisor.EnvironmentSupervisor.of({
264 target: new PrimaryConnectionTarget({
265 environmentId,
266 label: environmentId,
267 httpBaseUrl: `https://${environmentId}.test`,
268 wsBaseUrl: `wss://${environmentId}.test`,
269 }),
270 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
271 ...AVAILABLE_CONNECTION_STATE,
272 desired: true,
273 network: "online",
274 phase: "connected",
275 attempt: 1,
276 generation: 1,
277 }),
278 session: yield* SubscriptionRef.make(Option.some(session)),
279 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none()),
280 connect: Effect.void,
281 disconnect: Effect.void,
282 retryNow: Effect.void,
283 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
284 });
285 const supervisors = new Map([
286 [remote, yield* supervisor(remote)],
287 [local, yield* supervisor(local)],
288 ]);
289 type Registry = EnvironmentRegistry.EnvironmentRegistry["Service"];
290 const run: Registry["run"] = (environmentId, effect) =>
291 Effect.provideService(
292 effect,
293 EnvironmentSupervisor.EnvironmentSupervisor,
294 supervisors.get(environmentId)!,
295 );
296 const followStream: Registry["followStream"] = (environmentId, stream) =>
297 Stream.provideService(
298 stream,
299 EnvironmentSupervisor.EnvironmentSupervisor,
300 supervisors.get(environmentId)!,
301 );
302 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
303 run,
304 followStream,
305 } as unknown as Registry);
306 const registry = AtomRegistry.make();
307 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
308 const atoms = createAssetEnvironmentAtoms(
309 Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry)),
310 Atom.make({ environmentId: local, httpBaseUrl: "https://media-local.test" }),
311 );
312 const load = (source: string) => {
313 const media = resolveMediaSource(source, { threadId, workspaceRoot: "/tmp/repo" });
314 if (media?.access !== "environment") throw new Error(`${source} is not host media`);
315 calls.length = 0;
316 return AtomRegistry.getResult(
317 registry,
318 atoms.createUrl({ environmentId: remote, input: { resource: media.resource } }),
319 ).pipe(
320 Effect.result,
321 Effect.map((result) => ({ loaded: result._tag === "Success", calls: [...calls] })),
322 );
323 };
324 return { load };
325 });
326​
327 it.effect("keeps a relative Markdown image on the thread's environment", () =>
328 Effect.scoped(
329 Effect.gen(function* () {
330 const { load } = yield* makeFallback();
331 expect(yield* load("docs/report.png")).toEqual({ loaded: false, calls: [remote] });
332 // The same resolved path written absolute still falls back, and shares no cached result.
333 expect(yield* load("/tmp/repo/docs/report.png")).toEqual({
334 loaded: true,
335 calls: [remote, local],
336 });
337 }),
338 ),
339 );
340});
341​
342const revisionedEnvironmentId = EnvironmentId.make("environment-1");
343const revisionedResource: AssetResource = {
344 _tag: "workspace-file",
345 threadId: ThreadId.make("thread-1"),
346 path: "docs/diagram.png",
347};
348​
349type MintResult = AsyncResult.AsyncResult<{
350 relativeUrl: string;
351 expiresAt: number;
352 fileRevision?: string;
353}>;
354​
355const minted = (n: number, fileRevision?: string): MintResult =>
356 AsyncResult.success({
357 relativeUrl: `/a/${n}`,
358 expiresAt: 60 * 60_000,
359 ...(fileRevision === undefined ? {} : { fileRevision }),
360 });
361​
362// A stand-in for the asset URL query: a refresh starts a mint (counted, shown as
363// waiting) and `settle` completes the latest one.
364function setup(initial: MintResult) {
365 let mints = 0;
366 // Node removal runs on the registry's scheduler; `unmount` flushes it so the
367 // next mount of the same revision builds a fresh node.
368 const scheduled: Array<() => void> = [];
369 const registry = AtomRegistry.make({
370 scheduleTask: (task) => {
371 scheduled.push(task);
372 return () => {};
373 },
374 });
375 const server = Atom.make(initial).pipe(Atom.keepAlive);
376 const query = Atom.readable(
377 (get) => get(server),
378 () => {
379 mints += 1;
380 registry.set(server, AsyncResult.waiting(registry.get(server)));
381 },
382 ).pipe(Atom.keepAlive);
383 const revisioned = makeRevisionedAssetUrlFamily(
384 () => query,
385 () => 0,
386 );
387 const atom = (revision: string | null) =>
388 revisioned({
389 environmentId: revisionedEnvironmentId,
390 input: { resource: revisionedResource },
391 revision,
392 });
393 const mount = (revision: string | null) => {
394 const release = registry.mount(atom(revision));
395 return () => {
396 release();
397 for (const task of scheduled.splice(0)) task();
398 };
399 };
400 const settle = (fileRevision?: string) => registry.set(server, minted(mints + 1, fileRevision));
401 const url = (revision: string | null) => {
402 const result = registry.get(atom(revision));
403 return result._tag === "Success" ? result.value.relativeUrl : null;
404 };
405 return { mount, settle, url, mints: () => mints };
407​
408describe("makeRevisionedAssetUrlFamily", () => {
409 it("re-mints a settled URL on first read and on each new revision, not on remount", () => {
410 const { mount, settle, mints } = setup(minted(0));
411​
412 mount("mutation-1")();
413 expect(mints()).toBe(1);
414 settle();
415​
416 mount("mutation-1")();
417 expect(mints()).toBe(1);
418​
419 mount("mutation-2")();
420 expect(mints()).toBe(2);
421 });
422​
423 it("re-mints when a revert returns to an earlier revision", () => {
424 const { mount, settle, mints } = setup(minted(0));
425​
426 mount("mutation-a")();
427 settle();
428 mount("mutation-b")();
429 settle();
430 expect(mints()).toBe(2);
431​
432 const reverted = mount("mutation-a");
433 expect(mints()).toBe(3);
434 reverted();
435 });
436​
437 it("shares a mint in flight on the first read", () => {
438 const { mount, mints } = setup(AsyncResult.initial(true));
439​
440 mount("mutation-1")();
441 expect(mints()).toBe(0);
442 });
443​
444 it("re-mints after a mint that was in flight when the revision changed", () => {
445 const { mount, settle, mints } = setup(minted(0));
446​
447 const before = mount("mutation-1");
448 settle();
449 const edited = mount("mutation-2");
450 expect(mints()).toBe(2);
451 before();
452​
453 const stillMinting = mount("mutation-3");
454 edited();
455 expect(mints()).toBe(2);
456​
457 settle();
458 expect(mints()).toBe(3);
459 settle();
460 expect(mints()).toBe(3);
461 stillMinting();
462 });
463​
464 it("keeps the URL while the file is unchanged and swaps it once the file changes", () => {
465 const { mount, settle, url } = setup(minted(0, "file-a"));
466​
467 const first = mount("mutation-1");
468 settle("file-a");
469 first();
470​
471 const unchanged = mount("mutation-2");
472 settle("file-a");
473 expect(url("mutation-2")).toBe("/a/0");
474 unchanged();
475​
476 // The query now holds /a/3; a later revision must still keep the URL on screen.
477 const stillUnchanged = mount("mutation-3");
478 expect(url("mutation-3")).toBe("/a/0");
479 settle("file-a");
480 expect(url("mutation-3")).toBe("/a/0");
481 stillUnchanged();
482​
483 const edited = mount("mutation-4");
484 settle("file-b");
485 expect(url("mutation-4")).toBe("/a/5");
486 edited();
487 });
488});