diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index d7b5ba1c..12a042ff 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -6,7 +6,8 @@ import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify'; import Fastify from 'fastify'; import metricsPlugin from 'fastify-metrics'; -import { db } from '@openpanel/db'; +import { round } from '@openpanel/common'; +import { chQuery, db } from '@openpanel/db'; import type { IServiceClient } from '@openpanel/db'; import { eventsQueue } from '@openpanel/queue'; import { redis, redisPub } from '@openpanel/redis'; @@ -27,6 +28,12 @@ declare module 'fastify' { } } +async function withTimings(promise: Promise) { + const time = performance.now(); + const res = await promise; + return [round(performance.now() - time, 2), res] as const; +} + const port = parseInt(process.env.API_PORT || '3000', 10); const startServer = async () => { @@ -83,15 +90,30 @@ const startServer = async () => { }); fastify.get('/healthcheck', async (request, reply) => { try { - const [redisRes, dbRes, queueRes] = await Promise.all([ - redis.keys('*'), - db.project.findFirst(), - eventsQueue.getCompleted(), - ]); + const redisRes = await withTimings(redis.keys('*')); + const dbRes = await withTimings(db.project.findFirst()); + const queueRes = await withTimings(eventsQueue.getCompleted()); + const chRes = await withTimings( + chQuery('SELECT * FROM events LIMIT 1') + ); + reply.send({ - redis: redisRes.length > 0, - db: dbRes ? true : false, - queue: queueRes.length > 0, + redis: { + ok: redisRes[1].length ? true : false, + time: `${redisRes[0]}ms`, + }, + db: { + ok: dbRes[1] ? true : false, + time: `${dbRes[0]}ms`, + }, + queue: { + ok: queueRes[1].length ? true : false, + time: `${queueRes[0]}ms`, + }, + ch: { + ok: chRes[1].length ? true : false, + time: `${chRes[0]}ms`, + }, }); } catch (e) { reply.status(500).send();