Debian Codegraph @

retrier.go

raw
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
5 package elastic
6
7 import (
8 "context"
9 "net/http"
10 "time"
11 )
12
13 // RetrierFunc specifies the signature of a Retry function.
14 type RetrierFunc func(context.Context, int, *http.Request, *http.Response, error) (time.Duration, bool, error)
15
16 // Retrier decides whether to retry a failed HTTP request with Elasticsearch.
17 type Retrier interface {
18 // Retry is called when a request has failed. It decides whether to retry
19 // the call, how long to wait for the next call, or whether to return an
20 // error (which will be returned to the service that started the HTTP
21 // request in the first place).
22 //
23 // Callers may also use this to inspect the HTTP request/response and
24 // the error that happened. Additional data can be passed through via
25 // the context.
26 Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error)
27 }
28
29 // -- StopRetrier --
30
31 // StopRetrier is an implementation that does no retries.
32 type StopRetrier struct {
33 }
34
35 // NewStopRetrier returns a retrier that does no retries.
36 func NewStopRetrier() *StopRetrier {
37 return &StopRetrier{}
38 }
39
40 // Retry does not retry.
41 func (r *StopRetrier) Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error) {
42 return 0, false, nil
43 }
44
45 // -- BackoffRetrier --
46
47 // BackoffRetrier is an implementation that does nothing but return nil on Retry.
48 type BackoffRetrier struct {
49 backoff Backoff
50 }
51
52 // NewBackoffRetrier returns a retrier that uses the given backoff strategy.
53 func NewBackoffRetrier(backoff Backoff) *BackoffRetrier {
54 return &BackoffRetrier{backoff: backoff}
55 }
56
57 // Retry calls into the backoff strategy and its wait interval.
58 func (r *BackoffRetrier) Retry(ctx context.Context, retry int, req *http.Request, resp *http.Response, err error) (time.Duration, bool, error) {
59 wait, goahead := r.backoff.Next(retry)
60 return wait, goahead, nil
61 }