| 1 | import Redis, { RedisOptions } from 'ioredis'; |
| 2 | import { Injectable, OnModuleDestroy |
| 3 | import { ConfigService } |
| 4 | |
| 5 | @Injectable() |
| 6 | export class RedisService |
| 7 | private client: |
| 8 | private connectionConfig: |
| 9 | private idleTimeout: |
| 10 | private readonly IDLE_TIMEOUT_MS |
| 11 | private lastActivityTime: |
| 12 | |
| 13 | constructor(private readonly |
| 14 | // Parse Redis URL configuration |
| 15 | const redisUrl = |
| 16 | this.configService.get |
| 17 | ); |
| 18 | |
| 19 | this.connectionConfig = |
| 20 | host: redisUrl.hostname |
| 21 | port: parseInt(redisUrl |
| 22 | password: redisUrl.password |
| 23 | db: redisUrl.pathname |
| 24 | family: 0, // |
| 25 | lazyConnect: true, // |
| 26 | retryStrategy: (times) |
| 27 | // Retry with exponential backoff, max 3 seconds |
| 28 | const delay = |
| 29 | return delay; |
| 30 | }, |
| 31 | maxRetriesPerRequest: 3, |
| 32 | }; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Get or create Redis client, connecting on-demand |
| 37 | */ |
| 38 | private async getClient |
| 39 | // If client exists and is ready, return it |
| 40 | if (this.client |
| 41 | this.updateActivityTime(); |
| 42 | return this.client |
| 43 | } |
| 44 | |
| 45 | // If client exists and is reconnecting, wait for it to be ready |
| 46 | if (this.client |
| 47 | return new Promise |
| 48 | const timeout = |
| 49 | reject(new Error |
| 50 | }, 10000); // |
| 51 | |
| 52 | const onReady = |
| 53 | clearTimeout(timeout); |
| 54 | this.client!.removeListener |
| 55 | this.updateActivityTime(); |
| 56 | resolve(this.client |
| 57 | }; |
| 58 | |
| 59 | const onError = |
| 60 | clearTimeout(timeout); |
| 61 | this.client!.removeListener |
| 62 | reject(error); |
| 63 | }; |
| 64 | |
| 65 | this.client!.once |
| 66 | this.client!.once |
| 67 | }); |
| 68 | } |
| 69 | |
| 70 | // If client exists but not connected, try to reconnect |
| 71 | if (this.client |
| 72 | try { |
| 73 | // If client is in 'end' state, we need to create a new one |
| 74 | if (this.client |
| 75 | this.client.disconnect |
| 76 | this.client = |
| 77 | } else { |
| 78 | // Try to connect if not already connecting |
| 79 | if (this.client |
| 80 | await this.client |
| 81 | this.updateActivityTime(); |
| 82 | return this.client |
| 83 | } |
| 84 | } |
| 85 | } catch (error) |
| 86 | console.error('Failed to reconnect Redis client: |
| 87 | // Create new client if reconnect fails |
| 88 | if (this.client |
| 89 | this.client.disconnect |
| 90 | } |
| 91 | this.client = |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | // Create new client and connect |
| 96 | this.client = |
| 97 | |
| 98 | // Set up error handlers |
| 99 | this.client.on |
| 100 | console.error('Redis client error: |
| 101 | }); |
| 102 | |
| 103 | this.client.on |
| 104 | console.log('Redis client connected |
| 105 | }); |
| 106 | |
| 107 | this.client.on |
| 108 | console.log('Redis client disconnected |
| 109 | }); |
| 110 | |
| 111 | try { |
| 112 | await this.client |
| 113 | this.updateActivityTime(); |
| 114 | return this.client |
| 115 | } catch (error) |
| 116 | console.error('Failed to connect to Redis: |
| 117 | // Clean up on connection failure |
| 118 | if (this.client |
| 119 | this.client.disconnect |
| 120 | this.client = |
| 121 | } |
| 122 | throw error; |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /** |
| 127 | * Update last activity time and schedule idle disconnect |
| 128 | */ |
| 129 | private updateActivityTime(): |
| 130 | this.lastActivityTime = |
| 131 | |
| 132 | // Clear existing timeout |
| 133 | if (this.idleTimeout |
| 134 | clearTimeout(this.idleTimeout |
| 135 | } |
| 136 | |
| 137 | // Schedule disconnect after idle timeout |
| 138 | this.idleTimeout = |
| 139 | this.disconnectIfIdle(); |
| 140 | }, this.IDLE_TIMEOUT_MS |
| 141 | } |
| 142 | |
| 143 | /** |
| 144 | * Disconnect if client has been idle for the timeout period |
| 145 | */ |
| 146 | private async disconnectIfIdle |
| 147 | const timeSinceLastActivity = |
| 148 | |
| 149 | if (timeSinceLastActivity >= |
| 150 | console.log('Disconnecting Redis client due to inactivity |
| 151 | try { |
| 152 | await this.client |
| 153 | } catch (error) |
| 154 | console.error('Error disconnecting Redis client: |
| 155 | // Force disconnect if quit fails |
| 156 | this.client.disconnect |
| 157 | } |
| 158 | this.client = |
| 159 | this.idleTimeout = |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /** |
| 164 | * Get Redis client or null if not available |
| 165 | * This method is used by services that check for Redis availability |
| 166 | * Returns the service itself which implements the Redis interface methods |
| 167 | */ |
| 168 | getOrNil(): RedisService |
| 169 | return this; |
| 170 | } |
| 171 | |
| 172 | // Redis command methods that connect on-demand |
| 173 | |
| 174 | async get(key |
| 175 | try { |
| 176 | const client = |
| 177 | return await client |
| 178 | } catch (error) |
| 179 | console.error('Redis GET error: |
| 180 | return null; |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | async setex(key |
| 185 | try { |
| 186 | const client = |
| 187 | await client.setex |
| 188 | } catch (error) |
| 189 | console.error('Redis SETEX error: |
| 190 | throw error; |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | async del(key |
| 195 | try { |
| 196 | const client = |
| 197 | return await client |
| 198 | } catch (error) |
| 199 | console.error('Redis DEL error: |
| 200 | throw error; |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | async lrange(key |
| 205 | try { |
| 206 | const client = |
| 207 | return await client |
| 208 | } catch (error) |
| 209 | console.error('Redis LRANGE error: |
| 210 | throw error; |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | async lpush(key |
| 215 | try { |
| 216 | const client = |
| 217 | return await client |
| 218 | } catch (error) |
| 219 | console.error('Redis LPUSH error: |
| 220 | throw error; |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | async expire(key |
| 225 | try { |
| 226 | const client = |
| 227 | return await client |
| 228 | } catch (error) |
| 229 | console.error('Redis EXPIRE error: |
| 230 | throw error; |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | /** |
| 235 | * Cleanup on module destroy |
| 236 | */ |
| 237 | async onModuleDestroy(): |
| 238 | if (this.idleTimeout |
| 239 | clearTimeout(this.idleTimeout |
| 240 | this.idleTimeout = |
| 241 | } |
| 242 | |
| 243 | if (this.client |
| 244 | try { |
| 245 | await this.client |
| 246 | } catch (error) |
| 247 | console.error('Error closing Redis connection: |
| 248 | this.client.disconnect |
| 249 | } |
| 250 | this.client = |
| 251 | } |
| 252 | } |
| 253 | } |