| 5 | import { isShuttingDown } from '@/utils/graceful-shutdown'; |
| 6 | |
| 7 | export async function healthcheck( |
| 8 | request: FastifyRequest, |
| 9 | reply: FastifyReply |
| 10 | ) { |
| 11 | const [redisResult, dbResult, chResult] = await Promise.all([ |
| 12 | tryCatch(async () => (await getRedisCache().ping()) === 'PONG'), |
| 13 | tryCatch(async () => !!(await db.$executeRaw`SELECT 1`)), |
| 14 | tryCatch(async () => (await chQuery('SELECT 1')).length > 0), |
| 15 | ]); |
| 16 | |
| 17 | const dependencies = { |
| 18 | redis: redisResult.ok && redisResult.data, |
| 19 | db: dbResult.ok && dbResult.data, |
| 20 | ch: chResult.ok && chResult.data, |
| 21 | }; |
| 22 | const dependencyErrors = { |
| 23 | redis: redisResult.error?.message, |
| 24 | db: dbResult.error?.message, |
| 25 | ch: chResult.error?.message, |
| 26 | }; |
| 27 | |
| 28 | const failedDependencies = Object.entries(dependencies) |
| 29 | .filter(([, ok]) => !ok) |
| 30 | .map(([name]) => name); |
| 31 | const workingDependencies = Object.entries(dependencies) |
| 32 | .filter(([, ok]) => ok) |
| 33 | .map(([name]) => name); |
| 34 | |
| 35 | const status = failedDependencies.length === 0 ? 200 : 503; |
| 36 | |
| 37 | if (status === 200) { |
| 38 | request.log.debug( |
| 39 | { |
| 40 | workingDependencies, |
| 41 | failedDependencies, |
| 42 | dependencies, |
| 43 | }, |
| 44 | 'healthcheck passed' |
| 45 | ); |
| 46 | } else { |
| 47 | request.log.warn( |
| 48 | { |
| 49 | workingDependencies, |
| 50 | failedDependencies, |
| 51 | dependencies, |
| 52 | dependencyErrors, |
| 53 | }, |
| 54 | 'healthcheck failed' |
| 55 | ); |
| 56 | } |
| 57 | |
| 58 | return reply.status(status).send({ |
| 59 | ready: status === 200, |
| 60 | ...dependencies, |
| 61 | failedDependencies, |
| 62 | workingDependencies, |
| 63 | }); |
| 64 | } |