99 REDIS_URL ,
1010 CACHE_LIFETIME_IN_SECONDS ,
1111 CACHE_QUERY_LOGGING_THRESHOLD_MS ,
12+ CACHE_RETRIEVAL_TIMEOUT_MS ,
1213} = config
1314
1415const isTest = NODE_ENV === "test"
@@ -40,13 +41,13 @@ function createRedisClient() {
4041 // End reconnecting on a specific error and flush all commands with a
4142 // individual error.
4243 if ( options . error . code === "ECONNREFUSED" ) {
43- return new Error ( "The server refused the connection" )
44+ return new Error ( "[Cache] The server refused the connection" )
4445 }
4546 }
4647 // End reconnecting after a specific timeout and flush all commands with a
4748 // individual error.
4849 if ( options . total_retry_time > 1000 * 60 * 60 ) {
49- return new Error ( "Retry time exhausted" )
50+ return new Error ( "[Cache] Retry time exhausted" )
5051 }
5152 // End reconnecting with built in error.
5253 if ( options . attempt > 10 ) {
@@ -61,7 +62,7 @@ function createRedisClient() {
6162 }
6263 client . on ( "error" , error )
6364 VerboseEvents . forEach ( event => {
64- client . on ( event , ( ) => verbose ( `Redis: ${ event } ` ) )
65+ client . on ( event , ( ) => verbose ( `[Cache] ${ event } ` ) )
6566 } )
6667 return client
6768}
@@ -71,16 +72,37 @@ export const client = isTest ? createMockClient() : createRedisClient()
7172export default {
7273 get : key => {
7374 return new Promise ( ( resolve , reject ) => {
74- if ( isNull ( client ) ) return reject ( new Error ( "Cache client is `null`" ) )
75+ if ( isNull ( client ) ) return reject ( new Error ( "[Cache] `client` is `null`" ) )
76+
77+ let timeoutId = setTimeout ( ( ) => {
78+ timeoutId = null
79+ const err = new Error ( `[Cache#get] Timeout for key ${ key } ` )
80+ error ( err )
81+ reject ( err )
82+ } , CACHE_RETRIEVAL_TIMEOUT_MS )
83+
7584 const start = Date . now ( )
7685 client . get ( key , ( err , data ) => {
7786 const time = Date . now ( ) - start
7887 if ( time > CACHE_QUERY_LOGGING_THRESHOLD_MS ) {
79- error ( `Slow Cache#Get: ${ time } ms` )
88+ error ( `[Cache#get] Slow read of ${ time } ms for key ${ key } ` )
89+ }
90+
91+ if ( timeoutId ) {
92+ clearTimeout ( timeoutId )
93+ } else {
94+ // timed out and already rejected promise, no need to continue
95+ return
96+ }
97+
98+ if ( err ) {
99+ error ( err )
100+ reject ( err )
101+ } else if ( data ) {
102+ resolve ( JSON . parse ( data ) )
103+ } else {
104+ reject ( new Error ( "[Cache#get] Cache miss" ) )
80105 }
81- if ( err ) return reject ( err )
82- if ( data ) return resolve ( JSON . parse ( data ) )
83- reject ( new Error ( "cache#get did not return `data`" ) )
84106 } )
85107 } )
86108 } ,
0 commit comments