-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathin_flight_limit.go
More file actions
274 lines (234 loc) · 9.51 KB
/
in_flight_limit.go
File metadata and controls
274 lines (234 loc) · 9.51 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/*
Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/
package middleware
import (
"context"
"fmt"
"math"
"net/http"
"strconv"
"time"
"github.com/acronis/go-appkit/internal/inflightlimit"
"github.com/acronis/go-appkit/log"
"github.com/acronis/go-appkit/restapi"
)
// DefaultInFlightLimitMaxKeys is a default value of maximum keys number for the InFlightLimit middleware.
const DefaultInFlightLimitMaxKeys = 10000
// InFlightLimitErrCode is the error code that is used in a response body
// if the request is rejected by the middleware that limits in-flight HTTP requests.
const InFlightLimitErrCode = "tooManyInFlightRequests"
// Log fields for InFlightLimit middleware.
const (
InFlightLimitLogFieldKey = "in_flight_limit_key"
InFlightLimitLogFieldBacklogged = "in_flight_limit_backlogged"
)
// InFlightLimitParams contains data that relates to the in-flight limiting procedure
// and could be used for rejecting or handling an occurred error.
type InFlightLimitParams struct {
ResponseStatusCode int
GetRetryAfter InFlightLimitGetRetryAfterFunc
ErrDomain string
Key string
RequestBacklogged bool
}
// InFlightLimitGetRetryAfterFunc is a function that is called to get a value for Retry-After response HTTP header
// when the in-flight limit is exceeded.
type InFlightLimitGetRetryAfterFunc func(r *http.Request) time.Duration
// InFlightLimitOnRejectFunc is a function that is called for rejecting HTTP request when the in-flight limit is exceeded.
type InFlightLimitOnRejectFunc func(rw http.ResponseWriter, r *http.Request,
params InFlightLimitParams, next http.Handler, logger log.FieldLogger)
// InFlightLimitOnErrorFunc is a function that is called in case of any error that may occur during the in-flight limiting.
type InFlightLimitOnErrorFunc func(rw http.ResponseWriter, r *http.Request,
params InFlightLimitParams, err error, next http.Handler, logger log.FieldLogger)
// InFlightLimitGetKeyFunc is a function that is called for getting key for in-flight limiting.
type InFlightLimitGetKeyFunc func(r *http.Request) (key string, bypass bool, err error)
type inFlightLimitHandler struct {
processor *inflightlimit.RequestProcessor
next http.Handler
getKey InFlightLimitGetKeyFunc
errDomain string
respStatusCode int
getRetryAfter InFlightLimitGetRetryAfterFunc
onReject InFlightLimitOnRejectFunc
onRejectInDryRun InFlightLimitOnRejectFunc
onError InFlightLimitOnErrorFunc
}
// InFlightLimitOpts represents an options for the middleware to limit in-flight HTTP requests.
type InFlightLimitOpts struct {
GetKey InFlightLimitGetKeyFunc
MaxKeys int
ResponseStatusCode int
GetRetryAfter InFlightLimitGetRetryAfterFunc
BacklogLimit int
BacklogTimeout time.Duration
DryRun bool
OnReject InFlightLimitOnRejectFunc
OnRejectInDryRun InFlightLimitOnRejectFunc
OnError InFlightLimitOnErrorFunc
}
// InFlightLimit is a middleware that limits the total number of currently served (in-flight) HTTP requests.
// It checks how many requests are in-flight and rejects with 503 if exceeded.
func InFlightLimit(limit int, errDomain string) (func(next http.Handler) http.Handler, error) {
return InFlightLimitWithOpts(limit, errDomain, InFlightLimitOpts{})
}
// MustInFlightLimit is a version of InFlightLimit that panics on error.
func MustInFlightLimit(limit int, errDomain string) func(next http.Handler) http.Handler {
mw, err := InFlightLimit(limit, errDomain)
if err != nil {
panic(err)
}
return mw
}
// InFlightLimitWithOpts is a configurable version of a middleware to limit in-flight HTTP requests.
func InFlightLimitWithOpts(limit int, errDomain string, opts InFlightLimitOpts) (func(next http.Handler) http.Handler, error) {
backlogTimeout := opts.BacklogTimeout
if backlogTimeout == 0 {
backlogTimeout = inflightlimit.DefaultInFlightLimitBacklogTimeout
}
maxKeys := 0
if opts.GetKey != nil {
maxKeys = opts.MaxKeys
if maxKeys == 0 {
maxKeys = DefaultInFlightLimitMaxKeys
}
}
backlogParams := inflightlimit.BacklogParams{
MaxKeys: maxKeys,
Limit: opts.BacklogLimit,
Timeout: backlogTimeout,
}
processor, err := inflightlimit.NewRequestProcessor(limit, backlogParams, opts.DryRun)
if err != nil {
return nil, fmt.Errorf("create request processor: %w", err)
}
respStatusCode := opts.ResponseStatusCode
if respStatusCode == 0 {
respStatusCode = http.StatusServiceUnavailable
}
return func(next http.Handler) http.Handler {
return &inFlightLimitHandler{
processor: processor,
next: next,
getKey: opts.GetKey,
errDomain: errDomain,
respStatusCode: respStatusCode,
getRetryAfter: opts.GetRetryAfter,
onReject: makeInFlightLimitOnRejectFunc(opts),
onRejectInDryRun: makeInFlightLimitOnRejectInDryRunFunc(opts),
onError: makeInFlightLimitOnErrorFunc(opts),
}
}, nil
}
// MustInFlightLimitWithOpts is a version of InFlightLimitWithOpts that panics on error.
func MustInFlightLimitWithOpts(limit int, errDomain string, opts InFlightLimitOpts) func(next http.Handler) http.Handler {
mw, err := InFlightLimitWithOpts(limit, errDomain, opts)
if err != nil {
panic(err)
}
return mw
}
// inFlightLimitRequestHandler implements inflightlimit.RequestHandler for HTTP requests.
type inFlightLimitRequestHandler struct {
rw http.ResponseWriter
r *http.Request
parent *inFlightLimitHandler
}
func (rh *inFlightLimitRequestHandler) GetContext() context.Context {
return rh.r.Context()
}
func (rh *inFlightLimitRequestHandler) GetKey() (key string, bypass bool, err error) {
if rh.parent.getKey != nil {
return rh.parent.getKey(rh.r)
}
return "", false, nil
}
func (rh *inFlightLimitRequestHandler) Execute() error {
rh.parent.next.ServeHTTP(rh.rw, rh.r)
return nil
}
func (rh *inFlightLimitRequestHandler) OnReject(params inflightlimit.Params) error {
rh.parent.onReject(rh.rw, rh.r, rh.convertParams(params), rh.parent.next, GetLoggerFromContext(rh.r.Context()))
return nil
}
func (rh *inFlightLimitRequestHandler) OnRejectInDryRun(params inflightlimit.Params) error {
rh.parent.onRejectInDryRun(rh.rw, rh.r, rh.convertParams(params), rh.parent.next, GetLoggerFromContext(rh.r.Context()))
return nil
}
func (rh *inFlightLimitRequestHandler) OnError(params inflightlimit.Params, err error) error {
rh.parent.onError(rh.rw, rh.r, rh.convertParams(params), err, rh.parent.next, GetLoggerFromContext(rh.r.Context()))
return nil
}
func (rh *inFlightLimitRequestHandler) convertParams(params inflightlimit.Params) InFlightLimitParams {
return InFlightLimitParams{
ResponseStatusCode: rh.parent.respStatusCode,
GetRetryAfter: rh.parent.getRetryAfter,
ErrDomain: rh.parent.errDomain,
Key: params.Key,
RequestBacklogged: params.RequestBacklogged,
}
}
func (h *inFlightLimitHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
requestHandler := &inFlightLimitRequestHandler{rw: rw, r: r, parent: h}
_ = h.processor.ProcessRequest(requestHandler) // Error is always nil, as it is handled in the inFlightLimitRequestHandler methods.
}
// DefaultInFlightLimitOnReject sends HTTP response in a typical go-appkit way when the in-flight limit is exceeded.
func DefaultInFlightLimitOnReject(
rw http.ResponseWriter, r *http.Request, params InFlightLimitParams, next http.Handler, logger log.FieldLogger,
) {
if logger != nil {
logger = logger.With(
log.String(InFlightLimitLogFieldKey, params.Key),
log.Bool(InFlightLimitLogFieldBacklogged, params.RequestBacklogged),
log.String(userAgentLogFieldKey, r.UserAgent()),
)
}
if params.GetRetryAfter != nil {
rw.Header().Set("Retry-After", strconv.Itoa(int(math.Ceil(params.GetRetryAfter(r).Seconds()))))
}
apiErr := restapi.NewError(params.ErrDomain, InFlightLimitErrCode, "Too many in-flight requests.")
restapi.RespondError(rw, params.ResponseStatusCode, apiErr, logger)
}
// DefaultInFlightLimitOnRejectInDryRun sends HTTP response in a typical go-appkit way
// when the in-flight limit is exceeded in the dry-run mode.
func DefaultInFlightLimitOnRejectInDryRun(
rw http.ResponseWriter, r *http.Request, params InFlightLimitParams, next http.Handler, logger log.FieldLogger,
) {
if logger != nil {
logger.Warn("too many in-flight requests, serving will be continued because of dry run mode",
log.String(InFlightLimitLogFieldKey, params.Key),
log.Bool(InFlightLimitLogFieldBacklogged, params.RequestBacklogged),
log.String(userAgentLogFieldKey, r.UserAgent()),
)
}
next.ServeHTTP(rw, r)
}
// DefaultInFlightLimitOnError sends HTTP response in a typical go-appkit way in case
// when the error occurs during the in-flight limiting.
func DefaultInFlightLimitOnError(
rw http.ResponseWriter, r *http.Request, params InFlightLimitParams, err error, next http.Handler, logger log.FieldLogger,
) {
if logger != nil {
logger.Error(err.Error(), log.String(InFlightLimitLogFieldKey, params.Key))
}
restapi.RespondInternalError(rw, params.ErrDomain, logger)
}
func makeInFlightLimitOnRejectFunc(opts InFlightLimitOpts) InFlightLimitOnRejectFunc {
if opts.OnReject != nil {
return opts.OnReject
}
return DefaultInFlightLimitOnReject
}
func makeInFlightLimitOnRejectInDryRunFunc(opts InFlightLimitOpts) InFlightLimitOnRejectFunc {
if opts.OnRejectInDryRun != nil {
return opts.OnRejectInDryRun
}
return DefaultInFlightLimitOnRejectInDryRun
}
func makeInFlightLimitOnErrorFunc(opts InFlightLimitOpts) InFlightLimitOnErrorFunc {
if opts.OnError != nil {
return opts.OnError
}
return DefaultInFlightLimitOnError
}