retrier.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2012-present Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. import (
  6. "context"
  7. "net/http"
  8. "time"
  9. )
  10. // RetrierFunc specifies the signature of a Retry function.
  11. type RetrierFunc func(context.Context, int, *http.Request, *http.Response, error) (time.Duration, bool, error)
  12. // Retrier decides whether to retry a failed HTTP request with Elasticsearch.
  13. type Retrier interface {
  14. // Retry is called when a request has failed. It decides whether to retry
  15. // the call, how long to wait for the next call, or whether to return an
  16. // error (which will be returned to the service that started the HTTP
  17. // request in the first place).
  18. //
  19. // Callers may also use this to inspect the HTTP request/response and
  20. // the error that happened. Additional data can be passed through via
  21. // the context.
  22. Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error)
  23. }
  24. // -- StopRetrier --
  25. // StopRetrier is an implementation that does no retries.
  26. type StopRetrier struct {
  27. }
  28. // NewStopRetrier returns a retrier that does no retries.
  29. func NewStopRetrier() *StopRetrier {
  30. return &StopRetrier{}
  31. }
  32. // Retry does not retry.
  33. func (r *StopRetrier) Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error) {
  34. return 0, false, nil
  35. }
  36. // -- BackoffRetrier --
  37. // BackoffRetrier is an implementation that does nothing but return nil on Retry.
  38. type BackoffRetrier struct {
  39. backoff Backoff
  40. }
  41. // NewBackoffRetrier returns a retrier that uses the given backoff strategy.
  42. func NewBackoffRetrier(backoff Backoff) *BackoffRetrier {
  43. return &BackoffRetrier{backoff: backoff}
  44. }
  45. // Retry calls into the backoff strategy and its wait interval.
  46. func (r *BackoffRetrier) Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error) {
  47. wait, goahead := r.backoff.Next(retry)
  48. return wait, goahead, nil
  49. }