-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware.go
97 lines (80 loc) · 2.02 KB
/
middleware.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
package carrot
import (
"github.com/DataDog/datadog-go/statsd"
log "github.com/sirupsen/logrus"
"math"
)
const (
InputChannelSize = 16384
)
var count = 0
/*
Middlewares
*/
// func parseRequest(req *Request, logger *log.Entry) {
// logger.Info("I am going to parse a request!")
// }
func logger(req *Request, logger *log.Entry) error {
logger.WithField("session_token", req.SessionToken).Debug("new request")
return nil
}
func discardBadRequest(req *Request, logger *log.Entry) error {
if req.err != nil {
logger.WithField("session_token", req.SessionToken).Errorf("invalid request: %v", req.err.Error())
return req.err
}
return nil
}
type MiddlewarePipeline struct {
In chan *Request
middlewares []func(*Request, *log.Entry) error
dispatcher *Dispatcher
logger *log.Entry
statsd *statsd.Client
}
func (mw *MiddlewarePipeline) Run() {
go mw.dispatcher.Run()
func() {
for {
select {
case req := <-mw.In:
if len(mw.In) > int(math.Floor(InputChannelSize*0.90)) {
mw.logger.WithField("buf_size", len(mw.In)).Warn("input channel is at or above 90% capacity!")
}
if len(mw.In) == InputChannelSize {
mw.logger.WithField("buf_size", len(mw.In)).Warn("input channel is full!")
}
mw.statsd.Incr("carrot.middleware.request_rate", nil, 1)
var err error
for _, f := range mw.middlewares {
err = f(req, mw.logger)
if err != nil {
req.End()
break
}
count++
}
if err == nil {
mw.dispatcher.requests <- req
}
req.AddMetric(MiddlewareOutputToDispatcher)
}
}
}()
}
func NewMiddlewarePipeline() *MiddlewarePipeline {
// middleware function index
mw := []func(*Request, *log.Entry) error{discardBadRequest, logger}
logger := log.WithField("module", "middleware")
c, err := statsd.New("127.0.0.1:8125")
if err != nil {
logger.Error(err)
}
return &MiddlewarePipeline{
In: make(chan *Request, InputChannelSize),
middlewares: mw,
dispatcher: NewDispatcher(),
logger: logger,
statsd: c,
}
}