Skip to content

Commit

Permalink
finialize healthChecks
Browse files Browse the repository at this point in the history
  • Loading branch information
SepehrGanji committed Feb 28, 2024
1 parent 1d23b62 commit 325730d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 17 deletions.
9 changes: 9 additions & 0 deletions src/block-watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -45,6 +48,7 @@ class BlockWatcher {
repository
.getMaxHeight()
.then((height) => {
this._healthy = true;
if (!height || this._lastBlockHeight >= height) {
return;
}
Expand All @@ -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();
30 changes: 13 additions & 17 deletions src/health-check.ts
Original file line number Diff line number Diff line change
@@ -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<void> => {
/**
* Things to check:
* - Database connection (Done)
* - Redis connection (Done)
* - Node connection
* - Block watcher
*/

export const checkHealth = async (dataContext: DatabaseContext): Promise<void> => {
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.");
};

0 comments on commit 325730d

Please sign in to comment.