| 38 | * - Performance statistics |
| 39 | */ |
| 40 | export class CacheManager<T = MemoryEntry> extends EventEmitter { |
| 41 | private config: CacheConfig; |
| 42 | private cache: Map<string, LRUNode<T>> = new Map(); |
| 43 | private head: LRUNode<T> | null = null; |
| 44 | private tail: LRUNode<T> | null = null; |
| 45 | private currentMemory: number = 0; |
| 46 | |
| 47 | // Statistics |
| 48 | private stats: { |
| 49 | hits: number; |
| 50 | misses: number; |
| 51 | evictions: number; |
| 52 | expirations: number; |
| 53 | writes: number; |
| 54 | } = { |
| 55 | hits: 0, |
| 56 | misses: 0, |
| 57 | evictions: 0, |
| 58 | expirations: 0, |
| 59 | writes: 0, |
| 60 | }; |
| 61 | |
| 62 | // Cleanup timer |
| 63 | private cleanupInterval: NodeJS.Timeout | null = null; |
| 64 | |
| 65 | constructor(config: Partial<CacheConfig> = {}) { |
| 66 | super(); |
| 67 | this.config = this.mergeConfig(config); |
| 68 | this.startCleanupTimer(); |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Get a value from the cache |
| 73 | */ |
| 74 | get(key: string): T | null { |
| 75 | const node = this.cache.get(key); |
| 76 | |
| 77 | if (!node) { |
| 78 | this.stats.misses++; |
| 79 | this.emit('cache:miss', { key }); |
| 80 | return null; |
| 81 | } |
| 82 | |
| 83 | // Check if expired |
| 84 | if (this.isExpired(node.value)) { |
| 85 | this.delete(key); |
| 86 | this.stats.misses++; |
| 87 | this.stats.expirations++; |
| 88 | this.emit('cache:expired', { key }); |
| 89 | return null; |
| 90 | } |
| 91 | |
| 92 | // Update access time and count |
| 93 | node.value.lastAccessedAt = Date.now(); |
| 94 | node.value.accessCount++; |
| 95 | |
| 96 | // Move to front (most recently used) |
| 97 | this.moveToFront(node); |
nothing calls this directly
no outgoing calls
no test coverage detected