fix: cache project favicons across web and mobile (#4767)
This commit is contained in:
1 parent
4ba4871af7
commit
1d77cec991
9 files changed
+552
-48
No files matched your search
@@ -1,14 +1,21 @@
|
||||
import { SymbolView } from "./AppSymbol";
|
||||
import { Image } from "expo-image";
|
||||
import { useState } from "react";
|
||||
import { useLayoutEffect, useMemo, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
|
||||
import {
|
||||
getProjectFaviconCacheKey,
|
||||
isProjectFaviconFallbackUrl,
|
||||
} from "@t3tools/shared/projectFavicon";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import { useAssetUrl } from "../state/assets";
|
||||
|
||||
/* ─── Favicon cache (matches web pattern) ────────────────────────────── */
|
||||
const loadedFaviconUrls = new Set<string>();
|
||||
import {
|
||||
beginProjectFaviconRequest,
|
||||
createProjectFaviconRequest,
|
||||
hasLoadedProjectFavicon,
|
||||
markProjectFaviconFailed,
|
||||
markProjectFaviconLoaded,
|
||||
} from "./projectFaviconCache";
|
||||
|
||||
/* ─── Component ──────────────────────────────────────────────────────── */
|
||||
export function ProjectFavicon(props: {
|
||||
@@ -26,10 +33,15 @@ export function ProjectFavicon(props: {
|
||||
: { _tag: "project-favicon", cwd: props.workspaceRoot },
|
||||
);
|
||||
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
|
||||
const cacheKey =
|
||||
renderableFaviconUrl && props.workspaceRoot
|
||||
? getProjectFaviconCacheKey(props.environmentId, props.workspaceRoot, renderableFaviconUrl)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<ProjectFaviconImage
|
||||
key={faviconUrl}
|
||||
key={cacheKey}
|
||||
cacheKey={cacheKey}
|
||||
faviconUrl={renderableFaviconUrl}
|
||||
open={props.open}
|
||||
projectTitle={props.projectTitle}
|
||||
@@ -39,18 +51,32 @@ export function ProjectFavicon(props: {
|
||||
}
|
||||
|
||||
function ProjectFaviconImage(props: {
|
||||
readonly cacheKey: string | null;
|
||||
readonly faviconUrl: string | null;
|
||||
readonly open?: boolean;
|
||||
readonly projectTitle: string;
|
||||
readonly size: number;
|
||||
}) {
|
||||
const iconMuted = useThemeColor("--color-icon-subtle");
|
||||
const faviconRequest = useMemo(
|
||||
() => createProjectFaviconRequest(props.cacheKey, props.faviconUrl),
|
||||
[props.cacheKey, props.faviconUrl],
|
||||
);
|
||||
const [activeFaviconRequest, setActiveFaviconRequest] = useState<typeof faviconRequest>(null);
|
||||
useLayoutEffect(() => {
|
||||
if (faviconRequest === null) return;
|
||||
|
||||
const endRequest = beginProjectFaviconRequest(faviconRequest);
|
||||
setActiveFaviconRequest(faviconRequest);
|
||||
return endRequest;
|
||||
}, [faviconRequest]);
|
||||
|
||||
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
|
||||
props.faviconUrl && loadedFaviconUrls.has(props.faviconUrl) ? "loaded" : "loading",
|
||||
hasLoadedProjectFavicon(props.cacheKey) ? "loaded" : "loading",
|
||||
);
|
||||
|
||||
const showImage = props.faviconUrl !== null && status === "loaded";
|
||||
const requestIsActive = faviconRequest !== null && activeFaviconRequest === faviconRequest;
|
||||
const showImage = requestIsActive && status === "loaded";
|
||||
|
||||
return (
|
||||
<View
|
||||
@@ -72,11 +98,15 @@ function ProjectFaviconImage(props: {
|
||||
) : null}
|
||||
|
||||
{/* Favicon image (hidden until loaded) */}
|
||||
{props.faviconUrl ? (
|
||||
{requestIsActive ? (
|
||||
<Image
|
||||
key={faviconRequest.faviconUrl}
|
||||
source={{
|
||||
uri: props.faviconUrl,
|
||||
uri: faviconRequest.faviconUrl,
|
||||
cacheKey: faviconRequest.cacheKey,
|
||||
}}
|
||||
cachePolicy="memory-disk"
|
||||
recyclingKey={faviconRequest.cacheKey}
|
||||
accessibilityLabel={`${props.projectTitle} favicon`}
|
||||
style={{
|
||||
width: props.size,
|
||||
@@ -86,10 +116,13 @@ function ProjectFaviconImage(props: {
|
||||
}}
|
||||
contentFit="contain"
|
||||
onLoad={() => {
|
||||
if (props.faviconUrl) loadedFaviconUrls.add(props.faviconUrl);
|
||||
if (!markProjectFaviconLoaded(faviconRequest)) return;
|
||||
setStatus("loaded");
|
||||
}}
|
||||
onError={() => setStatus("error")}
|
||||
onError={() => {
|
||||
if (!markProjectFaviconFailed(faviconRequest)) return;
|
||||
setStatus("error");
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
beginProjectFaviconRequest,
|
||||
createProjectFaviconRequest,
|
||||
hasLoadedProjectFavicon,
|
||||
markProjectFaviconFailed,
|
||||
markProjectFaviconLoaded,
|
||||
} from "./projectFaviconCache";
|
||||
|
||||
describe("project favicon cache", () => {
|
||||
it("ignores callbacks from a superseded URL", () => {
|
||||
const cacheKey = "environment-1:/workspace:v1-favicon.svg";
|
||||
const expiredUrl = "https://environment.example/api/assets/expired/v1-favicon.svg";
|
||||
const refreshedUrl = "https://environment.example/api/assets/refreshed/v1-favicon.svg";
|
||||
|
||||
const expiredRequest = createProjectFaviconRequest(cacheKey, expiredUrl);
|
||||
const endExpiredRequest = beginProjectFaviconRequest(expiredRequest);
|
||||
markProjectFaviconLoaded(expiredRequest);
|
||||
const refreshedRequest = createProjectFaviconRequest(cacheKey, refreshedUrl);
|
||||
const endRefreshedRequest = beginProjectFaviconRequest(refreshedRequest);
|
||||
|
||||
expect(markProjectFaviconLoaded(expiredRequest)).toBe(false);
|
||||
expect(markProjectFaviconFailed(expiredRequest)).toBe(false);
|
||||
expect(hasLoadedProjectFavicon(cacheKey)).toBe(true);
|
||||
expect(markProjectFaviconFailed(refreshedRequest)).toBe(true);
|
||||
expect(hasLoadedProjectFavicon(cacheKey)).toBe(false);
|
||||
|
||||
endRefreshedRequest();
|
||||
endExpiredRequest();
|
||||
});
|
||||
|
||||
it("evicts the URL that actually failed", () => {
|
||||
const cacheKey = "environment-1:/workspace:v2-favicon.svg";
|
||||
const faviconUrl = "https://environment.example/api/assets/current/v2-favicon.svg";
|
||||
const request = createProjectFaviconRequest(cacheKey, faviconUrl);
|
||||
const endRequest = beginProjectFaviconRequest(request);
|
||||
|
||||
markProjectFaviconLoaded(request);
|
||||
|
||||
expect(markProjectFaviconFailed(request)).toBe(true);
|
||||
expect(hasLoadedProjectFavicon(cacheKey)).toBe(false);
|
||||
|
||||
endRequest();
|
||||
});
|
||||
|
||||
it("does not supersede a request until the next request begins", () => {
|
||||
const cacheKey = "environment-1:/workspace:v3-favicon.svg";
|
||||
const committedUrl = "https://environment.example/api/assets/current/v3-favicon.svg";
|
||||
const abandonedUrl = "https://environment.example/api/assets/abandoned/v3-favicon.svg";
|
||||
const committedRequest = createProjectFaviconRequest(cacheKey, committedUrl);
|
||||
const endCommittedRequest = beginProjectFaviconRequest(committedRequest);
|
||||
|
||||
createProjectFaviconRequest(cacheKey, abandonedUrl);
|
||||
|
||||
expect(markProjectFaviconLoaded(committedRequest)).toBe(true);
|
||||
expect(hasLoadedProjectFavicon(cacheKey)).toBe(true);
|
||||
|
||||
endCommittedRequest();
|
||||
});
|
||||
|
||||
it("requires a cache key before creating a URL-bearing request", () => {
|
||||
const firstUrl = "https://environment.example/api/assets/first/favicon.svg";
|
||||
const secondUrl = "https://environment.example/api/assets/second/favicon.svg";
|
||||
|
||||
expect(createProjectFaviconRequest(null, firstUrl)).toBeNull();
|
||||
expect(createProjectFaviconRequest(null, secondUrl)).toBeNull();
|
||||
});
|
||||
|
||||
it("restores the remaining active URL when a newer request ends", () => {
|
||||
const cacheKey = "environment-1:/workspace:v4-favicon.svg";
|
||||
const firstRequest = createProjectFaviconRequest(
|
||||
cacheKey,
|
||||
"https://environment.example/api/assets/first/v4-favicon.svg",
|
||||
);
|
||||
const secondRequest = createProjectFaviconRequest(
|
||||
cacheKey,
|
||||
"https://environment.example/api/assets/second/v4-favicon.svg",
|
||||
);
|
||||
const endFirstRequest = beginProjectFaviconRequest(firstRequest);
|
||||
const endSecondRequest = beginProjectFaviconRequest(secondRequest);
|
||||
|
||||
expect(markProjectFaviconLoaded(firstRequest)).toBe(false);
|
||||
endSecondRequest();
|
||||
expect(markProjectFaviconLoaded(firstRequest)).toBe(true);
|
||||
endFirstRequest();
|
||||
expect(markProjectFaviconLoaded(firstRequest)).toBe(false);
|
||||
});
|
||||
|
||||
it("bounds remembered loaded revisions", () => {
|
||||
const firstCacheKey = "environment-1:/workspace:revision-0";
|
||||
let lastCacheKey = firstCacheKey;
|
||||
|
||||
for (let revision = 0; revision < 300; revision++) {
|
||||
lastCacheKey = `environment-1:/workspace:revision-${revision}`;
|
||||
const request = createProjectFaviconRequest(
|
||||
lastCacheKey,
|
||||
`https://environment.example/api/assets/revision-${revision}/favicon.svg`,
|
||||
);
|
||||
const endRequest = beginProjectFaviconRequest(request);
|
||||
markProjectFaviconLoaded(request);
|
||||
endRequest();
|
||||
}
|
||||
|
||||
expect(hasLoadedProjectFavicon(firstCacheKey)).toBe(false);
|
||||
expect(hasLoadedProjectFavicon(lastCacheKey)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
export interface ProjectFaviconRequest {
|
||||
readonly cacheKey: string;
|
||||
readonly faviconUrl: string;
|
||||
}
|
||||
|
||||
interface ActiveFaviconRequests {
|
||||
readonly urls: Map<string, number>;
|
||||
currentUrl: string;
|
||||
}
|
||||
|
||||
const MAX_LOADED_FAVICONS = 256;
|
||||
const activeFaviconRequests = new Map<string, ActiveFaviconRequests>();
|
||||
const loadedFaviconKeys = new Map<string, true>();
|
||||
|
||||
export function createProjectFaviconRequest(
|
||||
cacheKey: string,
|
||||
faviconUrl: string,
|
||||
): ProjectFaviconRequest;
|
||||
export function createProjectFaviconRequest(
|
||||
cacheKey: string | null,
|
||||
faviconUrl: string | null,
|
||||
): ProjectFaviconRequest | null;
|
||||
export function createProjectFaviconRequest(cacheKey: string | null, faviconUrl: string | null) {
|
||||
if (!cacheKey || !faviconUrl) return null;
|
||||
return { cacheKey, faviconUrl };
|
||||
}
|
||||
|
||||
export function beginProjectFaviconRequest(request: ProjectFaviconRequest) {
|
||||
let activeRequests = activeFaviconRequests.get(request.cacheKey);
|
||||
if (!activeRequests) {
|
||||
activeRequests = { currentUrl: request.faviconUrl, urls: new Map() };
|
||||
activeFaviconRequests.set(request.cacheKey, activeRequests);
|
||||
}
|
||||
|
||||
const activeCount = activeRequests.urls.get(request.faviconUrl) ?? 0;
|
||||
activeRequests.urls.delete(request.faviconUrl);
|
||||
activeRequests.urls.set(request.faviconUrl, activeCount + 1);
|
||||
activeRequests.currentUrl = request.faviconUrl;
|
||||
|
||||
let ended = false;
|
||||
return () => {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
|
||||
const remainingCount = (activeRequests.urls.get(request.faviconUrl) ?? 1) - 1;
|
||||
if (remainingCount > 0) {
|
||||
activeRequests.urls.set(request.faviconUrl, remainingCount);
|
||||
return;
|
||||
}
|
||||
|
||||
activeRequests.urls.delete(request.faviconUrl);
|
||||
if (activeRequests.urls.size === 0) {
|
||||
if (activeFaviconRequests.get(request.cacheKey) === activeRequests) {
|
||||
activeFaviconRequests.delete(request.cacheKey);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (activeRequests.currentUrl === request.faviconUrl) {
|
||||
activeRequests.currentUrl = Array.from(activeRequests.urls.keys()).at(-1)!;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function hasLoadedProjectFavicon(cacheKey: string | null) {
|
||||
return cacheKey !== null && loadedFaviconKeys.has(cacheKey);
|
||||
}
|
||||
|
||||
function isCurrentProjectFaviconRequest(request: ProjectFaviconRequest) {
|
||||
return activeFaviconRequests.get(request.cacheKey)?.currentUrl === request.faviconUrl;
|
||||
}
|
||||
|
||||
function rememberLoadedProjectFavicon(cacheKey: string) {
|
||||
loadedFaviconKeys.delete(cacheKey);
|
||||
loadedFaviconKeys.set(cacheKey, true);
|
||||
|
||||
if (loadedFaviconKeys.size > MAX_LOADED_FAVICONS) {
|
||||
loadedFaviconKeys.delete(loadedFaviconKeys.keys().next().value!);
|
||||
}
|
||||
}
|
||||
|
||||
export function markProjectFaviconLoaded(request: ProjectFaviconRequest) {
|
||||
if (!isCurrentProjectFaviconRequest(request)) return false;
|
||||
|
||||
rememberLoadedProjectFavicon(request.cacheKey);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function markProjectFaviconFailed(request: ProjectFaviconRequest) {
|
||||
if (!isCurrentProjectFaviconRequest(request)) return false;
|
||||
|
||||
loadedFaviconKeys.delete(request.cacheKey);
|
||||
return true;
|
||||
}
|
||||
@@ -2,11 +2,13 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
@@ -214,12 +216,21 @@ describe("AssetAccess", () => {
|
||||
prefix: "t3-asset-favicon-",
|
||||
});
|
||||
const faviconPath = path.join(root, "favicon.svg");
|
||||
yield* fileSystem.writeFileString(faviconPath, "<svg />");
|
||||
const initialFavicon = "<svg>a</svg>";
|
||||
const updatedFavicon = "<svg>b</svg>";
|
||||
expect(updatedFavicon).toHaveLength(initialFavicon.length);
|
||||
yield* fileSystem.writeFileString(faviconPath, initialFavicon);
|
||||
const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
|
||||
|
||||
const faviconResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
|
||||
expect(
|
||||
yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
}),
|
||||
).toEqual(faviconResult);
|
||||
const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const faviconSeparatorIndex = faviconSuffix.indexOf("/");
|
||||
expect(
|
||||
@@ -229,6 +240,14 @@ describe("AssetAccess", () => {
|
||||
),
|
||||
).toEqual({ kind: "file", path: canonicalFaviconPath });
|
||||
|
||||
yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
|
||||
const updatedFaviconResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(
|
||||
updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
|
||||
).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
|
||||
|
||||
yield* fileSystem.remove(faviconPath);
|
||||
const fallbackResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
@@ -245,6 +264,31 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("buckets project favicon expiry after content hashing", () =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-expiry-",
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg />");
|
||||
|
||||
const bucketMs = 30 * 60 * 1000;
|
||||
yield* TestClock.setTime(bucketMs - 1);
|
||||
const crossingCrypto = Crypto.make({
|
||||
randomBytes: (size) => new Uint8Array(size),
|
||||
digest: (algorithm, data) =>
|
||||
TestClock.adjust("2 millis").pipe(Effect.andThen(crypto.digest(algorithm, data))),
|
||||
});
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
}).pipe(Effect.provideService(Crypto.Crypto, crossingCrypto));
|
||||
|
||||
expect(result.expiresAt).toBe(3 * bucketMs);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("preserves structured project favicon resolution causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -21,7 +21,9 @@ import {
|
||||
} from "@t3tools/shared/filePreview";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -44,6 +46,8 @@ export const ASSET_ROUTE_PREFIX = "/api/assets";
|
||||
|
||||
const SIGNING_SECRET_NAME = "asset-access-signing-key";
|
||||
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
|
||||
const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
|
||||
const PROJECT_FAVICON_VERSION_PREFIX = "v";
|
||||
const PREVIEW_ASSET_EXTENSIONS = new Set([
|
||||
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
|
||||
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
|
||||
@@ -169,7 +173,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
const expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
|
||||
let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
|
||||
let claims: AssetClaims;
|
||||
let fileName: string;
|
||||
|
||||
@@ -293,18 +297,18 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
),
|
||||
);
|
||||
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
|
||||
if (
|
||||
relativePath &&
|
||||
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
))
|
||||
) {
|
||||
const canonicalFaviconPath = relativePath
|
||||
? yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
if (relativePath && !canonicalFaviconPath) {
|
||||
return yield* new AssetProjectFaviconNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
@@ -324,7 +328,31 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
relativePath,
|
||||
expiresAt,
|
||||
};
|
||||
fileName = relativePath ? path.basename(relativePath) : PROJECT_FAVICON_FALLBACK_MARKER;
|
||||
if (relativePath && canonicalFaviconPath) {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const revision = yield* crypto.digest("SHA-256", faviconBytes).pipe(
|
||||
Effect.map(Encoding.encodeHex),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconInspectionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(relativePath)}`;
|
||||
} else {
|
||||
fileName = PROJECT_FAVICON_FALLBACK_MARKER;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -339,6 +367,13 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (claims.kind === "project-favicon") {
|
||||
const issuedAt = yield* Clock.currentTimeMillis;
|
||||
expiresAt =
|
||||
(Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
|
||||
PROJECT_FAVICON_TOKEN_BUCKET_MS;
|
||||
claims = { ...claims, expiresAt };
|
||||
}
|
||||
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
|
||||
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { ComponentType, Dispatch, ReactElement, SetStateAction } from "react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
faviconUrl: "https://environment.test/api/assets/token-a/v1-20-favicon.svg",
|
||||
}));
|
||||
|
||||
const hooks = vi.hoisted(() => {
|
||||
let cursor = 0;
|
||||
let slots: unknown[] = [];
|
||||
const nextIndex = () => cursor++;
|
||||
|
||||
return {
|
||||
beginRender() {
|
||||
cursor = 0;
|
||||
},
|
||||
reset() {
|
||||
cursor = 0;
|
||||
slots = [];
|
||||
},
|
||||
useMemoCache(size: number): unknown[] {
|
||||
const index = nextIndex();
|
||||
if (!slots[index]) {
|
||||
slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));
|
||||
}
|
||||
return slots[index] as unknown[];
|
||||
},
|
||||
useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
|
||||
const index = nextIndex();
|
||||
if (index >= slots.length) {
|
||||
slots[index] =
|
||||
typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
|
||||
}
|
||||
const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {
|
||||
const previous = slots[index] as T;
|
||||
slots[index] =
|
||||
typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;
|
||||
};
|
||||
return [slots[index] as T, setValue];
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react")>();
|
||||
return {
|
||||
...actual,
|
||||
useState: hooks.useState,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react/compiler-runtime", () => ({ c: hooks.useMemoCache }));
|
||||
vi.mock("../assets/assetUrls", () => ({
|
||||
useAssetUrl: () => testState.faviconUrl,
|
||||
}));
|
||||
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
|
||||
type ProjectFaviconImageProps = {
|
||||
readonly cacheKey: string;
|
||||
readonly src: string;
|
||||
readonly className?: string | undefined;
|
||||
readonly fallbackIcon: ComponentType<{ className?: string }>;
|
||||
};
|
||||
|
||||
type ImageElement = ReactElement<{
|
||||
readonly src: string;
|
||||
readonly onLoad?: () => void;
|
||||
readonly onError?: () => void;
|
||||
}>;
|
||||
|
||||
type ProjectFaviconImageElement = ReactElement<{
|
||||
readonly children: [ReactElement | null, ImageElement | null, ImageElement | null];
|
||||
}>;
|
||||
|
||||
function resolveImageComponent(): {
|
||||
readonly Component: (props: ProjectFaviconImageProps) => ProjectFaviconImageElement;
|
||||
readonly props: ProjectFaviconImageProps;
|
||||
} {
|
||||
hooks.beginRender();
|
||||
const element = ProjectFavicon({
|
||||
environmentId: "environment-test" as EnvironmentId,
|
||||
cwd: "/workspace-test",
|
||||
}) as ReactElement<ProjectFaviconImageProps>;
|
||||
hooks.reset();
|
||||
|
||||
return {
|
||||
Component: element.type as (props: ProjectFaviconImageProps) => ProjectFaviconImageElement,
|
||||
props: element.props,
|
||||
};
|
||||
}
|
||||
|
||||
function renderImage(
|
||||
Component: (props: ProjectFaviconImageProps) => ProjectFaviconImageElement,
|
||||
props: ProjectFaviconImageProps,
|
||||
): ProjectFaviconImageElement {
|
||||
hooks.beginRender();
|
||||
return Component(props);
|
||||
}
|
||||
|
||||
describe("ProjectFavicon", () => {
|
||||
beforeEach(() => {
|
||||
hooks.reset();
|
||||
});
|
||||
|
||||
it("falls back when the displayed favicon fails without discarding a valid older image early", () => {
|
||||
const { Component, props } = resolveImageComponent();
|
||||
const initialLoadingImage = renderImage(Component, props).props.children[2];
|
||||
initialLoadingImage?.props.onLoad?.();
|
||||
|
||||
const refreshedProps = {
|
||||
...props,
|
||||
src: "https://environment.test/api/assets/token-b/v1-20-favicon.svg",
|
||||
};
|
||||
const refreshing = renderImage(Component, refreshedProps).props.children;
|
||||
expect(refreshing[1]?.props.src).toBe(props.src);
|
||||
refreshing[2]?.props.onError?.();
|
||||
|
||||
const afterRefreshError = renderImage(Component, refreshedProps).props.children;
|
||||
expect(afterRefreshError[1]?.props.src).toBe(props.src);
|
||||
afterRefreshError[1]?.props.onError?.();
|
||||
|
||||
const afterDisplayedError = renderImage(Component, refreshedProps).props.children;
|
||||
expect(afterDisplayedError[0]).not.toBeNull();
|
||||
expect(afterDisplayedError[1]).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,15 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
|
||||
import {
|
||||
getProjectFaviconCacheKey,
|
||||
isProjectFaviconFallbackUrl,
|
||||
} from "@t3tools/shared/projectFavicon";
|
||||
import { FolderIcon } from "lucide-react";
|
||||
import type { ComponentType } from "react";
|
||||
import { useState } from "react";
|
||||
import { useAssetUrl } from "../assets/assetUrls";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const loadedProjectFaviconSrcs = new Set<string>();
|
||||
const loadedProjectFaviconSrcs = new Map<string, string>();
|
||||
|
||||
export function ProjectFavicon(input: {
|
||||
environmentId: EnvironmentId;
|
||||
@@ -24,9 +27,12 @@ export function ProjectFavicon(input: {
|
||||
return <ProjectFaviconFallback className={input.className} icon={FallbackIcon} />;
|
||||
}
|
||||
|
||||
const cacheKey = getProjectFaviconCacheKey(input.environmentId, input.cwd, src);
|
||||
|
||||
return (
|
||||
<ProjectFaviconImage
|
||||
key={src}
|
||||
key={cacheKey}
|
||||
cacheKey={cacheKey}
|
||||
src={src}
|
||||
className={input.className}
|
||||
fallbackIcon={FallbackIcon}
|
||||
@@ -45,37 +51,52 @@ function ProjectFaviconFallback({
|
||||
}
|
||||
|
||||
function ProjectFaviconImage({
|
||||
cacheKey,
|
||||
src,
|
||||
className,
|
||||
fallbackIcon: FallbackIcon,
|
||||
}: {
|
||||
readonly cacheKey: string;
|
||||
readonly src: string;
|
||||
readonly className?: string | undefined;
|
||||
readonly fallbackIcon: ComponentType<{ className?: string }>;
|
||||
}) {
|
||||
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
|
||||
loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
|
||||
const [displayedSrc, setDisplayedSrc] = useState<string | null>(
|
||||
() => loadedProjectFaviconSrcs.get(cacheKey) ?? null,
|
||||
);
|
||||
const isLoading = displayedSrc !== src;
|
||||
const handleLoadError = (failedSrc: string) => {
|
||||
if (loadedProjectFaviconSrcs.get(cacheKey) === failedSrc) {
|
||||
loadedProjectFaviconSrcs.delete(cacheKey);
|
||||
}
|
||||
setDisplayedSrc((currentSrc) => (currentSrc === failedSrc ? null : currentSrc));
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{status !== "loaded" ? (
|
||||
{displayedSrc === null ? (
|
||||
<ProjectFaviconFallback className={className} icon={FallbackIcon} />
|
||||
) : null}
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 rounded-sm object-contain",
|
||||
status !== "loaded" && "hidden",
|
||||
className,
|
||||
)}
|
||||
onLoad={() => {
|
||||
loadedProjectFaviconSrcs.add(src);
|
||||
setStatus("loaded");
|
||||
}}
|
||||
onError={() => setStatus("error")}
|
||||
/>
|
||||
{displayedSrc ? (
|
||||
<img
|
||||
src={displayedSrc}
|
||||
alt=""
|
||||
className={cn("size-3.5 shrink-0 rounded-sm object-contain", className)}
|
||||
onError={() => handleLoadError(displayedSrc)}
|
||||
/>
|
||||
) : null}
|
||||
{isLoading ? (
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className="hidden"
|
||||
onLoad={() => {
|
||||
loadedProjectFaviconSrcs.set(cacheKey, src);
|
||||
setDisplayedSrc(src);
|
||||
}}
|
||||
onError={() => handleLoadError(src)}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,32 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isProjectFaviconFallbackUrl, PROJECT_FAVICON_FALLBACK_MARKER } from "./projectFavicon.ts";
|
||||
import {
|
||||
getProjectFaviconCacheKey,
|
||||
isProjectFaviconFallbackUrl,
|
||||
PROJECT_FAVICON_FALLBACK_MARKER,
|
||||
} from "./projectFavicon.ts";
|
||||
|
||||
describe("project favicon", () => {
|
||||
it("uses the project and versioned filename as the cache identity", () => {
|
||||
const firstUrl = "https://environment.example/api/assets/first-signed-token/v1-20-favicon.svg";
|
||||
const refreshedUrl =
|
||||
"https://environment.example/api/assets/refreshed-signed-token/v1-20-favicon.svg";
|
||||
|
||||
expect(getProjectFaviconCacheKey("environment-1", "/workspace", firstUrl)).toBe(
|
||||
getProjectFaviconCacheKey("environment-1", "/workspace", refreshedUrl),
|
||||
);
|
||||
expect(getProjectFaviconCacheKey("environment-1", "/workspace", firstUrl)).not.toBe(
|
||||
getProjectFaviconCacheKey(
|
||||
"environment-1",
|
||||
"/workspace",
|
||||
"https://environment.example/api/assets/refreshed-signed-token/v2-20-favicon.svg",
|
||||
),
|
||||
);
|
||||
expect(getProjectFaviconCacheKey("environment-1", "/workspace", firstUrl)).not.toBe(
|
||||
getProjectFaviconCacheKey("environment-2", "/workspace", firstUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("identifies fallback asset URLs by their dedicated filename", () => {
|
||||
expect(
|
||||
isProjectFaviconFallbackUrl(
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
export const PROJECT_FAVICON_FALLBACK_MARKER = "project-favicon-missing";
|
||||
|
||||
export function getProjectFaviconCacheKey(
|
||||
environmentId: string,
|
||||
workspaceRoot: string,
|
||||
url: string,
|
||||
) {
|
||||
let revision = url;
|
||||
|
||||
try {
|
||||
const pathname = new URL(url, "https://t3.invalid").pathname;
|
||||
revision = pathname.slice(pathname.lastIndexOf("/") + 1);
|
||||
} catch {
|
||||
// Keep the full value as a safe fallback for malformed URLs.
|
||||
}
|
||||
|
||||
return JSON.stringify([environmentId, workspaceRoot, revision]);
|
||||
}
|
||||
|
||||
export function isProjectFaviconFallbackUrl(url: string | null | undefined): boolean {
|
||||
if (!url) return false;
|
||||
|
||||
|
||||
Reference in new issue
Block a user