import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common'; import type { createClient } from 'redis'; import { AUCTION_REDIS_CLIENT } from './auction-redis.constants'; import type { AuctionRedisScriptDefinition } from './auction-redis.scripts'; export type AuctionRedisClient = ReturnType; export interface EvalShaWithReloadParams { keys: string[]; script: string; scriptSha: string; values: string[]; } export class AuctionRedisNoscriptError extends Error { constructor(message = 'NOSCRIPT No matching script. Please use EVAL.') { super(message); this.name = 'AuctionRedisNoscriptError'; } } function isNoscriptError(error: unknown): boolean { if (error instanceof AuctionRedisNoscriptError) return true; const message = error instanceof Error ? error.message : typeof error === 'string' ? error : ''; return /\bNOSCRIPT\b/iu.test(message); } function buildEvalShaCommand( scriptSha: string, keys: string[], values: string[], ): string[] { return ['EVALSHA', scriptSha, String(keys.length), ...keys, ...values]; } function parseRedisTimeReply(reply: unknown): number { if (Array.isArray(reply) && reply.length >= 2) { const seconds = Number(reply[0]); const microseconds = Number(reply[1]); if (Number.isFinite(seconds) && Number.isFinite(microseconds)) { return seconds * 1000 + Math.floor(microseconds / 1000); } } throw new Error(`Unexpected Redis TIME reply: ${JSON.stringify(reply)}`); } @Injectable() export class AuctionRedisService implements OnModuleDestroy { constructor( @Inject(AUCTION_REDIS_CLIENT) private readonly client: AuctionRedisClient, ) {} async onModuleDestroy() { try { await this.client.quit(); } catch { this.client.destroy(); } } public raw(): AuctionRedisClient { return this.client; } public async getCurrentRedisTimestampMS(): Promise { const reply = await this.client.sendCommand(['TIME']); return parseRedisTimeReply(reply); } public async evalShaWithReload( params: EvalShaWithReloadParams, ): Promise { try { return (await this.client.sendCommand( buildEvalShaCommand(params.scriptSha, params.keys, params.values), )) as T; } catch (error) { if (!isNoscriptError(error)) throw error; } const loadedShaReply = await this.client.sendCommand([ 'SCRIPT', 'LOAD', params.script, ]); if (typeof loadedShaReply !== 'string') { throw new Error('Redis SCRIPT LOAD returned a non-string SHA.'); } const loadedSha = loadedShaReply; return (await this.client.sendCommand( buildEvalShaCommand(loadedSha, params.keys, params.values), )) as T; } public async evalScript( script: AuctionRedisScriptDefinition, keys: string[], values: string[], ): Promise { return this.evalShaWithReload({ keys, script: script.lua, scriptSha: script.sha, values, }); } public async acquireTokenLock( key: string, token: string, ttlMS: number, ): Promise { const result = await this.client.sendCommand([ 'SET', key, token, 'PX', String(ttlMS), 'NX', ]); return result === 'OK'; } public async releaseTokenLock(key: string, token: string): Promise { const result = await this.client.sendCommand([ 'EVAL', 'if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end', '1', key, token, ]); return Number(result) === 1; } }