import { MatrixClient } from 'matrix-js-sdk'; /** * Single shared cache for a user's profile fields. * * Colour, banner and collectibles all come from the same profile endpoint, so they * must read through one cache instead of each keeping their own - otherwise opening * a profile view fires the same request three times. */ export type ProfileFields = Record; export const PROFILE_CACHE_TTL_MS = 5 * 60 * 1000; const MAX_PROFILE_CACHE_ENTRIES = 500; type ProfileCacheEntry = { fields: ProfileFields; timestamp: number }; const profileCache = new Map(); const inflightRequests = new Map>(); const cacheListeners = new Set<(userId: string) => void>(); export function registerProfileCacheListener(fn: (userId: string) => void): () => void { cacheListeners.add(fn); return () => cacheListeners.delete(fn); } export function clearProfileCache(userId?: string): void { if (!userId) return; profileCache.delete(userId); inflightRequests.delete(userId); cacheListeners.forEach((listener) => listener(userId)); } function setProfileCache(userId: string, fields: ProfileFields): void { if (profileCache.size >= MAX_PROFILE_CACHE_ENTRIES) { const firstKey = profileCache.keys().next().value; if (firstKey !== undefined) profileCache.delete(firstKey); } profileCache.set(userId, { fields, timestamp: Date.now() }); } /** Cached profile fields, or undefined when the entry is missing or expired. */ export function getCachedProfileFields(userId: string): ProfileFields | undefined { if (!userId) return undefined; const entry = profileCache.get(userId); if (!entry || Date.now() - entry.timestamp >= PROFILE_CACHE_TTL_MS) return undefined; return entry.fields; } /** * Profile fields for a user, served from the shared cache when possible. * Concurrent callers for the same user share one request. */ export async function getProfileFields(mx: MatrixClient, userId: string): Promise { if (!userId) return {}; const cached = getCachedProfileFields(userId); if (cached) return cached; const pending = inflightRequests.get(userId); if (pending) return pending; const request = (async () => { let fields: ProfileFields = {}; try { if (await mx.doesServerSupportExtendedProfiles()) { fields = await mx.getExtendedProfile(userId); } } catch { // Server may not support MSC4133, or the user has no extended fields. } if (Object.keys(fields).length === 0) { try { fields = (await mx.getProfileInfo(userId)) as ProfileFields; } catch { fields = {}; } } setProfileCache(userId, fields); return fields; })(); inflightRequests.set(userId, request); try { return await request; } finally { if (inflightRequests.get(userId) === request) inflightRequests.delete(userId); } }