/
resources.go
191 lines (173 loc) · 5.65 KB
/
resources.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package hedgehog
import (
"fmt"
"math"
"net/http"
"regexp"
"sort"
"sync"
"sync/atomic"
"time"
)
// ErrResourceUnexpectedResponseCode defines resource response check error that is returned on non matching response code.
type ErrResourceUnexpectedResponseCode struct {
StatusCode int
}
func (err ErrResourceUnexpectedResponseCode) Error() string {
return fmt.Sprintf("resource check failed: received unexpected response status code %d", err.StatusCode)
}
// Resource defines abstract http resource that is capable of:
// - matching http request applicability
// - checking http request validity
// - and returning delay which should be accounted before executing this resource request
type Resource interface {
After() <-chan time.Time
Match(*http.Request) bool
Check(*http.Response) error
Hook(*http.Request) func(*http.Response)
}
type static struct {
method string
url *regexp.Regexp
delay time.Duration
codes map[int]bool
}
// NewResourceStatic returns new resource instance that always waits for static specified delay.
// Returned resource matches each request against both provided http method and full url regexp.
// Returned resource checks if response result http code is included in provided allowed codes,
// if it is not it returnes `ErrResourceUnexpectedResponseCode`.
func NewResourceStatic(method string, url *regexp.Regexp, delay time.Duration, allowedCodes ...int) Resource {
rs := static{
method: method,
url: url,
delay: delay,
codes: make(map[int]bool, len(allowedCodes)),
}
for _, code := range allowedCodes {
rs.codes[code] = true
}
return rs
}
func (r static) After() <-chan time.Time {
return time.After(r.delay)
}
func (r static) Match(req *http.Request) bool {
if r.method != req.Method {
return false
}
if r.url != nil && !r.url.MatchString(req.URL.String()) {
return false
}
return true
}
func (r static) Check(resp *http.Response) error {
if !r.codes[resp.StatusCode] {
return ErrResourceUnexpectedResponseCode{StatusCode: resp.StatusCode}
}
return nil
}
func (r static) Hook(*http.Request) func(*http.Response) {
return func(*http.Response) {}
}
type average struct {
static
sum int64
count int64
capacity int64
}
// NewResourceAverage returns new resource instance that dynamically adjusts wait delay based on
// received successful responses average delays.
// Returned resource is starting to use dynamically adjusted wait delay only after capacity/4 calls.
// Returned resource matches each request against both provided http method and full url regexp.
// Returned resource checks if response result http code is included in provided allowed codes,
// if it is not it returnes `ErrResourceUnexpectedResponseCode`.
func NewResourceAverage(method string, url *regexp.Regexp, delay time.Duration, capacity int, allowedCodes ...int) Resource {
if capacity < 0 {
capacity = math.MaxInt16
}
return &average{
static: NewResourceStatic(method, url, delay, allowedCodes...).(static),
capacity: int64(capacity),
}
}
func (r *average) After() <-chan time.Time {
delay := r.delay
count := atomic.LoadInt64(&r.count)
if count >= r.capacity {
delay = time.Duration(atomic.LoadInt64(&r.sum) / count)
}
return time.After(delay)
}
func (r *average) Hook(*http.Request) func(*http.Response) {
t := time.Now()
return func(*http.Response) {
d := time.Since(t)
oldval := atomic.LoadInt64(&r.sum)
newval := atomic.AddInt64(&r.sum, int64(d))
count := atomic.AddInt64(&r.count, 1)
// in case of overflow:
// - calculate average value on capacity+1
// - replace current sum and count with it
if newval < 0 || count > r.capacity*2 {
val := oldval / count * (r.capacity + 1)
atomic.StoreInt64(&r.sum, val)
atomic.StoreInt64(&r.count, r.capacity+1)
}
}
}
type percentiles struct {
static
percentile float64
capacity int64
latencies []time.Duration
lock sync.RWMutex
}
// NewResourcePercentiles returns new resource instance that dynamically adjusts wait delay based on
// received successful responses delays percentiles.
// Returned resource is starting to use dynamically adjusted wait delay only after capacity/2 calls,
// if more than provided capacity calls were received, first half of delay percentiles buffer will be flushed.
// Returned resource matches each request against both provided http method and full url regexp.
// Returned resource checks if response result http code is included in provided allowed codes,
// if it is not it returnes `ErrResourceUnexpectedResponseCode`.
func NewResourcePercentiles(method string, url *regexp.Regexp, delay time.Duration, percentile float64, capacity int, allowedCodes ...int) Resource {
percentile = math.Abs(percentile)
if percentile > 1.0 {
percentile = 1.0
}
if capacity < 0 {
capacity = math.MaxInt16
}
return &percentiles{
static: NewResourceStatic(method, url, delay, allowedCodes...).(static),
percentile: percentile,
capacity: int64(capacity),
latencies: make([]time.Duration, 0, capacity+capacity/2),
}
}
func (r *percentiles) After() <-chan time.Time {
delay := r.delay
r.lock.RLock()
if l := int64(len(r.latencies)); l >= r.capacity/2 {
lat := make([]time.Duration, l)
copy(lat, r.latencies)
sort.Slice(lat, func(i, j int) bool {
return lat[i] < lat[j]
})
delay = lat[int(math.Round(float64(l)*r.percentile))-1]
}
r.lock.RUnlock()
return time.After(delay)
}
func (r *percentiles) Hook(*http.Request) func(*http.Response) {
t := time.Now()
return func(*http.Response) {
d := time.Since(t)
r.lock.Lock()
r.latencies = append(r.latencies, d)
// in case of overflow: just drop half of the buffer
if int64(len(r.latencies)) >= r.capacity {
r.latencies = r.latencies[r.capacity/2:]
}
r.lock.Unlock()
}
}