add redis process time and add timeout clause

This commit is contained in:
Michael C 2022-09-07 23:43:14 -04:00
parent bd7dfc63ff
commit 9be9d05dbe
No known key found for this signature in database
GPG key ID: FFB04FB3B878B7B4
2 changed files with 33 additions and 6 deletions

View file

@ -3,25 +3,40 @@ import { Logger } from "../utils/logger";
import { Request, Response } from "express";
import os from "os";
import redis from "../utils/redis";
import { setTimeout } from "timers/promises";
export async function getStatus(req: Request, res: Response): Promise<Response> {
const startTime = Date.now();
let value = req.params.value as string[] | string;
value = Array.isArray(value) ? value[0] : value;
let processTime, redisProcessTime = -1;
const timeoutPromise = async (): Promise<string> => {
await setTimeout(5000);
return "timeout";
};
try {
const dbVersion = (await db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"])).value;
const dbVersion = await Promise.race([db.prepare("get", "SELECT key, value FROM config where key = ?", ["version"]), timeoutPromise()])
.then(e => {
if (e === "timeout") return e;
processTime = Date.now() - startTime;
return e.value;
});
let statusRequests: unknown = 0;
try {
const numberRequests = await redis.increment("statusRequest");
statusRequests = numberRequests?.[0];
} catch (error) { } // eslint-disable-line no-empty
const numberRequests = await Promise.race([redis.increment("statusRequest"), timeoutPromise()])
.then(e => {
if (e === "timeout") return [-1];
redisProcessTime = Date.now() - startTime;
return e;
});
statusRequests = numberRequests?.[0];
const statusValues: Record<string, any> = {
uptime: process.uptime(),
commit: (global as any).HEADCOMMIT || "unknown",
db: Number(dbVersion),
startTime,
processTime: Date.now() - startTime,
processTime,
redisProcessTime,
loadavg: os.loadavg().slice(1), // only return 5 & 15 minute load average
statusRequests,
hostname: os.hostname()

View file

@ -110,4 +110,16 @@ describe("getStatus", () => {
})
.catch(err => done(err));
});
it("Should be able to get redis latency", function (done) {
if (!config.redis?.enabled) this.skip();
client.get(endpoint)
.then(res => {
assert.strictEqual(res.status, 200);
const data = res.data;
assert.ok(data.redisProcessTime >= 0);
done();
})
.catch(err => done(err));
});
});