healthcheck.go 1.5 KB

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