Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | import { QueryBuilder } from './QueryBuilder'; import { BaseModel } from '../models/BaseModel'; export interface CacheEntry<T> { key: string; data: T[]; timestamp: number; ttl: number; hitCount: number; } export interface CacheStats { totalRequests: number; cacheHits: number; cacheMisses: number; hitRate: number; size: number; maxSize: number; } export class QueryCache { private cache: Map<string, CacheEntry<any>> = new Map(); private maxSize: number; private defaultTTL: number; private stats: CacheStats; constructor(maxSize: number = 1000, defaultTTL: number = 300000) { // 5 minutes default this.maxSize = maxSize; this.defaultTTL = defaultTTL; this.stats = { totalRequests: 0, cacheHits: 0, cacheMisses: 0, hitRate: 0, size: 0, maxSize, }; } generateKey<T extends BaseModel>(query: QueryBuilder<T>): string { const model = query.getModel(); const conditions = query.getConditions(); const relations = query.getRelations(); const sorting = query.getSorting(); const limit = query.getLimit(); const offset = query.getOffset(); // Create a deterministic cache key const keyParts = [ model.name, model.scope, JSON.stringify(conditions.sort((a, b) => a.field.localeCompare(b.field))), JSON.stringify(relations.sort()), JSON.stringify(sorting), limit?.toString() || 'no-limit', offset?.toString() || 'no-offset', ]; // Create hash of the key parts return this.hashString(keyParts.join('|')); } async get<T extends BaseModel>(query: QueryBuilder<T>): Promise<T[] | null> { this.stats.totalRequests++; const key = this.generateKey(query); const entry = this.cache.get(key); if (!entry) { this.stats.cacheMisses++; this.updateHitRate(); return null; } // Check if entry has expired if (Date.now() - entry.timestamp > entry.ttl) { this.cache.delete(key); this.stats.cacheMisses++; this.updateHitRate(); return null; } // Update hit count and stats entry.hitCount++; this.stats.cacheHits++; this.updateHitRate(); // Convert cached data back to model instances const modelClass = query.getModel() as any; // Type assertion for abstract class return entry.data.map((item) => new modelClass(item)); } set<T extends BaseModel>(query: QueryBuilder<T>, data: T[], customTTL?: number): void { const key = this.generateKey(query); const ttl = customTTL || this.defaultTTL; // Serialize model instances to plain objects for caching const serializedData = data.map((item) => item.toJSON()); const entry: CacheEntry<any> = { key, data: serializedData, timestamp: Date.now(), ttl, hitCount: 0, }; // Check if we need to evict entries if (this.cache.size >= this.maxSize) { this.evictLeastUsed(); } this.cache.set(key, entry); this.stats.size = this.cache.size; } invalidate<T extends BaseModel>(query: QueryBuilder<T>): boolean { const key = this.generateKey(query); const deleted = this.cache.delete(key); this.stats.size = this.cache.size; return deleted; } invalidateByModel(modelName: string): number { let deletedCount = 0; for (const [key, _entry] of this.cache.entries()) { if (key.startsWith(this.hashString(modelName))) { this.cache.delete(key); deletedCount++; } } this.stats.size = this.cache.size; return deletedCount; } invalidateByUser(userId: string): number { let deletedCount = 0; for (const [key, entry] of this.cache.entries()) { // Check if the cached entry contains user-specific data if (this.entryContainsUser(entry, userId)) { this.cache.delete(key); deletedCount++; } } this.stats.size = this.cache.size; return deletedCount; } clear(): void { this.cache.clear(); this.stats.size = 0; this.stats.totalRequests = 0; this.stats.cacheHits = 0; this.stats.cacheMisses = 0; this.stats.hitRate = 0; } getStats(): CacheStats { return { ...this.stats }; } // Cache warming - preload frequently used queries async warmup<T extends BaseModel>(queries: QueryBuilder<T>[]): Promise<void> { console.log(`🔥 Warming up cache with ${queries.length} queries...`); const promises = queries.map(async (query) => { try { const results = await query.exec(); this.set(query, results); console.log(`✓ Cached query for ${query.getModel().name}`); } catch (error) { console.warn(`Failed to warm cache for ${query.getModel().name}:`, error); } }); await Promise.all(promises); console.log(`✅ Cache warmup completed`); } // Get cache entries sorted by various criteria getPopularEntries(limit: number = 10): Array<{ key: string; hitCount: number; age: number }> { return Array.from(this.cache.entries()) .map(([key, entry]) => ({ key, hitCount: entry.hitCount, age: Date.now() - entry.timestamp, })) .sort((a, b) => b.hitCount - a.hitCount) .slice(0, limit); } getExpiredEntries(): string[] { const now = Date.now(); const expired: string[] = []; for (const [key, entry] of this.cache.entries()) { if (now - entry.timestamp > entry.ttl) { expired.push(key); } } return expired; } // Cleanup expired entries cleanup(): number { const expired = this.getExpiredEntries(); for (const key of expired) { this.cache.delete(key); } this.stats.size = this.cache.size; return expired.length; } // Configure cache behavior setMaxSize(size: number): void { this.maxSize = size; this.stats.maxSize = size; // Evict entries if current size exceeds new max while (this.cache.size > size) { this.evictLeastUsed(); } } setDefaultTTL(ttl: number): void { this.defaultTTL = ttl; } // Cache analysis analyzeUsage(): { totalEntries: number; averageHitCount: number; averageAge: number; memoryUsage: number; } { const entries = Array.from(this.cache.values()); const now = Date.now(); const totalHits = entries.reduce((sum, entry) => sum + entry.hitCount, 0); const totalAge = entries.reduce((sum, entry) => sum + (now - entry.timestamp), 0); // Rough memory usage estimation const memoryUsage = entries.reduce((sum, entry) => { return sum + JSON.stringify(entry.data).length; }, 0); return { totalEntries: entries.length, averageHitCount: entries.length > 0 ? totalHits / entries.length : 0, averageAge: entries.length > 0 ? totalAge / entries.length : 0, memoryUsage, }; } private evictLeastUsed(): void { if (this.cache.size === 0) return; // Find entry with lowest hit count and oldest timestamp let leastUsedKey: string | null = null; let leastUsedScore = Infinity; for (const [key, entry] of this.cache.entries()) { // Score based on hit count and age (lower is worse) const age = Date.now() - entry.timestamp; const score = entry.hitCount - age / 1000000; // Age penalty if (score < leastUsedScore) { leastUsedScore = score; leastUsedKey = key; } } if (leastUsedKey) { this.cache.delete(leastUsedKey); this.stats.size = this.cache.size; } } private entryContainsUser(entry: CacheEntry<any>, userId: string): boolean { // Check if the cached data contains user-specific information try { const dataStr = JSON.stringify(entry.data); return dataStr.includes(userId); } catch { return false; } } private updateHitRate(): void { if (this.stats.totalRequests > 0) { this.stats.hitRate = this.stats.cacheHits / this.stats.totalRequests; } } private hashString(str: string): string { let hash = 0; if (str.length === 0) return hash.toString(); for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; // Convert to 32-bit integer } return Math.abs(hash).toString(36); } } |