fix(clients): persist project icons across reloads and reconnects (#10138)
This commit is contained in:
1 parent
050690d1bc
commit
eee05575eb
20 files changed
+1207
-62
No files matched your search
@@ -0,0 +1,323 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
createProjectFaviconCache,
|
||||
createProjectFaviconImageLoader,
|
||||
PROJECT_FAVICON_CACHE_MAX_BYTES,
|
||||
PROJECT_FAVICON_CACHE_MAX_ENTRIES,
|
||||
PROJECT_FAVICON_MAX_DATA_URL_LENGTH,
|
||||
PROJECT_FAVICON_MAX_SOURCE_BYTES,
|
||||
type ProjectFaviconEntry,
|
||||
type ProjectFaviconStorage,
|
||||
} from "./projectFaviconCache.ts";
|
||||
|
||||
const target = { environmentId: EnvironmentId.make("remote"), cwd: "/workspace" };
|
||||
const url = "https://remote.test/api/assets/token-a/vabc-icon.svg";
|
||||
const image = "data:image/png;base64,aWNvbg==";
|
||||
const replacement = "data:image/png;base64,bmV3";
|
||||
const signal = () => new AbortController().signal;
|
||||
|
||||
function deferred<A>() {
|
||||
let resolve!: (value: A) => void;
|
||||
const promise = new Promise<A>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const records = new Map<string, ProjectFaviconEntry>();
|
||||
const load = vi.fn(async () => image);
|
||||
const storage: ProjectFaviconStorage = {
|
||||
list: async () => [...records.values()],
|
||||
put: async (key, entry) => {
|
||||
records.set(key, entry);
|
||||
},
|
||||
remove: async (key) => {
|
||||
records.delete(key);
|
||||
},
|
||||
};
|
||||
return {
|
||||
storage,
|
||||
load,
|
||||
records,
|
||||
cache: createProjectFaviconCache({ storage, load }),
|
||||
};
|
||||
}
|
||||
|
||||
describe("persistent project favicon cache", () => {
|
||||
it("restores image bytes in a fresh client before any remote response", async () => {
|
||||
const { cache, storage, load } = fixture();
|
||||
expect(await cache.resolve(target, url, signal())).toBe(image);
|
||||
await cache.flush();
|
||||
const reloaded = createProjectFaviconCache({ storage, load });
|
||||
await reloaded.hydrate();
|
||||
expect(reloaded.peek(target)).toBe(image);
|
||||
expect(await reloaded.resolve(target, null, signal())).toBe(image);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reuses the image when signed URLs or connection origins change", async () => {
|
||||
const { cache, load } = fixture();
|
||||
await cache.resolve(target, url, signal());
|
||||
expect(
|
||||
await cache.resolve(target, "https://new.test/api/assets/token-b/vabc-icon.svg", signal()),
|
||||
).toBe(image);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps the old image during refresh and failures, then persists its replacement", async () => {
|
||||
const { cache, load, storage } = fixture();
|
||||
await cache.resolve(target, url, signal());
|
||||
const next = deferred<string>();
|
||||
load.mockImplementationOnce(() => next.promise);
|
||||
const refreshing = cache.resolve(target, url.replace("vabc", "vdef"), signal());
|
||||
expect(cache.peek(target)).toBe(image);
|
||||
next.resolve(replacement);
|
||||
expect(await refreshing).toBe(replacement);
|
||||
load.mockRejectedValueOnce(new Error("offline"));
|
||||
expect(await cache.resolve(target, url, signal())).toBe(replacement);
|
||||
await cache.flush();
|
||||
expect(await createProjectFaviconCache({ storage, load }).resolve(target, null, signal())).toBe(
|
||||
replacement,
|
||||
);
|
||||
});
|
||||
|
||||
it("persists confirmed removal and ignores an aborted older download", async () => {
|
||||
const { cache, load, storage } = fixture();
|
||||
await cache.resolve(target, url, signal());
|
||||
const next = deferred<string>();
|
||||
const started = deferred<void>();
|
||||
load.mockImplementationOnce(() => {
|
||||
started.resolve();
|
||||
return next.promise;
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const pending = cache.resolve(target, url.replace("vabc", "vdef"), controller.signal);
|
||||
await started.promise;
|
||||
controller.abort();
|
||||
expect(
|
||||
await cache.resolve(
|
||||
target,
|
||||
"https://remote.test/api/assets/token/project-favicon-missing",
|
||||
signal(),
|
||||
),
|
||||
).toBeNull();
|
||||
next.resolve(replacement);
|
||||
await pending;
|
||||
await cache.flush();
|
||||
expect(
|
||||
await createProjectFaviconCache({ storage, load }).resolve(target, null, signal()),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("isolates environments, workspaces, and icon selections", async () => {
|
||||
const { cache } = fixture();
|
||||
await cache.resolve(target, url, signal());
|
||||
expect(cache.peek({ ...target, faviconPath: null })).toBe(image);
|
||||
expect(cache.peek({ ...target, faviconPath: "brand.svg" })).toBeNull();
|
||||
expect(cache.peek({ ...target, cwd: "/other" })).toBeNull();
|
||||
expect(cache.peek({ ...target, environmentId: EnvironmentId.make("other") })).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
scope: "one environment",
|
||||
clear: (cache: ReturnType<typeof fixture>["cache"]) =>
|
||||
cache.clearEnvironment(target.environmentId),
|
||||
remaining: 1,
|
||||
},
|
||||
{
|
||||
scope: "every environment",
|
||||
clear: (cache: ReturnType<typeof fixture>["cache"]) => cache.clearAll(),
|
||||
remaining: 0,
|
||||
},
|
||||
])(
|
||||
"does not restore images for $scope removed during a download",
|
||||
async ({ clear, remaining }) => {
|
||||
const { cache, load, records } = fixture();
|
||||
const other = { ...target, environmentId: EnvironmentId.make("other") };
|
||||
await cache.resolve(other, url, signal());
|
||||
const next = deferred<string>();
|
||||
const started = deferred<void>();
|
||||
load.mockImplementationOnce(() => {
|
||||
started.resolve();
|
||||
return next.promise;
|
||||
});
|
||||
const pending = cache.resolve(target, url, signal());
|
||||
await started.promise;
|
||||
await clear(cache);
|
||||
next.resolve(image);
|
||||
await pending;
|
||||
await cache.flush();
|
||||
expect(cache.peek(target)).toBeNull();
|
||||
expect(records.size).toBe(remaining);
|
||||
},
|
||||
);
|
||||
|
||||
it("discards a download that starts while the environment is being cleared", async () => {
|
||||
const records = new Map<string, ProjectFaviconEntry>();
|
||||
const removal = deferred<void>();
|
||||
const load = vi.fn(async () => image);
|
||||
const storage: ProjectFaviconStorage = {
|
||||
list: async () => [...records.values()],
|
||||
put: async (key, entry) => {
|
||||
records.set(key, entry);
|
||||
},
|
||||
remove: async (key) => {
|
||||
await removal.promise;
|
||||
records.delete(key);
|
||||
},
|
||||
};
|
||||
const cache = createProjectFaviconCache({ storage, load });
|
||||
await cache.resolve(target, url, signal());
|
||||
await cache.flush();
|
||||
const clearing = cache.clearEnvironment(target.environmentId);
|
||||
await Promise.resolve();
|
||||
const late = cache.resolve(target, url.replace("vabc", "vdef"), signal());
|
||||
removal.resolve();
|
||||
await clearing;
|
||||
expect(records.size).toBe(0);
|
||||
expect(cache.peek(target)).toBeNull();
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
expect(await late).toBe(image);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("bounds individual images, total bytes, and entry count in storage", async () => {
|
||||
const { cache, load, records } = fixture();
|
||||
load.mockResolvedValueOnce(
|
||||
`data:image/png;base64,${"a".repeat(PROJECT_FAVICON_MAX_DATA_URL_LENGTH)}`,
|
||||
);
|
||||
expect(await cache.resolve(target, url, signal())).toBe(url);
|
||||
expect(cache.peek(target)).toBeNull();
|
||||
const large = `data:image/png;base64,${"a".repeat(PROJECT_FAVICON_MAX_DATA_URL_LENGTH - 32)}`;
|
||||
load.mockResolvedValue(large);
|
||||
for (let i = 0; i < 40; i++) {
|
||||
await cache.resolve({ ...target, cwd: `/large-${i}` }, url, signal());
|
||||
}
|
||||
await cache.flush();
|
||||
expect(
|
||||
[...records.values()].reduce((total, entry) => total + entry.dataUrl.length, 0),
|
||||
).toBeLessThanOrEqual(PROJECT_FAVICON_CACHE_MAX_BYTES);
|
||||
expect(cache.peek({ ...target, cwd: "/large-0" })).toBeNull();
|
||||
expect(cache.peek({ ...target, cwd: "/large-39" })).toBe(large);
|
||||
load.mockResolvedValue(image);
|
||||
for (let i = 0; i <= PROJECT_FAVICON_CACHE_MAX_ENTRIES; i++) {
|
||||
await cache.resolve({ ...target, cwd: `/small-${i}` }, url, signal());
|
||||
}
|
||||
await cache.flush();
|
||||
expect(records.size).toBe(PROJECT_FAVICON_CACHE_MAX_ENTRIES);
|
||||
expect(cache.peek({ ...target, cwd: "/small-0" })).toBeNull();
|
||||
});
|
||||
|
||||
it("skips corrupt records and tolerates unavailable storage", async () => {
|
||||
const corrupt = createProjectFaviconCache({
|
||||
storage: {
|
||||
list: async () => [
|
||||
{ ...target, faviconPath: null, revision: "r", dataUrl: image },
|
||||
{ ...target, cwd: "/broken", faviconPath: null, revision: "r", dataUrl: "not-an-image" },
|
||||
"garbage",
|
||||
],
|
||||
put: async () => {},
|
||||
remove: async () => {},
|
||||
},
|
||||
load: async () => replacement,
|
||||
});
|
||||
await corrupt.hydrate();
|
||||
expect(corrupt.peek(target)).toBe(image);
|
||||
expect(corrupt.peek({ ...target, cwd: "/broken" })).toBeNull();
|
||||
|
||||
const unavailable = createProjectFaviconCache({
|
||||
storage: {
|
||||
list: async () => {
|
||||
throw new Error("storage unavailable");
|
||||
},
|
||||
put: async () => {
|
||||
throw new Error("quota exceeded");
|
||||
},
|
||||
remove: async () => {
|
||||
throw new Error("quota exceeded");
|
||||
},
|
||||
},
|
||||
load: async () => image,
|
||||
});
|
||||
expect(await unavailable.resolve(target, url, signal())).toBe(image);
|
||||
await unavailable.flush();
|
||||
expect(unavailable.peek(target)).toBe(image);
|
||||
});
|
||||
});
|
||||
|
||||
describe("project favicon image loader", () => {
|
||||
const svg =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><rect width="16" height="16"/></svg>';
|
||||
const svgBase64 = btoa(svg);
|
||||
|
||||
function loader(response: Response, downscale = vi.fn(async () => replacement)) {
|
||||
return {
|
||||
downscale,
|
||||
load: createProjectFaviconImageLoader({ fetch: async () => response, downscale }),
|
||||
};
|
||||
}
|
||||
|
||||
it("inlines small icons exactly as served without rasterizing", async () => {
|
||||
const { load, downscale } = loader(
|
||||
new Response(svg, { headers: { "content-type": "image/svg+xml; charset=utf-8" } }),
|
||||
);
|
||||
expect(await load(url, signal())).toBe(`data:image/svg+xml;base64,${svgBase64}`);
|
||||
expect(downscale).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to the file extension when the response has no image type", async () => {
|
||||
const { load } = loader(new Response(svg, { headers: { "content-type": "text/plain" } }));
|
||||
expect(await load(url, signal())).toBe(`data:image/svg+xml;base64,${svgBase64}`);
|
||||
});
|
||||
|
||||
it("downscales large bitmaps and refuses large vector icons", async () => {
|
||||
const bytes = new Uint8Array(PROJECT_FAVICON_MAX_DATA_URL_LENGTH);
|
||||
const bitmap = loader(new Response(bytes, { headers: { "content-type": "image/png" } }));
|
||||
expect(await bitmap.load("https://remote.test/api/assets/t/v1-icon.png", signal())).toBe(
|
||||
replacement,
|
||||
);
|
||||
expect(bitmap.downscale).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ mimeType: "image/png", bytes }),
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
const vector = loader(new Response(bytes, { headers: { "content-type": "image/svg+xml" } }));
|
||||
await expect(vector.load(url, signal())).rejects.toThrow("exceeds the cache limit");
|
||||
expect(vector.downscale).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stops reading a response that exceeds the source limit", async () => {
|
||||
let pulled = 0;
|
||||
const chunk = new Uint8Array(1024 * 1024);
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
pulled += 1;
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
});
|
||||
const { load, downscale } = loader(
|
||||
new Response(stream, { headers: { "content-type": "image/png" } }),
|
||||
);
|
||||
await expect(load(url, signal())).rejects.toThrow("too large");
|
||||
expect(pulled).toBeLessThan(PROJECT_FAVICON_MAX_SOURCE_BYTES / chunk.byteLength + 3);
|
||||
expect(downscale).not.toHaveBeenCalled();
|
||||
const declared = loader(
|
||||
new Response("x", {
|
||||
headers: { "content-type": "image/png", "content-length": String(2 ** 40) },
|
||||
}),
|
||||
);
|
||||
await expect(declared.load(url, signal())).rejects.toThrow("too large");
|
||||
});
|
||||
|
||||
it("rejects failed responses and non-image payloads", async () => {
|
||||
const failed = loader(new Response("nope", { status: 404 }));
|
||||
await expect(failed.load(url, signal())).rejects.toThrow("404");
|
||||
const html = loader(new Response("<html/>", { headers: { "content-type": "text/html" } }));
|
||||
await expect(
|
||||
html.load("https://remote.test/api/assets/t/v1-favicon", signal()),
|
||||
).rejects.toThrow("no image type");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,263 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { mediaMimeType } from "@t3tools/shared/filePreview";
|
||||
import {
|
||||
getProjectFaviconCacheKey,
|
||||
getProjectFaviconResourceKey,
|
||||
isProjectFaviconFallbackUrl,
|
||||
} from "@t3tools/shared/projectFavicon";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const PROJECT_FAVICON_THUMBNAIL_SIZE = 96;
|
||||
export const PROJECT_FAVICON_MAX_DATA_URL_LENGTH = 32 * 1024;
|
||||
/** Larger sources are not worth decoding for an icon and are left to the remote URL. */
|
||||
export const PROJECT_FAVICON_MAX_SOURCE_BYTES = 4 * 1024 * 1024;
|
||||
export const PROJECT_FAVICON_CACHE_MAX_BYTES = 1024 * 1024;
|
||||
export const PROJECT_FAVICON_CACHE_MAX_ENTRIES = 128;
|
||||
|
||||
export interface ProjectFaviconTarget {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly cwd: string;
|
||||
readonly faviconPath?: string | null | undefined;
|
||||
}
|
||||
|
||||
const ImageDataUrl = Schema.String.check(
|
||||
Schema.isMaxLength(PROJECT_FAVICON_MAX_DATA_URL_LENGTH),
|
||||
Schema.isPattern(
|
||||
/^data:image\/(?:png|jpeg|gif|webp|avif|svg\+xml|x-icon|vnd\.microsoft\.icon);base64,[A-Za-z0-9+/]+={0,2}$/,
|
||||
),
|
||||
);
|
||||
const Entry = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
cwd: Schema.String,
|
||||
faviconPath: Schema.NullOr(Schema.String),
|
||||
revision: Schema.String,
|
||||
dataUrl: ImageDataUrl,
|
||||
});
|
||||
export type ProjectFaviconEntry = typeof Entry.Type;
|
||||
const decodeEntry = Schema.decodeUnknownOption(Entry);
|
||||
const isImageDataUrl = Schema.is(ImageDataUrl);
|
||||
|
||||
function keyFor(target: ProjectFaviconTarget) {
|
||||
return getProjectFaviconResourceKey(target.environmentId, target.cwd, target.faviconPath);
|
||||
}
|
||||
|
||||
export interface ProjectFaviconStorage {
|
||||
/** Every persisted record; entries that fail validation are ignored. */
|
||||
readonly list: () => Promise<ReadonlyArray<unknown>>;
|
||||
readonly put: (key: string, entry: ProjectFaviconEntry) => Promise<void>;
|
||||
readonly remove: (key: string, entry: ProjectFaviconEntry) => Promise<void>;
|
||||
}
|
||||
|
||||
async function readBounded(response: Response, maxBytes: number) {
|
||||
const declared = Number(response.headers.get("content-length"));
|
||||
if (declared > maxBytes) throw new Error("Project icon is too large to decode.");
|
||||
if (!response.body) {
|
||||
const bytes = new Uint8Array<ArrayBuffer>(await response.arrayBuffer());
|
||||
if (bytes.byteLength > maxBytes) throw new Error("Project icon is too large to decode.");
|
||||
return bytes;
|
||||
}
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Array<Uint8Array> = [];
|
||||
let total = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) throw new Error("Project icon is too large to decode.");
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.cancel().catch(() => {});
|
||||
}
|
||||
const bytes = new Uint8Array<ArrayBuffer>(new ArrayBuffer(total));
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches an icon and inlines its bytes when they fit the cache limit, so SVGs
|
||||
* and small bitmaps are stored exactly as served. Larger bitmaps go through the
|
||||
* platform downscaler; larger SVGs stay remote because rasterizing them without
|
||||
* intrinsic dimensions is unreliable.
|
||||
*/
|
||||
export function createProjectFaviconImageLoader(input: {
|
||||
readonly fetch?: typeof fetch;
|
||||
readonly downscale: (
|
||||
image: {
|
||||
readonly url: string;
|
||||
readonly mimeType: string;
|
||||
readonly bytes: Uint8Array<ArrayBuffer>;
|
||||
},
|
||||
signal: AbortSignal,
|
||||
) => Promise<string>;
|
||||
}) {
|
||||
const fetchImpl = input.fetch ?? globalThis.fetch;
|
||||
return async (url: string, signal: AbortSignal): Promise<string> => {
|
||||
const response = await fetchImpl(url, { signal });
|
||||
if (!response.ok) throw new Error(`Project icon request failed with ${response.status}.`);
|
||||
const contentType = response.headers
|
||||
.get("content-type")
|
||||
?.split(";", 1)[0]
|
||||
?.trim()
|
||||
.toLowerCase();
|
||||
const mimeType = contentType?.startsWith("image/") ? contentType : mediaMimeType(url);
|
||||
if (!mimeType) throw new Error("Project icon has no image type.");
|
||||
const bytes = await readBounded(response, PROJECT_FAVICON_MAX_SOURCE_BYTES);
|
||||
signal.throwIfAborted();
|
||||
const dataUrl = `data:${mimeType};base64,${Encoding.encodeBase64(bytes)}`;
|
||||
if (isImageDataUrl(dataUrl)) return dataUrl;
|
||||
if (mimeType === "image/svg+xml") throw new Error("Project icon exceeds the cache limit.");
|
||||
return input.downscale({ url, mimeType, bytes }, signal);
|
||||
};
|
||||
}
|
||||
|
||||
/** Stores small, self-contained images so startup never needs an old signed URL. */
|
||||
export function createProjectFaviconCache(input: {
|
||||
readonly storage: ProjectFaviconStorage;
|
||||
readonly load: (url: string, signal: AbortSignal) => Promise<string>;
|
||||
}) {
|
||||
const entries = new Map<string, ProjectFaviconEntry>();
|
||||
const environmentRevisions = new Map<EnvironmentId, number>();
|
||||
let generation = 0;
|
||||
let hydration: Promise<void> | undefined;
|
||||
let clearing: Promise<void> | undefined;
|
||||
const pending = new Set<Promise<void>>();
|
||||
|
||||
const persist = (operation: () => Promise<void>) => {
|
||||
const task: Promise<void> = operation()
|
||||
.catch(() => {
|
||||
// Keep the in-memory image if local storage is full or unavailable.
|
||||
})
|
||||
.finally(() => pending.delete(task));
|
||||
pending.add(task);
|
||||
};
|
||||
|
||||
const remove = (key: string) => {
|
||||
const entry = entries.get(key);
|
||||
if (!entry) return;
|
||||
entries.delete(key);
|
||||
persist(() => input.storage.remove(key, entry));
|
||||
};
|
||||
|
||||
const trim = () => {
|
||||
let bytes = 0;
|
||||
for (const entry of entries.values()) bytes += entry.dataUrl.length;
|
||||
while (
|
||||
entries.size > PROJECT_FAVICON_CACHE_MAX_ENTRIES ||
|
||||
bytes > PROJECT_FAVICON_CACHE_MAX_BYTES
|
||||
) {
|
||||
const oldest = entries.entries().next().value;
|
||||
if (!oldest) break;
|
||||
bytes -= oldest[1].dataUrl.length;
|
||||
remove(oldest[0]);
|
||||
}
|
||||
};
|
||||
|
||||
const hydrate = () =>
|
||||
(hydration ??= (async () => {
|
||||
try {
|
||||
for (const record of await input.storage.list()) {
|
||||
const entry = decodeEntry(record);
|
||||
if (Option.isSome(entry)) entries.set(keyFor(entry.value), entry.value);
|
||||
}
|
||||
trim();
|
||||
} catch {
|
||||
// A missing, corrupt, or unavailable cache must not prevent startup.
|
||||
}
|
||||
})());
|
||||
|
||||
const peek = (target: ProjectFaviconTarget) => entries.get(keyFor(target))?.dataUrl ?? null;
|
||||
|
||||
const resolve = async (
|
||||
target: ProjectFaviconTarget,
|
||||
url: string | null,
|
||||
signal: AbortSignal,
|
||||
): Promise<string | null> => {
|
||||
await clearing;
|
||||
const startGeneration = generation;
|
||||
const startRevision = environmentRevisions.get(target.environmentId) ?? 0;
|
||||
await hydrate();
|
||||
if (signal.aborted || url === null) return peek(target);
|
||||
const key = keyFor(target);
|
||||
if (isProjectFaviconFallbackUrl(url)) {
|
||||
remove(key);
|
||||
return null;
|
||||
}
|
||||
const revision = getProjectFaviconCacheKey(target.environmentId, target.cwd, url);
|
||||
const cached = entries.get(key);
|
||||
if (cached) {
|
||||
entries.delete(key);
|
||||
entries.set(key, cached);
|
||||
if (cached.revision === revision) return cached.dataUrl;
|
||||
}
|
||||
try {
|
||||
const dataUrl = await input.load(url, signal);
|
||||
if (
|
||||
signal.aborted ||
|
||||
startGeneration !== generation ||
|
||||
startRevision !== (environmentRevisions.get(target.environmentId) ?? 0)
|
||||
) {
|
||||
return peek(target);
|
||||
}
|
||||
if (isImageDataUrl(dataUrl)) {
|
||||
const entry = {
|
||||
environmentId: target.environmentId,
|
||||
cwd: target.cwd,
|
||||
faviconPath: target.faviconPath || null,
|
||||
revision,
|
||||
dataUrl,
|
||||
};
|
||||
entries.set(key, entry);
|
||||
persist(() => input.storage.put(key, entry));
|
||||
trim();
|
||||
return dataUrl;
|
||||
}
|
||||
} catch {
|
||||
// An outage or failed decode leaves the last successful image visible.
|
||||
}
|
||||
return peek(target) ?? url;
|
||||
};
|
||||
|
||||
const flush = async () => {
|
||||
await Promise.all(pending);
|
||||
};
|
||||
|
||||
// A download that started before the clear sees the revision change and is discarded;
|
||||
// one that starts during the clear waits for it, so it cannot repopulate storage.
|
||||
const clear = async (environmentId?: EnvironmentId) => {
|
||||
if (environmentId === undefined) generation += 1;
|
||||
else
|
||||
environmentRevisions.set(environmentId, (environmentRevisions.get(environmentId) ?? 0) + 1);
|
||||
const previous = clearing;
|
||||
const task = (async () => {
|
||||
await previous;
|
||||
await hydrate();
|
||||
for (const [key, entry] of entries) {
|
||||
if (environmentId === undefined || entry.environmentId === environmentId) remove(key);
|
||||
}
|
||||
await flush();
|
||||
})().finally(() => {
|
||||
if (clearing === task) clearing = undefined;
|
||||
});
|
||||
clearing = task;
|
||||
await task;
|
||||
};
|
||||
|
||||
return {
|
||||
hydrate,
|
||||
peek,
|
||||
resolve,
|
||||
clearEnvironment: (environmentId: EnvironmentId) => clear(environmentId),
|
||||
clearAll: () => clear(),
|
||||
flush,
|
||||
};
|
||||
}
|
||||
|
||||
export type ProjectFaviconCache = ReturnType<typeof createProjectFaviconCache>;
|
||||
@@ -1,11 +1,15 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
import { createProjectFaviconCache } from "../projectFaviconCache.ts";
|
||||
import {
|
||||
createAssetEnvironmentAtoms,
|
||||
createProjectFaviconUrlAtomFamily,
|
||||
InvalidAssetCollectionKeyError,
|
||||
parseAssetCollectionKey,
|
||||
} from "./assets.ts";
|
||||
@@ -118,3 +122,160 @@ describe("createAssetEnvironmentAtoms", () => {
|
||||
).not.toBe(assets.createUrls({ environmentId, resources }));
|
||||
});
|
||||
});
|
||||
|
||||
describe("project favicon URL cache", () => {
|
||||
it("renders a persisted thumbnail immediately in a fresh registry and refreshes it remotely", async () => {
|
||||
const image = "data:image/png;base64,aWNvbg==";
|
||||
const replacement = "data:image/png;base64,bmV3";
|
||||
const records = new Map<string, unknown>();
|
||||
const storage = {
|
||||
list: async () => [...records.values()],
|
||||
put: async (key: string, entry: unknown) => {
|
||||
records.set(key, entry);
|
||||
},
|
||||
remove: async (key: string) => {
|
||||
records.delete(key);
|
||||
},
|
||||
};
|
||||
const target = { environmentId: EnvironmentId.make("remote"), cwd: "/workspace" };
|
||||
const previousCache = createProjectFaviconCache({ storage, load: async () => image });
|
||||
await previousCache.resolve(
|
||||
target,
|
||||
"https://remote.test/api/assets/old/v1-icon.png",
|
||||
new AbortController().signal,
|
||||
);
|
||||
await previousCache.flush();
|
||||
const cache = createProjectFaviconCache({ storage, load: async () => replacement });
|
||||
await cache.hydrate();
|
||||
const registry = AtomRegistry.make();
|
||||
const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
|
||||
AsyncResult.initial(),
|
||||
);
|
||||
const connection = Atom.make<Option.Option<{ httpBaseUrl: string }>>(Option.none());
|
||||
const favicon = createProjectFaviconUrlAtomFamily({
|
||||
createUrl: () => result,
|
||||
preparedConnection: () => connection,
|
||||
imageCache: cache,
|
||||
})(target);
|
||||
const unmount = registry.mount(favicon);
|
||||
try {
|
||||
expect(registry.get(favicon)).toBe(image);
|
||||
let unsubscribe = () => {};
|
||||
const refreshed = new Promise<void>((resolve) => {
|
||||
unsubscribe = registry.subscribe(favicon, (value) => {
|
||||
if (value === replacement) resolve();
|
||||
});
|
||||
});
|
||||
registry.set(connection, Option.some({ httpBaseUrl: "https://remote.test" }));
|
||||
registry.set(
|
||||
result,
|
||||
AsyncResult.success({
|
||||
relativeUrl: "/api/assets/new/v2-icon.png",
|
||||
expiresAt: 4_000_000_000_000,
|
||||
}),
|
||||
);
|
||||
expect(registry.get(favicon)).toBe(image);
|
||||
await refreshed;
|
||||
unsubscribe();
|
||||
expect(registry.get(favicon)).toBe(replacement);
|
||||
registry.set(connection, Option.none());
|
||||
registry.set(result, AsyncResult.failure(Cause.die("offline")));
|
||||
expect(registry.get(favicon)).toBe(replacement);
|
||||
} finally {
|
||||
unmount();
|
||||
registry.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains icons across outages and remounts, then accepts refreshed and missing icons", () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
|
||||
AsyncResult.initial(),
|
||||
);
|
||||
const connection = Atom.make(Option.some({ httpBaseUrl: "https://remote.test" }));
|
||||
const favicon = createProjectFaviconUrlAtomFamily({
|
||||
createUrl: () => result,
|
||||
preparedConnection: () => connection,
|
||||
})({ environmentId: EnvironmentId.make("remote"), cwd: "/workspace" });
|
||||
let unmount = registry.mount(favicon);
|
||||
try {
|
||||
expect(registry.get(favicon)).toBeNull();
|
||||
registry.set(
|
||||
result,
|
||||
AsyncResult.success({
|
||||
expiresAt: 4_000_000_000_000,
|
||||
relativeUrl: "/api/assets/token-a/icon.svg",
|
||||
}),
|
||||
);
|
||||
expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
|
||||
|
||||
registry.set(connection, Option.none());
|
||||
registry.set(result, AsyncResult.failure(Cause.die("disconnected")));
|
||||
expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
|
||||
unmount();
|
||||
unmount = registry.mount(favicon);
|
||||
expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
|
||||
|
||||
registry.set(result, AsyncResult.initial());
|
||||
registry.set(connection, Option.some({ httpBaseUrl: "https://reconnected.test" }));
|
||||
expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
|
||||
registry.set(
|
||||
result,
|
||||
AsyncResult.success({
|
||||
expiresAt: 4_000_000_000_000,
|
||||
relativeUrl: "/api/assets/token-b/icon.svg",
|
||||
}),
|
||||
);
|
||||
expect(registry.get(favicon)).toBe("https://reconnected.test/api/assets/token-b/icon.svg");
|
||||
|
||||
registry.set(
|
||||
result,
|
||||
AsyncResult.success({
|
||||
expiresAt: 4_000_000_000_000,
|
||||
relativeUrl: "/api/assets/token-c/project-favicon-missing",
|
||||
}),
|
||||
);
|
||||
expect(registry.get(favicon)).toBe(
|
||||
"https://reconnected.test/api/assets/token-c/project-favicon-missing",
|
||||
);
|
||||
registry.set(connection, Option.none());
|
||||
expect(registry.get(favicon)).toBe(
|
||||
"https://reconnected.test/api/assets/token-c/project-favicon-missing",
|
||||
);
|
||||
} finally {
|
||||
unmount();
|
||||
registry.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not reuse another environment, workspace, or selected icon's cached URL", () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
|
||||
AsyncResult.success({
|
||||
expiresAt: 4_000_000_000_000,
|
||||
relativeUrl: "/api/assets/token/icon.svg",
|
||||
}),
|
||||
);
|
||||
const favicon = createProjectFaviconUrlAtomFamily({
|
||||
createUrl: () => result,
|
||||
preparedConnection: () => Atom.make(Option.some({ httpBaseUrl: "https://remote.test" })),
|
||||
});
|
||||
const target = { environmentId: EnvironmentId.make("remote"), cwd: "/workspace" };
|
||||
const unmount = registry.mount(favicon(target));
|
||||
try {
|
||||
expect(registry.get(favicon(target))).toBe("https://remote.test/api/assets/token/icon.svg");
|
||||
registry.set(result, AsyncResult.failure(Cause.die("disconnected")));
|
||||
expect(
|
||||
registry.get(favicon({ ...target, environmentId: EnvironmentId.make("other") })),
|
||||
).toBeNull();
|
||||
expect(registry.get(favicon({ ...target, cwd: "/other" }))).toBeNull();
|
||||
expect(registry.get(favicon({ ...target, faviconPath: "brand.svg" }))).toBeNull();
|
||||
expect(registry.get(favicon({ ...target, faviconPath: null }))).toBe(
|
||||
"https://remote.test/api/assets/token/icon.svg",
|
||||
);
|
||||
} finally {
|
||||
unmount();
|
||||
registry.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -5,10 +5,17 @@ import {
|
||||
EnvironmentId,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getProjectFaviconResourceKey,
|
||||
isProjectFaviconFallbackUrl,
|
||||
} from "@t3tools/shared/projectFavicon";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
import type { ProjectFaviconCache, ProjectFaviconTarget } from "../projectFaviconCache.ts";
|
||||
import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
|
||||
|
||||
const ASSET_URL_REFRESH_INTERVAL_MS = 30 * 60_000;
|
||||
@@ -118,3 +125,53 @@ export function createAssetEnvironmentAtoms<R, E>(
|
||||
}) => createUrlsFamily(JSON.stringify([target.environmentId, target.resources])),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps project icons visible while their environment reconnects. Each resource
|
||||
* owns its last resolved URL, including a confirmed missing-icon response.
|
||||
*/
|
||||
export function createProjectFaviconUrlAtomFamily(input: {
|
||||
readonly imageCache?: ProjectFaviconCache;
|
||||
readonly createUrl: (target: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly input: { readonly resource: AssetResource };
|
||||
}) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>;
|
||||
readonly preparedConnection: (
|
||||
environmentId: EnvironmentId,
|
||||
) => Atom.Atom<Option.Option<{ readonly httpBaseUrl: string }>>;
|
||||
}) {
|
||||
const decodeKey = Schema.decodeUnknownSync(
|
||||
Schema.Tuple([EnvironmentId, Schema.String, Schema.NullOr(Schema.String)]),
|
||||
);
|
||||
const family = Atom.family((key: string) => {
|
||||
const [environmentId, cwd, path] = decodeKey(JSON.parse(key));
|
||||
const resource = { _tag: "project-favicon" as const, cwd, ...(path ? { path } : {}) };
|
||||
const request = input.createUrl({ environmentId, input: { resource } });
|
||||
const resolvedUrl = Atom.make((get): string | null => {
|
||||
const result = get(request);
|
||||
const connection = get(input.preparedConnection(environmentId));
|
||||
const state = assetUrlStateFromResult(
|
||||
result,
|
||||
Option.isSome(connection) ? connection.value.httpBaseUrl : null,
|
||||
);
|
||||
return state._tag === "Success" ? state.url : Option.getOrNull(get.self<string | null>());
|
||||
}).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
|
||||
const cache = input.imageCache;
|
||||
if (!cache) return resolvedUrl;
|
||||
|
||||
const target = { environmentId, cwd, faviconPath: path };
|
||||
const image = Atom.make((get) => {
|
||||
get(request);
|
||||
const url = get(resolvedUrl);
|
||||
return Effect.promise((signal) => cache.resolve(target, url, signal));
|
||||
}).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
|
||||
|
||||
return Atom.make((get): string | null => {
|
||||
const result = get(image);
|
||||
if (isProjectFaviconFallbackUrl(get(resolvedUrl))) return null;
|
||||
return Option.getOrElse(AsyncResult.value(result), () => cache.peek(target));
|
||||
}).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
|
||||
});
|
||||
return (target: ProjectFaviconTarget) =>
|
||||
family(getProjectFaviconResourceKey(target.environmentId, target.cwd, target.faviconPath));
|
||||
}
|
||||
Reference in new issue
Block a user