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