-
Notifications
You must be signed in to change notification settings - Fork 3
/
policy.go
84 lines (72 loc) · 1.74 KB
/
policy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package client
import (
"net/http"
"strings"
)
// RetryPolicy configures a RetryWrapper's logic
// to determine when a HTTP request is retryable.
type RetryPolicy interface {
// IsErrorRetryable determines which url.Error
// instances can be retried.
IsErrorRetryable(error) bool
// IsStatusRetryableForMethod accepts a HTTP method
// name and a status code and returns 'true' if a
// given combination of the aforementioned parameters
// should be retried.
IsStatusRetryableForMethod(string, int) bool
}
// NewDefaultRetryPolicy returns the default retry policy
// implementation.
func NewDefaultRetryPolicy() DefaultRetryPolicy {
return DefaultRetryPolicy{}
}
type DefaultRetryPolicy struct{}
func (p DefaultRetryPolicy) IsErrorRetryable(err error) bool {
if err == nil {
return true
}
switch msg := err.Error(); {
case msgInRetryPatterns(msg):
return true
default:
return false
}
}
func (p DefaultRetryPolicy) IsStatusRetryableForMethod(method string, code int) bool {
switch code {
case http.StatusRequestTimeout, // 408
http.StatusTooManyRequests, // 429
http.StatusServiceUnavailable: // 503
return true
case http.StatusInternalServerError, // 500
http.StatusBadGateway, // 502
http.StatusGatewayTimeout: // 504
return isMethodIdempotent(method)
default:
return false
}
}
func msgInRetryPatterns(msg string) bool {
retryPatterns := []string{
"connection refused",
"connection reset",
"EOF",
"PROTOCOL_ERROR",
"REFUSED_STREAM",
}
for _, pat := range retryPatterns {
if !strings.Contains(msg, pat) {
continue
}
return true
}
return false
}
func isMethodIdempotent(method string) bool {
switch method {
case http.MethodPost, http.MethodPatch:
return false
default:
return true
}
}