Skip to content

Commit fa0e077

Browse files
committed
add timeout to redis commands so that the health api endpoint will return a value
1 parent dac3c9b commit fa0e077

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

lib/api/health.js

+15-4
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ module.exports = (db, server, loggelf) => {
7575

7676
// 3) test redis PING
7777
try {
78-
await db.redis.ping();
78+
// Redis might try to reconnect causing a situation where given ping() command might never return a value, add a fixed timeout
79+
await promiseRaceTimeoutWrapper(db.redis.ping(), 10000);
7980
} catch (err) {
8081
loggelf({
8182
short_message: '[HEALTH] Redis is down. PING to Redis failed.'
@@ -90,14 +91,15 @@ module.exports = (db, server, loggelf) => {
9091

9192
// 4) test if redis is writeable
9293
try {
93-
await db.redis.hset('health', `${currentTimestamp}`, `${currentTimestamp}`);
94-
const data = await db.redis.hget(`health`, `${currentTimestamp}`);
94+
await promiseRaceTimeoutWrapper(db.redis.hset('health', `${currentTimestamp}`, `${currentTimestamp}`), 10000);
95+
96+
const data = await promiseRaceTimeoutWrapper(db.redis.hget(`health`, `${currentTimestamp}`), 10000);
9597

9698
if (data !== `${currentTimestamp}`) {
9799
throw Error('Received data is not the same!');
98100
}
99101

100-
await db.redis.hdel('health', `${currentTimestamp}`);
102+
await promiseRaceTimeoutWrapper(db.redis.hdel('health', `${currentTimestamp}`), 10000);
101103
} catch (err) {
102104
loggelf({
103105
short_message:
@@ -116,3 +118,12 @@ module.exports = (db, server, loggelf) => {
116118
})
117119
);
118120
};
121+
122+
async function promiseRaceTimeoutWrapper(promise, timeout) {
123+
return Promise.race([
124+
promise,
125+
new Promise((_resolve, reject) => {
126+
setTimeout(() => reject(new Error('Async call timed out!')), timeout);
127+
})
128+
]);
129+
}

0 commit comments

Comments
 (0)