Matteo Scandolo | 9a2772a | 2018-11-19 14:56:26 -0800 | [diff] [blame] | 1 | package metrics |
| 2 | |
| 3 | // Healthchecks hold an error value describing an arbitrary up/down status. |
| 4 | type 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. |
| 13 | func 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. |
| 21 | type NilHealthcheck struct{} |
| 22 | |
| 23 | // Check is a no-op. |
| 24 | func (NilHealthcheck) Check() {} |
| 25 | |
| 26 | // Error is a no-op. |
| 27 | func (NilHealthcheck) Error() error { return nil } |
| 28 | |
| 29 | // Healthy is a no-op. |
| 30 | func (NilHealthcheck) Healthy() {} |
| 31 | |
| 32 | // Unhealthy is a no-op. |
| 33 | func (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. |
| 37 | type StandardHealthcheck struct { |
| 38 | err error |
| 39 | f func(Healthcheck) |
| 40 | } |
| 41 | |
| 42 | // Check runs the healthcheck function to update the healthcheck's status. |
| 43 | func (h *StandardHealthcheck) Check() { |
| 44 | h.f(h) |
| 45 | } |
| 46 | |
| 47 | // Error returns the healthcheck's status, which will be nil if it is healthy. |
| 48 | func (h *StandardHealthcheck) Error() error { |
| 49 | return h.err |
| 50 | } |
| 51 | |
| 52 | // Healthy marks the healthcheck as healthy. |
| 53 | func (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. |
| 59 | func (h *StandardHealthcheck) Unhealthy(err error) { |
| 60 | h.err = err |
| 61 | } |