import { Injectable, Logger, OnModuleDestroy, OnModuleInit, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { createClient, type RedisClientType } from 'redis'; import type { AppConfig } from '../config/app-config.schema.js'; import { MetricsService } from '../metrics/metrics.service.js'; const UNLOCK_SCRIPT = 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end'; type Client = RedisClientType; @Injectable() export class RedisClient implements OnModuleInit, OnModuleDestroy { readonly client: Client; private readonly logger = new Logger(RedisClient.name); constructor( private readonly config: ConfigService, private readonly metrics: MetricsService, ) { this.client = createClient({ url: this.config.getOrThrow('REDIS_URL'), disableOfflineQueue: true, socket: { reconnectStrategy: (attempt) => Math.min(1000 + attempt * 250, 5000), connectTimeout: 5000, }, }) as Client; // Reconnect failures must be visible; the readiness probe pings Redis. this.client.on('error', (error: Error) => { this.metrics.increment('redis.error'); this.logger.warn(`Redis error: ${error.message}`); }); } async onModuleInit(): Promise { await this.client.connect(); } async onModuleDestroy(): Promise { if (this.client.isOpen) await this.client.quit(); } async health(): Promise { this.metrics.increment('redis.ping'); // AbortSignal.timeout ограничивает именно пробу: обычные GET/SET остаются // без командного таймаута, а замороженный Redis проваливает готовность // в бюджет, который короче timeout check балансировщика. const timeout = AbortSignal.timeout( this.config.getOrThrow('HEALTH_TIMEOUT_MS'), ); await this.client.withAbortSignal(timeout).ping(); } async get(key: string): Promise { this.metrics.increment('redis.get'); return this.client.get(key); } async set( key: string, value: string, options?: { EX?: number; PX?: number; NX?: boolean }, ): Promise { this.metrics.increment('redis.set'); return this.client.set(key, value, options); } async setNxEx( key: string, value: string, seconds: number, ): Promise { this.metrics.increment('redis.set'); return ( (await this.client.set(key, value, { NX: true, EX: seconds })) === 'OK' ); } async setNxPx( key: string, value: string, milliseconds: number, ): Promise { this.metrics.increment('redis.set'); return ( (await this.client.set(key, value, { NX: true, PX: milliseconds, })) === 'OK' ); } async del(key: string): Promise { this.metrics.increment('redis.del'); return this.client.del(key); } async incr(key: string): Promise { this.metrics.increment('redis.incr'); return this.client.incr(key); } async expire(key: string, seconds: number): Promise { this.metrics.increment('redis.expire'); return (await this.client.expire(key, seconds)) === 1; } async scan( cursor: number, pattern?: string, count = 100, ): Promise<{ cursor: number; keys: string[] }> { this.metrics.increment('redis.scan'); const result = await this.client.scan(String(cursor), { MATCH: pattern, COUNT: count, }); return { cursor: Number(result.cursor), keys: result.keys }; } async unlock(key: string, owner: string): Promise { this.metrics.increment('redis.unlock'); return Number( await this.client.eval(UNLOCK_SCRIPT, { keys: [key], arguments: [owner], }), ); } pipeline(commands: Array<[string, ...string[]]>): Promise { this.metrics.increment('redis.pipeline'); const multi = this.client.multi(); for (const [command, ...args] of commands) multi.addCommand([command, ...args]); return multi.exec(); } }