Adds request latency tracking

Fixes #1
This commit is contained in:
sm
2018-01-24 21:25:15 -08:00
parent 6fa26ec095
commit 70288014ea
4 changed files with 87 additions and 1 deletions
+46
View File
@@ -0,0 +1,46 @@
package hwt
import (
"context"
"time"
"github.com/twitchtv/twirp"
)
var reqStartKey = new(int)
type Timer func(path string, dur time.Duration)
func NewMetricsHooks(timer Timer) *twirp.ServerHooks {
hs := &twirp.ServerHooks{}
hs.RequestReceived = func(ctx context.Context) (context.Context, error) {
return markReqStart(ctx), nil
}
hs.ResponseSent = func(ctx context.Context) {
name, ok := twirp.MethodName(ctx)
if !ok {
// XXX (sm) : something else?
panic("missing name")
}
start, ok := getReqStart(ctx)
if !ok {
// XXX (sm) : something else?
panic("missing start")
}
dur := time.Now().Sub(start)
timer(name, dur)
}
return hs
}
func markReqStart(ctx context.Context) context.Context {
return context.WithValue(ctx, reqStartKey, time.Now())
}
func getReqStart(ctx context.Context) (time.Time, bool) {
t, ok := ctx.Value(reqStartKey).(time.Time)
return t, ok
}