-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstartupHealthcheckPlugin.ts
More file actions
79 lines (69 loc) · 2.52 KB
/
startupHealthcheckPlugin.ts
File metadata and controls
79 lines (69 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { type Either, isError } from '@lokalise/node-core'
import type { FastifyPluginCallback } from 'fastify'
import fp from 'fastify-plugin'
import { stdSerializers } from 'pino'
import { type HealthCheck, resolveHealthcheckResults } from './commonHealthcheckPlugin.js'
import type { HealthChecker } from './healthcheckCommons.js'
async function executeHealthCheck(
checker: HealthChecker,
app: Parameters<HealthChecker>[0],
): Promise<Either<Error, true>> {
try {
return await checker(app)
} catch (err) {
return { error: isError(err) ? err : new Error(String(err)) }
}
}
export interface StartupHealthcheckPluginOptions {
resultsLogLevel?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'
healthChecks: readonly HealthCheck[]
}
const plugin: FastifyPluginCallback<StartupHealthcheckPluginOptions> = (app, opts, done) => {
app.addHook('onReady', async () => {
let isFullyHealthy = true
let isPartiallyHealthy = false
let healthChecks: Record<string, string> = {}
const failedHealthchecks: string[] = []
if (opts.healthChecks.length) {
const results = await Promise.all(
opts.healthChecks.map(async (healthcheck) => {
const result = await executeHealthCheck(healthcheck.checker, app)
if (result.error) {
app.log.error(
{
error: stdSerializers.err(result.error),
},
`${healthcheck.name} healthcheck has failed`,
)
}
if (result.error) {
failedHealthchecks.push(healthcheck.name)
}
return {
name: healthcheck.name,
result,
isMandatory: healthcheck.isMandatory,
}
}),
)
const resolvedHealthcheckResponse = resolveHealthcheckResults(results, opts)
healthChecks = resolvedHealthcheckResponse.healthChecks
isFullyHealthy = resolvedHealthcheckResponse.isFullyHealthy
isPartiallyHealthy = resolvedHealthcheckResponse.isPartiallyHealthy
}
const heartbeat = isFullyHealthy ? 'HEALTHY' : isPartiallyHealthy ? 'PARTIALLY_HEALTHY' : 'FAIL'
const resultLog = {
heartbeat,
checks: healthChecks,
}
app.log[opts.resultsLogLevel ?? 'info'](resultLog, 'Healthcheck finished')
if (!isPartiallyHealthy && !isFullyHealthy) {
throw new Error(`Healthchecks failed: ${JSON.stringify(failedHealthchecks)}`)
}
})
done()
}
export const startupHealthcheckPlugin = fp(plugin, {
fastify: '5.x',
name: 'startup-healthcheck-plugin',
})