import { createHash } from 'crypto'; import path from 'path'; import { StorageProvider } from '../storage/StorageProvider'; export interface MediaCacheOptions { storage: StorageProvider; cacheRoot: string; } export interface CacheEntry { hit: true; buffer: Buffer; contentType: string; } export interface CacheMiss { hit: false; } export type CacheLookup = CacheEntry | CacheMiss; export interface CacheStats { images: { count: number; totalBytes: number }; audio: { count: number; totalBytes: number }; } function hashKey(key: string): string { return createHash('sha256').update(key).digest('hex'); } const MAX_ENTRIES = 500; const CATEGORIES = ['images', 'audio'] as const; export function createMediaCache(options: MediaCacheOptions) { const { storage, cacheRoot } = options; function categoryDir(category: string): string { return path.join(cacheRoot, category); } async function ensureCategory(category: string): Promise { await storage.ensureFolderExists(categoryDir(category)); } async function get(category: string, key: string): Promise { const hash = hashKey(key); const dir = categoryDir(category); const metaPath = path.join(dir, `${hash}.meta.json`); if (!(await storage.checkIfExists(metaPath))) { return { hit: false }; } const meta = JSON.parse(await storage.loadFile(metaPath)); const dataPath = path.join(dir, `${hash}${meta.extension}`); try { const buffer = await storage.loadBuffer(dataPath); // Update last access time for eviction tracking meta.lastAccessedAt = new Date().toISOString(); await storage.saveFile(metaPath, JSON.stringify(meta, null, 2)); return { hit: true, buffer, contentType: meta.contentType }; } catch { return { hit: false }; } } async function put( category: string, key: string, data: Buffer, contentType: string, meta: Record ): Promise { await ensureCategory(category); const hash = hashKey(key); const dir = categoryDir(category); const extension = extensionForContentType(contentType); const dataPath = path.join(dir, `${hash}${extension}`); const metaPath = path.join(dir, `${hash}.meta.json`); const now = new Date().toISOString(); await storage.saveBuffer(dataPath, data); await storage.saveFile(metaPath, JSON.stringify({ ...meta, contentType, extension, createdAt: now, lastAccessedAt: now, }, null, 2)); // Run eviction after writing the new entry await evict(); } async function evict(): Promise { // Collect all entries across categories const entries: { category: string; hash: string; lastAccessedAt: string; size: number; metaPath: string; extension: string }[] = []; for (const category of CATEGORIES) { const dir = categoryDir(category); if (!(await storage.checkIfExists(dir))) continue; const files = await storage.listFiles(dir); for (const file of files) { if (!file.endsWith('.meta.json')) continue; const metaPath = path.join(dir, file); try { const meta = JSON.parse(await storage.loadFile(metaPath)); const hash = file.replace('.meta.json', ''); const dataPath = path.join(dir, `${hash}${meta.extension}`); let size = 0; try { const info = await storage.stat(dataPath); size = info.size; } catch { /* data file missing, size stays 0 */ } entries.push({ category, hash, lastAccessedAt: meta.lastAccessedAt || meta.createdAt || '1970-01-01T00:00:00.000Z', size, metaPath, extension: meta.extension, }); } catch { /* skip unreadable meta */ } } } if (entries.length <= MAX_ENTRIES) return; // Sort by lastAccessedAt descending — most recent first entries.sort((a, b) => b.lastAccessedAt.localeCompare(a.lastAccessedAt)); // Evict everything beyond the first 500 const toEvict = entries.slice(MAX_ENTRIES); for (const entry of toEvict) { const dir = categoryDir(entry.category); const dataPath = path.join(dir, `${entry.hash}${entry.extension}`); try { await storage.deleteFile(dataPath); } catch { /* ignore */ } try { await storage.deleteFile(entry.metaPath); } catch { /* ignore */ } } } async function invalidate(category: string, key: string): Promise { const hash = hashKey(key); const dir = categoryDir(category); const metaPath = path.join(dir, `${hash}.meta.json`); if (await storage.checkIfExists(metaPath)) { const meta = JSON.parse(await storage.loadFile(metaPath)); const dataPath = path.join(dir, `${hash}${meta.extension}`); try { await storage.deleteFile(dataPath); } catch { /* ignore */ } try { await storage.deleteFile(metaPath); } catch { /* ignore */ } } } async function clearCategory(category: string): Promise { const dir = categoryDir(category); if (await storage.checkIfExists(dir)) { await storage.deleteFolder(dir); } } async function clearAll(): Promise { await clearCategory('images'); await clearCategory('audio'); } async function stats(): Promise { const result: CacheStats = { images: { count: 0, totalBytes: 0 }, audio: { count: 0, totalBytes: 0 }, }; for (const category of CATEGORIES) { const dir = categoryDir(category); if (!(await storage.checkIfExists(dir))) continue; const files = await storage.listFiles(dir); for (const file of files) { if (file.endsWith('.meta.json')) continue; try { const info = await storage.stat(path.join(dir, file)); result[category].count++; result[category].totalBytes += info.size; } catch { /* skip missing */ } } } return result; } return { get, put, invalidate, clearCategory, clearAll, stats, evict }; } function extensionForContentType(contentType: string): string { if (contentType.includes('png')) return '.png'; if (contentType.includes('jpeg') || contentType.includes('jpg')) return '.jpg'; if (contentType.includes('webp')) return '.webp'; if (contentType.includes('mpeg') || contentType.includes('mp3')) return '.mp3'; if (contentType.includes('wav')) return '.wav'; if (contentType.includes('ogg')) return '.ogg'; return '.bin'; } export type MediaCache = ReturnType;