|
| 1 | +/** |
| 2 | + * Global LRU thumbnail cache to prevent repeated IPC calls and memory leaks. |
| 3 | + * |
| 4 | + * Features: |
| 5 | + * - LRU eviction when cache exceeds MAX_CACHE_SIZE |
| 6 | + * - Request deduplication via pending promises |
| 7 | + * - TTL expiration to handle file updates |
| 8 | + * - Invalidation API for file operations (move, rename, delete) |
| 9 | + */ |
| 10 | + |
| 11 | +import { log } from './logger' |
| 12 | + |
| 13 | +interface CacheEntry { |
| 14 | + data: string // base64 data URL |
| 15 | + timestamp: number // for TTL expiration |
| 16 | + accessTime: number // for LRU eviction |
| 17 | +} |
| 18 | + |
| 19 | +// Cache configuration |
| 20 | +const MAX_CACHE_SIZE = 200 // ~6MB max (200 x 30KB avg) |
| 21 | +const CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes |
| 22 | + |
| 23 | +// Global cache state (module singleton) |
| 24 | +const cache = new Map<string, CacheEntry>() |
| 25 | +const pending = new Map<string, Promise<string | null>>() |
| 26 | + |
| 27 | +// Normalize path for cache key (lowercase, forward slashes) |
| 28 | +function normalizePath(filePath: string): string { |
| 29 | + return filePath.replace(/\\/g, '/').toLowerCase() |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Evict oldest entries when cache exceeds max size |
| 34 | + */ |
| 35 | +function evictOldest(): void { |
| 36 | + if (cache.size <= MAX_CACHE_SIZE) return |
| 37 | + |
| 38 | + // Sort entries by access time (oldest first) |
| 39 | + const entries = Array.from(cache.entries()) |
| 40 | + .sort((a, b) => a[1].accessTime - b[1].accessTime) |
| 41 | + |
| 42 | + // Remove oldest 20% to avoid frequent evictions |
| 43 | + const toRemove = Math.ceil(cache.size * 0.2) |
| 44 | + for (let i = 0; i < toRemove && i < entries.length; i++) { |
| 45 | + cache.delete(entries[i][0]) |
| 46 | + } |
| 47 | + |
| 48 | + log.debug('[ThumbnailCache]', `Evicted ${toRemove} oldest entries`, { |
| 49 | + newSize: cache.size |
| 50 | + }) |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Check if entry is expired |
| 55 | + */ |
| 56 | +function isExpired(entry: CacheEntry): boolean { |
| 57 | + return Date.now() - entry.timestamp > CACHE_TTL_MS |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * Get thumbnail from cache or fetch via IPC. |
| 62 | + * Deduplicates concurrent requests for the same file. |
| 63 | + * |
| 64 | + * @param filePath - Full file path |
| 65 | + * @returns Base64 data URL or null if not available |
| 66 | + */ |
| 67 | +export async function getThumbnail(filePath: string): Promise<string | null> { |
| 68 | + const key = normalizePath(filePath) |
| 69 | + |
| 70 | + // Check cache first |
| 71 | + const cached = cache.get(key) |
| 72 | + if (cached && !isExpired(cached)) { |
| 73 | + // Update access time for LRU |
| 74 | + cached.accessTime = Date.now() |
| 75 | + return cached.data |
| 76 | + } |
| 77 | + |
| 78 | + // Remove expired entry if exists |
| 79 | + if (cached) { |
| 80 | + cache.delete(key) |
| 81 | + } |
| 82 | + |
| 83 | + // Check if request is already pending |
| 84 | + const pendingRequest = pending.get(key) |
| 85 | + if (pendingRequest) { |
| 86 | + return pendingRequest |
| 87 | + } |
| 88 | + |
| 89 | + // Create new request |
| 90 | + const request = fetchThumbnail(filePath, key) |
| 91 | + pending.set(key, request) |
| 92 | + |
| 93 | + try { |
| 94 | + const result = await request |
| 95 | + return result |
| 96 | + } finally { |
| 97 | + pending.delete(key) |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +/** |
| 102 | + * Fetch thumbnail from electron IPC |
| 103 | + */ |
| 104 | +async function fetchThumbnail(filePath: string, key: string): Promise<string | null> { |
| 105 | + try { |
| 106 | + const result = await window.electronAPI?.extractSolidWorksThumbnail(filePath) |
| 107 | + |
| 108 | + if (result?.success && result.data && result.data.startsWith('data:image/')) { |
| 109 | + // Validate data size (skip if too small or too large) |
| 110 | + if (result.data.length > 100 && result.data.length < 10000000) { |
| 111 | + const now = Date.now() |
| 112 | + cache.set(key, { |
| 113 | + data: result.data, |
| 114 | + timestamp: now, |
| 115 | + accessTime: now |
| 116 | + }) |
| 117 | + |
| 118 | + // Evict if needed |
| 119 | + evictOldest() |
| 120 | + |
| 121 | + return result.data |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + return null |
| 126 | + } catch (err) { |
| 127 | + log.error('[ThumbnailCache]', 'Failed to fetch thumbnail', { |
| 128 | + path: filePath, |
| 129 | + error: err |
| 130 | + }) |
| 131 | + return null |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +/** |
| 136 | + * Invalidate cache entry for a specific path. |
| 137 | + * Call this when files are moved, renamed, or deleted. |
| 138 | + * |
| 139 | + * @param filePath - File path to invalidate |
| 140 | + */ |
| 141 | +export function invalidate(filePath: string): void { |
| 142 | + const key = normalizePath(filePath) |
| 143 | + if (cache.delete(key)) { |
| 144 | + log.debug('[ThumbnailCache]', 'Invalidated', { path: filePath }) |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +/** |
| 149 | + * Invalidate all cache entries under a folder path. |
| 150 | + * Call this when folders are moved, renamed, or deleted. |
| 151 | + * |
| 152 | + * @param folderPath - Folder path prefix to invalidate |
| 153 | + */ |
| 154 | +export function invalidateFolder(folderPath: string): void { |
| 155 | + const prefix = normalizePath(folderPath) |
| 156 | + let count = 0 |
| 157 | + |
| 158 | + for (const key of cache.keys()) { |
| 159 | + if (key.startsWith(prefix + '/') || key === prefix) { |
| 160 | + cache.delete(key) |
| 161 | + count++ |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + if (count > 0) { |
| 166 | + log.debug('[ThumbnailCache]', `Invalidated folder`, { |
| 167 | + path: folderPath, |
| 168 | + count |
| 169 | + }) |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +/** |
| 174 | + * Clear the entire cache. |
| 175 | + * Call this on sign-out or vault change. |
| 176 | + */ |
| 177 | +export function clearCache(): void { |
| 178 | + const size = cache.size |
| 179 | + cache.clear() |
| 180 | + pending.clear() |
| 181 | + if (size > 0) { |
| 182 | + log.debug('[ThumbnailCache]', `Cleared cache`, { entriesCleared: size }) |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +/** |
| 187 | + * Get current cache statistics (for debugging) |
| 188 | + */ |
| 189 | +export function getCacheStats(): { size: number; pendingCount: number } { |
| 190 | + return { |
| 191 | + size: cache.size, |
| 192 | + pendingCount: pending.size |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +// Export as namespace for cleaner imports |
| 197 | +export const thumbnailCache = { |
| 198 | + get: getThumbnail, |
| 199 | + invalidate, |
| 200 | + invalidateFolder, |
| 201 | + clear: clearCache, |
| 202 | + getStats: getCacheStats |
| 203 | +} |
0 commit comments