timeout.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2020 by the contributors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package healthcheck
  15. import (
  16. "fmt"
  17. "time"
  18. )
  19. // TimeoutError is the error returned when a Timeout-wrapped Check takes too long
  20. type timeoutError time.Duration
  21. func (e timeoutError) Error() string {
  22. return fmt.Sprintf("timed out after %s", time.Duration(e).String())
  23. }
  24. // Timeout returns whether this error is a timeout (always true for timeoutError)
  25. func (e timeoutError) Timeout() bool {
  26. return true
  27. }
  28. // Temporary returns whether this error is temporary (always true for timeoutError)
  29. func (e timeoutError) Temporary() bool {
  30. return true
  31. }
  32. // Timeout adds a timeout to a Check. If the underlying check takes longer than
  33. // the timeout, it returns an error.
  34. func Timeout(check Check, timeout time.Duration) Check {
  35. return func() error {
  36. c := make(chan error, 1)
  37. go func() { c <- check() }()
  38. select {
  39. case err := <-c:
  40. return err
  41. case <-time.After(timeout):
  42. return timeoutError(timeout)
  43. }
  44. }
  45. }