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 | import { Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { createClient } from 'redis'; import { CacheOptions } from '../interfaces/ai.interface'; @Injectable() export class CacheService { private readonly logger = new Logger(CacheService.name); private readonly redis: ReturnType<typeof createClient>; private readonly defaultTTL: number; constructor(private configService: ConfigService) { this.defaultTTL = this.configService.get<number>('ai.caching.embeddingsTtl', 86400); this.redis = createClient({ socket: { host: this.configService.get<string>('redis.host'), port: this.configService.get<number>('redis.port'), }, password: this.configService.get<string>('redis.password'), database: this.configService.get<number>('redis.db'), }); this.redis.on('error', (error) => { this.logger.error('Redis connection error', error); }); this.redis.on('connect', () => { this.logger.log('Connected to Redis cache'); }); this.redis.connect(); } async get<T>(key: string): Promise<T | null> { try { const cached = await this.redis.get(this.prefixKey(key)); return cached ? JSON.parse(cached) : null; } catch (error) { this.logger.error(`Cache get error for key ${key}`, error); return null; } } async set<T>(key: string, value: T, options?: CacheOptions): Promise<void> { try { const ttl = options?.ttl || this.defaultTTL; const prefixedKey = this.prefixKey(key); await this.redis.setEx(prefixedKey, ttl, JSON.stringify(value)); // Add to tag sets if tags are provided Iif (options?.tags) { for (const tag of options.tags) { await this.redis.sAdd(this.tagKey(tag), prefixedKey); } } this.logger.debug(`Cached ${key} with TTL ${ttl}s`); } catch (error) { this.logger.error(`Cache set error for key ${key}`, error); } } async delete(key: string): Promise<void> { try { await this.redis.del(this.prefixKey(key)); this.logger.debug(`Deleted cache key ${key}`); } catch (error) { this.logger.error(`Cache delete error for key ${key}`, error); } } async deleteByTag(tag: string): Promise<void> { try { const tagKey = this.tagKey(tag); const keys = await this.redis.sMembers(tagKey); Iif (keys.length > 0) { await this.redis.del(keys); await this.redis.del(tagKey); this.logger.debug(`Deleted ${keys.length} cache entries with tag ${tag}`); } } catch (error) { this.logger.error(`Cache delete by tag error for tag ${tag}`, error); } } async exists(key: string): Promise<boolean> { try { const result = await this.redis.exists(this.prefixKey(key)); return result === 1; } catch (error) { this.logger.error(`Cache exists error for key ${key}`, error); return false; } } async getTTL(key: string): Promise<number> { try { return await this.redis.ttl(this.prefixKey(key)); } catch (error) { this.logger.error(`Cache TTL error for key ${key}`, error); return -1; } } async increment(key: string, value: number = 1): Promise<number> { try { return await this.redis.incrBy(this.prefixKey(key), value); } catch (error) { this.logger.error(`Cache increment error for key ${key}`, error); return 0; } } async getStats(): Promise<{ totalKeys: number; memoryUsage: string; hitRate: number; }> { try { const info = await this.redis.info('memory'); const keyspace = await this.redis.info('keyspace'); // Parse memory usage const memoryMatch = info.match(/used_memory_human:(.+)/); const memoryUsage = memoryMatch ? memoryMatch[1].trim() : 'Unknown'; // Parse total keys const keysMatch = keyspace.match(/keys=(\d+)/); const totalKeys = keysMatch ? parseInt(keysMatch[1]) : 0; return { totalKeys, memoryUsage, hitRate: 0, // Would need to track hits/misses for accurate calculation }; } catch (error) { this.logger.error('Cache stats error', error); return { totalKeys: 0, memoryUsage: 'Unknown', hitRate: 0, }; } } // Specialized methods for AI caching async cacheEmbeddings(text: string, embeddings: number[], model: string): Promise<void> { const key = this.embeddingKey(text, model); await this.set(key, embeddings, { ttl: this.configService.get<number>('ai.caching.embeddingsTtl', 86400), tags: ['embeddings', model], }); } async getCachedEmbeddings(text: string, model: string): Promise<number[] | null> { const key = this.embeddingKey(text, model); return this.get<number[]>(key); } async cacheRecommendations(userId: string, context: any, recommendations: any): Promise<void> { const key = this.recommendationKey(userId, context); await this.set(key, recommendations, { ttl: this.configService.get<number>('ai.caching.recommendationsTtl', 3600), tags: ['recommendations', `user:${userId}`], }); } async getCachedRecommendations(userId: string, context: any): Promise<any | null> { const key = this.recommendationKey(userId, context); return this.get(key); } async cacheChatResponse(query: string, response: any, model: string): Promise<void> { const key = this.chatKey(query, model); await this.set(key, response, { ttl: this.configService.get<number>('ai.caching.chatResponsesTtl', 1800), tags: ['chat', model], }); } async getCachedChatResponse(query: string, model: string): Promise<any | null> { const key = this.chatKey(query, model); return this.get(key); } async invalidateUserCache(userId: string): Promise<void> { await this.deleteByTag(`user:${userId}`); } async invalidateProductCache(productId: string): Promise<void> { await this.deleteByTag(`product:${productId}`); } // Private helper methods private prefixKey(key: string): string { return `savepal:ai:${key}`; } private tagKey(tag: string): string { return `savepal:ai:tag:${tag}`; } private embeddingKey(text: string, model: string): string { const hash = this.hashString(text); return `embedding:${model}:${hash}`; } private recommendationKey(userId: string, context: any): string { const contextHash = this.hashString(JSON.stringify(context)); return `recommendation:${userId}:${contextHash}`; } private chatKey(query: string, model: string): string { const queryHash = this.hashString(query); return `chat:${model}:${queryHash}`; } private hashString(str: string): string { // Simple hash function for cache keys let hash = 0; 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); } async onModuleDestroy(): Promise<void> { await this.redis.quit(); } } |