Files
cinny/src/app/utils/profileAssetCache.ts
T
litruv 9b657e3ab4
Trigger cinny-mobile / dispatch (push) Successful in 1s
Cache profile fields and assets behind one shared store.
Colour, banner, collectibles, and profile each read the same extended
profile endpoint through separate caches with mismatched TTLs, so a
single profile view fired three round trips. They now read through one
cache with a shared TTL and in-flight dedupe, and profile media is kept
as blob URLs instead of being re-downloaded per mount.

useUserProfile now prefers the SDK's sync-cached user and only fetches
when both the SDK and the cache are cold.
2026-10-06 07:42:47 +11:00

74 lines
2.1 KiB
TypeScript

import { MatrixClient } from 'matrix-js-sdk';
import { mxcUrlToHttp } from './matrix';
import { getCurrentAccessToken } from './auth';
/**
* Blob URLs for profile assets (banner, nameplate, avatar decoration).
*
* Kept in one cache so reopening the same profile does not re-download the
* same media on every mount. Entries are revoked only when evicted.
*/
const MAX_ASSET_CACHE_ENTRIES = 200;
const assetCache = new Map<string, string>();
const inflightAssets = new Map<string, Promise<string | undefined>>();
function evictOldest(): void {
const firstKey = assetCache.keys().next().value;
if (firstKey === undefined) return;
const url = assetCache.get(firstKey);
assetCache.delete(firstKey);
if (url) URL.revokeObjectURL(url);
}
export async function getProfileAssetUrl(
mx: MatrixClient,
mxcUrl: string,
useAuthentication: boolean
): Promise<string | undefined> {
if (!mxcUrl) return undefined;
const cached = assetCache.get(mxcUrl);
if (cached) return cached;
const pending = inflightAssets.get(mxcUrl);
if (pending) return pending;
const request = (async () => {
const httpUrl = mxcUrlToHttp(mx, mxcUrl, useAuthentication);
if (!httpUrl) return undefined;
const headers: HeadersInit = {};
if (useAuthentication) {
const accessToken = getCurrentAccessToken();
if (accessToken) headers.Authorization = `Bearer ${accessToken}`;
}
try {
const response = await fetch(httpUrl, { headers });
if (!response.ok) return undefined;
const blob = await response.blob();
const blobUrl = URL.createObjectURL(blob);
if (assetCache.size >= MAX_ASSET_CACHE_ENTRIES) evictOldest();
assetCache.set(mxcUrl, blobUrl);
return blobUrl;
} catch {
return undefined;
}
})();
inflightAssets.set(mxcUrl, request);
try {
return await request;
} finally {
if (inflightAssets.get(mxcUrl) === request) inflightAssets.delete(mxcUrl);
}
}
export function clearProfileAssetCache(): void {
assetCache.forEach((url) => URL.revokeObjectURL(url));
assetCache.clear();
inflightAssets.clear();
}