All files / src/platform/cache cache.service.ts

0% Statements 0/67
0% Branches 0/48
0% Functions 0/11
0% Lines 0/63

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                                                                                                                                                                                                                                                                                                                                 
import { Injectable, Logger, Inject, Optional } from '@nestjs/common';
import Redis from 'ioredis';
import { CacheNamespace, NAMESPACE_POLICIES } from './cache-namespace.registry';
 
export const REDIS_CLIENT = 'REDIS_CLIENT';
 
const MAX_VALUE_SIZE_BYTES = 512 * 1024; // 512 KB limit per cached object
 
@Injectable()
export class CacheService {
  private readonly logger = new Logger(CacheService.name);
  private readonly inMemoryFallback = new Map<
    string,
    { value: string; expiresAt: number }
  >();
  private redisAvailable = true;
 
  constructor(
    @Optional() @Inject(REDIS_CLIENT) private readonly redis: Redis | null,
  ) {
    if (this.redis) {
      this.redis.on('error', (err) => {
        if (this.redisAvailable) {
          this.logger.warn(
            `Redis unavailable — falling back to in-memory cache: ${err.message}`,
          );
          this.redisAvailable = false;
        }
      });
 
      this.redis.on('ready', () => {
        if (!this.redisAvailable) {
          this.logger.log('Redis reconnected — resuming Redis cache');
          this.redisAvailable = true;
        }
      });
    } else {
      this.redisAvailable = false;
    }
  }
 
  async get<T>(key: string): Promise<T | null> {
    try {
      if (this.redisAvailable && this.redis) {
        const raw = await this.redis.get(key);
        return raw ? (JSON.parse(raw) as T) : null;
      }
    } catch (err) {
      this.logger.error(`Cache GET failed for key ${key}: ${err.message}`);
    }
 
    // Fallback to in-memory
    const record = this.inMemoryFallback.get(key);
    if (!record || Date.now() > record.expiresAt) {
      this.inMemoryFallback.delete(key);
      return null;
    }
    return JSON.parse(record.value) as T;
  }
 
  async set(
    key: string,
    value: any,
    ttlSeconds?: number,
    namespace?: CacheNamespace,
  ): Promise<void> {
    const ttl =
      ttlSeconds ??
      (namespace ? NAMESPACE_POLICIES[namespace]?.ttlSeconds : 60) ??
      60;
 
    const serialized = JSON.stringify(value);
    if (Buffer.byteLength(serialized) > MAX_VALUE_SIZE_BYTES) {
      this.logger.warn(
        `Cache SET skipped — value exceeds size limit for key ${key}`,
      );
      return;
    }
 
    try {
      if (this.redisAvailable && this.redis) {
        await this.redis.set(key, serialized, 'EX', ttl);
        return;
      }
    } catch (err) {
      this.logger.error(`Cache SET failed for key ${key}: ${err.message}`);
    }
 
    // Fallback
    this.inMemoryFallback.set(key, {
      value: serialized,
      expiresAt: Date.now() + ttl * 1000,
    });
  }
 
  async del(key: string): Promise<void> {
    try {
      if (this.redisAvailable && this.redis) {
        await this.redis.del(key);
      }
    } catch (err) {
      this.logger.error(`Cache DEL failed for key ${key}: ${err.message}`);
    }
    this.inMemoryFallback.delete(key);
  }
 
  async invalidatePattern(pattern: string): Promise<void> {
    try {
      if (this.redisAvailable && this.redis) {
        const keys = await this.redis.keys(pattern);
        if (keys.length > 0) {
          await this.redis.del(...keys);
          this.logger.log(
            `Invalidated ${keys.length} keys matching pattern: ${pattern}`,
          );
        }
      }
    } catch (err) {
      this.logger.error(
        `Cache pattern invalidation failed for ${pattern}: ${err.message}`,
      );
    }
  }
 
  async withCache<T>(
    key: string,
    factory: () => Promise<T>,
    ttlSeconds?: number,
    namespace?: CacheNamespace,
  ): Promise<T> {
    const cached = await this.get<T>(key);
    if (cached !== null) return cached;
 
    const value = await factory();
    await this.set(key, value, ttlSeconds, namespace);
    return value;
  }
 
  async acquireLock(lockKey: string, ttlSeconds = 30): Promise<boolean> {
    if (!this.redisAvailable || !this.redis) return true; // optimistic in-memory mode
    const result = await this.redis.set(
      `lock:${lockKey}`,
      '1',
      'EX',
      ttlSeconds,
      'NX',
    );
    return result === 'OK';
  }
 
  async releaseLock(lockKey: string): Promise<void> {
    if (this.redisAvailable && this.redis) {
      await this.redis.del(`lock:${lockKey}`);
    }
  }
 
  isRedisAvailable(): boolean {
    return this.redisAvailable;
  }
}