/
busy.go
70 lines (56 loc) · 1.5 KB
/
busy.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
// SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package xhttpserver
import (
"net/http"
"sync/atomic"
)
// busyHandler is the internal http.Handler implementation that wraps another http.Handler
// in concurrent request protection
type busyHandler struct {
next http.Handler
onBusy http.Handler
maxConcurrentRequests int32
inFlight int32
}
func (bh *busyHandler) tryStart() bool {
if atomic.AddInt32(&bh.inFlight, 1) > bh.maxConcurrentRequests {
atomic.AddInt32(&bh.inFlight, -1)
return false
}
return true
}
func (bh *busyHandler) end() {
atomic.AddInt32(&bh.inFlight, -1)
}
func (bh *busyHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {
if !bh.tryStart() {
bh.onBusy.ServeHTTP(response, request)
return
}
defer bh.end()
bh.next.ServeHTTP(response, request)
}
// Busy is an Alice-style decorator that enforces a maximum number of concurrent HTTP transactions
type Busy struct {
MaxConcurrentRequests int
OnBusy http.Handler
}
func (b Busy) Then(next http.Handler) http.Handler {
if b.MaxConcurrentRequests < 1 {
return next
}
bh := &busyHandler{
maxConcurrentRequests: int32(b.MaxConcurrentRequests),
next: next,
}
if b.OnBusy != nil {
bh.onBusy = b.OnBusy
} else {
bh.onBusy = Constant{StatusCode: http.StatusTooManyRequests}.NewHandler()
}
return bh
}
func (b Busy) ThenFunc(next http.HandlerFunc) http.Handler {
return b.Then(next)
}