blob: 445131caee596ff3fe323c720557c4075455a982 [file] [log] [blame]
Takahiro Suzuki241c10e2020-12-17 20:17:57 +09001package metrics
2
3// Healthchecks hold an error value describing an arbitrary up/down status.
4type Healthcheck interface {
5 Check()
6 Error() error
7 Healthy()
8 Unhealthy(error)
9}
10
11// NewHealthcheck constructs a new Healthcheck which will use the given
12// function to update its status.
13func NewHealthcheck(f func(Healthcheck)) Healthcheck {
14 if UseNilMetrics {
15 return NilHealthcheck{}
16 }
17 return &StandardHealthcheck{nil, f}
18}
19
20// NilHealthcheck is a no-op.
21type NilHealthcheck struct{}
22
23// Check is a no-op.
24func (NilHealthcheck) Check() {}
25
26// Error is a no-op.
27func (NilHealthcheck) Error() error { return nil }
28
29// Healthy is a no-op.
30func (NilHealthcheck) Healthy() {}
31
32// Unhealthy is a no-op.
33func (NilHealthcheck) Unhealthy(error) {}
34
35// StandardHealthcheck is the standard implementation of a Healthcheck and
36// stores the status and a function to call to update the status.
37type StandardHealthcheck struct {
38 err error
39 f func(Healthcheck)
40}
41
42// Check runs the healthcheck function to update the healthcheck's status.
43func (h *StandardHealthcheck) Check() {
44 h.f(h)
45}
46
47// Error returns the healthcheck's status, which will be nil if it is healthy.
48func (h *StandardHealthcheck) Error() error {
49 return h.err
50}
51
52// Healthy marks the healthcheck as healthy.
53func (h *StandardHealthcheck) Healthy() {
54 h.err = nil
55}
56
57// Unhealthy marks the healthcheck as unhealthy. The error is stored and
58// may be retrieved by the Error method.
59func (h *StandardHealthcheck) Unhealthy(err error) {
60 h.err = err
61}