11import { createClient } from "redis" ;
22
33let redisClient ;
4+ let redisErrorCount = 0 ;
5+
6+ function getRedisConnectTimeoutMs ( env = process . env ) {
7+ const raw = Number . parseInt ( String ( env . REDIS_CONNECT_TIMEOUT_MS || "4000" ) , 10 ) ;
8+ if ( ! Number . isFinite ( raw ) || raw <= 0 ) return 4000 ;
9+ return raw ;
10+ }
411
512export function getRedisClient ( {
613 redisUrl = process . env . REDIS_URL ,
714 clientFactory = createClient ,
815} = { } ) {
916 if ( ! redisClient ) {
10- redisClient = clientFactory ( { url : redisUrl } ) ;
17+ redisClient = clientFactory ( {
18+ url : redisUrl ,
19+ socket : {
20+ connectTimeout : getRedisConnectTimeoutMs ( ) ,
21+ // Prevent endless reconnect loops when Redis URL is invalid/unreachable.
22+ reconnectStrategy : ( ) => false ,
23+ } ,
24+ } ) ;
1125 redisClient . on ( "error" , ( err ) => {
12- console . error ( "Redis client error:" , err . message ) ;
26+ redisErrorCount += 1 ;
27+ const suffix = err ?. message ? ` ${ err . message } ` : "" ;
28+ if ( redisErrorCount <= 3 ) {
29+ console . error ( "Redis client error:" + suffix ) ;
30+ } else if ( redisErrorCount === 4 ) {
31+ console . error ( "Redis client error: suppressing repeated logs" ) ;
32+ }
1333 } ) ;
1434 }
1535 return redisClient ;
@@ -18,7 +38,18 @@ export function getRedisClient({
1838export async function connectRedisClient ( options ) {
1939 const client = getRedisClient ( options ) ;
2040 if ( ! client . isOpen ) {
21- await client . connect ( ) ;
41+ const timeoutMs = getRedisConnectTimeoutMs ( ) ;
42+ const timeout = new Promise ( ( _ , reject ) => {
43+ setTimeout ( ( ) => reject ( new Error ( `Redis connection timed out after ${ timeoutMs } ms` ) ) , timeoutMs ) ;
44+ } ) ;
45+ try {
46+ await Promise . race ( [ client . connect ( ) , timeout ] ) ;
47+ } catch ( err ) {
48+ try {
49+ client . disconnect ( ) ;
50+ } catch { }
51+ throw err ;
52+ }
2253 }
2354 return client ;
2455}
@@ -91,4 +122,4 @@ export async function invalidatePaymentCache(client, id) {
91122 } catch ( err ) {
92123 console . error ( "Redis DEL error:" , err . message ) ;
93124 }
94- }
125+ }
0 commit comments