-
-
Notifications
You must be signed in to change notification settings - Fork 637
/
index.ts
98 lines (86 loc) · 2.7 KB
/
index.ts
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { ApplicationContract } from '@ioc:Adonis/Core/Application'
import { parseIocReference, callIocReference } from '@poppinss/utils'
import { HealthCheckContract, Checker, HealthReport, HealthReportEntry } from '@ioc:Adonis/Core/HealthCheck'
/**
* The module exposes the API to find the health, liveliness and readiness of
* the system. You can also add your own checkers.
*/
export class HealthCheck implements HealthCheckContract {
/**
* A copy of custom checkers
*/
private _healthCheckers: { [service: string]: Checker } = {}
constructor (private _application: ApplicationContract) {}
/**
* Invokes a given checker to collect the report metrics.
*/
private async _invokeChecker (
service: string,
reportSheet: HealthReport,
): Promise<boolean> {
const checker = this._healthCheckers[service]
let report: HealthReportEntry
try {
if (typeof (checker) === 'function') {
report = await checker()
} else {
report = await callIocReference(parseIocReference(`${checker}.report`), [])
}
} catch (error) {
report = {
health: { healthy: false, message: error.message },
meta: { fatal: true },
}
}
reportSheet[service] = report
return report.health.healthy
}
/**
* A boolean to know, if all health checks have passed
* or not.
*/
public async isLive (): Promise<boolean> {
if (!this.isReady()) {
return false
}
const { healthy } = await this.report()
return healthy
}
/**
* Add a custom checker to check a given service connectivity
* with the server
*/
public addChecker (service: string, checker: Checker) {
this._healthCheckers[service] = checker
}
/**
* Ensure that application is ready and is not shutting
* down. This relies on the application module.
*/
public isReady () {
return this._application.isReady && !this._application.isShuttingDown
}
/**
* Returns the health check reports. The health checks are performed when
* this method is invoked.
*/
public async report (): Promise<{ healthy: boolean, report: HealthReport }> {
const report: HealthReport = {}
await Promise.all(Object.keys(this._healthCheckers).map((service) => {
return this._invokeChecker(service, report)
}))
/**
* Finding unhealthy service to know if system is healthy or not
*/
const unhealthyService = Object.keys(report).find((service) => !report[service].health.healthy)
return { healthy: !unhealthyService, report }
}
}