-
Notifications
You must be signed in to change notification settings - Fork 0
/
health.ts
91 lines (73 loc) · 2.1 KB
/
health.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
import { injectable } from 'inversify';
import { Logger } from './logger';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/skip';
import { BehaviorSubject } from 'rxjs';
interface HealthChecks {
[s: string]: BehaviorSubject<boolean>;
}
@injectable()
export class HealthManager {
private checks: HealthChecks = {};
private _health = false;
constructor(private logger: Logger) { }
public registerCheck(name: string, check: BehaviorSubject<boolean>) {
if (this.checks[name]) {
throw new Error(`Health check with name: ${name} already exists`);
}
this.logger.debug(`Registering new healthcheck: ${name}`);
this.checks[name] = check;
// Check the health
this.determineHealth();
// Skip the initial status no need to log that
check
.skip(1)
.distinctUntilChanged()
.subscribe((status: boolean) => {
if (status === true) {
this.logger.info(`Health check: ${name} became healthy`);
this.determineHealth();
} else {
this.logger.warn(`Health check: ${name} became unhealthy`);
this.healthy = false;
}
});
}
get healthy() {
return this._health;
}
set healthy(status: boolean) {
if (status !== this._health) {
this._health = status;
if (status === false) {
this.logger.warn('Service became unhealthy');
} else {
this.logger.info('Service became healthy');
}
}
}
get numberOfChecks() {
return Object.keys(this.checks).length;
}
public getReport() {
const report: any = {};
for (const check in this.checks) {
if (this.checks.hasOwnProperty(check)) {
report[check] = this.checks[check].getValue() ? 'healthy' : 'unhealthy';
}
}
return report;
}
private determineHealth() {
let status = true;
const keys = Object.keys(this.checks);
for (let i = 0, len = keys.length; i < len; i++) {
const checkStatus = this.checks[keys[i]].getValue();
if (checkStatus === false) {
status = false;
break;
}
}
this.healthy = status;
}
}