From 1ca42fe92ed513b149765e37a1b778e39eb15d40 Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Tue, 7 Nov 2023 22:44:34 -0500 Subject: [PATCH] add 1s cache to `/health` --- src/fetch/health.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/fetch/health.ts b/src/fetch/health.ts index 35e12a5..8a82b40 100644 --- a/src/fetch/health.ts +++ b/src/fetch/health.ts @@ -2,16 +2,32 @@ import client from "../clickhouse/createClient.js"; import { logger } from "../logger.js"; import { BadRequest, toText } from "./cors.js"; +function now() { + return Math.floor(Date.now() / 1000); // seconds +} + +// cache the timestamp and value for 1 seconds +let timestamp = now(); +let value = true; // true = OK, false = ERROR + export default async function () { + // return cached response if timestamp is less than 1 second old + if ( now() - timestamp < 1 ) { + return value ? toText("OK") : BadRequest; + } + try { const response = await client.ping(); if (!response.success) { throw new Error(response.error.message); } - + timestamp = now(); + value = true; return toText("OK"); } catch (e) { logger.error(e); + timestamp = now(); + value = false; return BadRequest; } }