From 325730df6eb62cc3f968b629885a03211873671d Mon Sep 17 00:00:00 2001 From: SepehrGanji Date: Tue, 27 Feb 2024 17:44:04 -0700 Subject: [PATCH] finialize healthChecks --- src/block-watcher.ts | 9 +++++++++ src/health-check.ts | 30 +++++++++++++----------------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/block-watcher.ts b/src/block-watcher.ts index 3ef62e6..bdd9392 100644 --- a/src/block-watcher.ts +++ b/src/block-watcher.ts @@ -6,9 +6,12 @@ class BlockWatcher { private _lastBlockHeight!: number; private _timer!: NodeJS.Timeout; + private _healthy: boolean; + constructor() { this._callbacks = []; this._lastBlockHeight = 0; + this._healthy = true; } public onNewBlock(callback: (height?: number) => void): BlockWatcher { @@ -45,6 +48,7 @@ class BlockWatcher { repository .getMaxHeight() .then((height) => { + this._healthy = true; if (!height || this._lastBlockHeight >= height) { return; } @@ -57,10 +61,15 @@ class BlockWatcher { this._notify(height); }) .catch((e) => { + this._healthy = true; this._notify(); console.error(e); }); } + + public isHealthy(): boolean { + return this._healthy; + } } export const blockWatcher = new BlockWatcher(); diff --git a/src/health-check.ts b/src/health-check.ts index 940986e..8cb5609 100644 --- a/src/health-check.ts +++ b/src/health-check.ts @@ -1,35 +1,31 @@ +import { blockWatcher } from "./block-watcher"; import { redisClient } from "./caching"; import { DatabaseContext } from "./context/database-context"; +import { nodeService } from "./services"; -export const checkHealth = async(dataContext: DatabaseContext): Promise => { - /** - * Things to check: - * - Database connection (Done) - * - Redis connection (Done) - * - Node connection - * - Block watcher - */ - +export const checkHealth = async (dataContext: DatabaseContext): Promise => { const checks = { - db: () => dataContext.checkConnection, - redis: async() => (await redisClient.mget("test")).length === 1, + db: () => () => dataContext.checkConnection, + redis: async () => (await redisClient.mget("test")).length === 1, + node: async () => (await nodeService.getNodeInfo()).status === 200, + blockWatcher: () => blockWatcher.isHealthy() }; const results = await Promise.all( Object.entries(checks).map(async ([key, func]) => ({ - [key]: await func(), + [key]: await func() })) ); let isAnyFailed = false; - for(const result of results) { - for(const [key, value] of Object.entries(result)) { - if(!value) { - console.error(`🚫 Health check failed for ${key}`); + for (const result of results) { + for (const [key, value] of Object.entries(result)) { + if (!value) { + console.error(`🚫 ${key} is not healthy.`); isAnyFailed = true; } } } - if(isAnyFailed) throw new Error("Health check failed"); + if (isAnyFailed) throw new Error("Service is unhealthy."); };