/** * Redis client singleton for SentryAgent.ai AgentIdP. * Used for token revocation tracking, rate limiting, and monthly token counts. */ import { createClient, RedisClientType } from 'redis'; let redisClient: RedisClientType | null = null; /** * Returns the singleton Redis client instance. * Initialises and connects the client on first call using REDIS_URL from env. * * @returns Promise resolving to the connected Redis client. * @throws Error if REDIS_URL is not set or connection fails. */ export async function getRedisClient(): Promise { if (!redisClient) { const url = process.env['REDIS_URL']; if (!url) { throw new Error('REDIS_URL environment variable is required'); } redisClient = createClient({ url }) as RedisClientType; redisClient.on('error', (err: Error) => { // eslint-disable-next-line no-console console.error('Redis client error', err); }); await redisClient.connect(); } return redisClient; } /** * Disconnects the Redis client and resets the singleton. * Used for graceful shutdown and tests. * * @returns Promise that resolves when the client is disconnected. */ export async function closeRedisClient(): Promise { if (redisClient) { await redisClient.quit(); redisClient = null; } }