|
| 1 | +import HawkCatcher from '@hawk.so/nodejs'; |
| 2 | +import { createClient, RedisClientType } from 'redis'; |
| 3 | + |
| 4 | +// eslint call error: 0:0 error Parsing error: Cannot read properties of undefined (reading 'map') |
| 5 | +// export type TsRangeResult = [timestamp: string, value: string]; |
| 6 | +export type TsRangeResult = any; |
| 7 | + |
| 8 | +/** |
| 9 | + * Helper class for working with Redis |
| 10 | + */ |
| 11 | +export default class RedisHelper { |
| 12 | + /** |
| 13 | + * TTL for lock records in Redis (in seconds) |
| 14 | + */ |
| 15 | + private static readonly LOCK_TTL = 10; |
| 16 | + |
| 17 | + /** |
| 18 | + * Singleton instance |
| 19 | + */ |
| 20 | + private static instance: RedisHelper | null = null; |
| 21 | + |
| 22 | + /** |
| 23 | + * Redis client instance |
| 24 | + */ |
| 25 | + private redisClient: RedisClientType | null = null; |
| 26 | + |
| 27 | + /** |
| 28 | + * Flag to track if we're currently reconnecting |
| 29 | + */ |
| 30 | + private isReconnecting = false; |
| 31 | + |
| 32 | + /** |
| 33 | + * Constructor |
| 34 | + * Initializes the Redis client and sets up error handling with auto-reconnect |
| 35 | + */ |
| 36 | + constructor() { |
| 37 | + if (!process.env.REDIS_URL) { |
| 38 | + console.warn('[Redis] REDIS_URL not set, Redis features will be disabled'); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + try { |
| 43 | + this.redisClient = createClient({ |
| 44 | + url: process.env.REDIS_URL, |
| 45 | + socket: { |
| 46 | + reconnectStrategy: (retries) => { |
| 47 | + /* |
| 48 | + * Exponential backoff: wait longer between each retry |
| 49 | + * Max wait time: 30 seconds |
| 50 | + */ |
| 51 | + const delay = Math.min(retries * 1000, 30000); |
| 52 | + console.log(`[Redis] Reconnecting... attempt ${retries}, waiting ${delay}ms`); |
| 53 | + return delay; |
| 54 | + }, |
| 55 | + }, |
| 56 | + }); |
| 57 | + |
| 58 | + // Handle connection errors |
| 59 | + this.redisClient.on('error', (error) => { |
| 60 | + console.error('[Redis] Client error:', error); |
| 61 | + if (error) { |
| 62 | + HawkCatcher.send(error); |
| 63 | + } |
| 64 | + }); |
| 65 | + |
| 66 | + // Handle successful reconnection |
| 67 | + this.redisClient.on('ready', () => { |
| 68 | + console.log('[Redis] Client ready'); |
| 69 | + this.isReconnecting = false; |
| 70 | + }); |
| 71 | + |
| 72 | + // Handle reconnecting event |
| 73 | + this.redisClient.on('reconnecting', () => { |
| 74 | + console.log('[Redis] Client reconnecting...'); |
| 75 | + this.isReconnecting = true; |
| 76 | + }); |
| 77 | + |
| 78 | + // Handle connection end |
| 79 | + this.redisClient.on('end', () => { |
| 80 | + console.log('[Redis] Connection ended'); |
| 81 | + }); |
| 82 | + } catch (error) { |
| 83 | + console.error('[Redis] Error creating client:', error); |
| 84 | + HawkCatcher.send(error as Error); |
| 85 | + this.redisClient = null; |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Get singleton instance |
| 91 | + */ |
| 92 | + public static getInstance(): RedisHelper { |
| 93 | + if (!RedisHelper.instance) { |
| 94 | + RedisHelper.instance = new RedisHelper(); |
| 95 | + } |
| 96 | + return RedisHelper.instance; |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * Connect to Redis |
| 101 | + */ |
| 102 | + public async initialize(): Promise<void> { |
| 103 | + if (!this.redisClient) { |
| 104 | + console.warn('[Redis] Client not initialized, skipping connection'); |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + try { |
| 109 | + if (!this.redisClient.isOpen && !this.isReconnecting) { |
| 110 | + await this.redisClient.connect(); |
| 111 | + console.log('[Redis] Connected successfully'); |
| 112 | + } |
| 113 | + } catch (error) { |
| 114 | + console.error('[Redis] Connection failed:', error); |
| 115 | + HawkCatcher.send(error as Error); |
| 116 | + // Don't throw - let reconnectStrategy handle it |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + /** |
| 121 | + * Close Redis client |
| 122 | + */ |
| 123 | + public async close(): Promise<void> { |
| 124 | + if (this.redisClient?.isOpen) { |
| 125 | + await this.redisClient.quit(); |
| 126 | + console.log('[Redis] Connection closed'); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + /** |
| 131 | + * Check if Redis is connected |
| 132 | + */ |
| 133 | + public isConnected(): boolean { |
| 134 | + return Boolean(this.redisClient?.isOpen); |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Execute TS.RANGE command with aggregation |
| 139 | + * |
| 140 | + * @param key - Redis TimeSeries key |
| 141 | + * @param start - start timestamp in milliseconds |
| 142 | + * @param end - end timestamp in milliseconds |
| 143 | + * @param aggregationType - aggregation type (sum, avg, min, max, etc.) |
| 144 | + * @param bucketMs - bucket size in milliseconds |
| 145 | + * @returns Array of [timestamp, value] tuples |
| 146 | + */ |
| 147 | + public async tsRange( |
| 148 | + key: string, |
| 149 | + start: string, |
| 150 | + end: string, |
| 151 | + aggregationType: string, |
| 152 | + bucketMs: string |
| 153 | + ): Promise<TsRangeResult[]> { |
| 154 | + if (!this.redisClient) { |
| 155 | + throw new Error('Redis client not initialized'); |
| 156 | + } |
| 157 | + |
| 158 | + return (await this.redisClient.sendCommand([ |
| 159 | + 'TS.RANGE', |
| 160 | + key, |
| 161 | + start, |
| 162 | + end, |
| 163 | + 'AGGREGATION', |
| 164 | + aggregationType, |
| 165 | + bucketMs, |
| 166 | + ])) as TsRangeResult[]; |
| 167 | + } |
| 168 | +} |
0 commit comments