-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstats.go
82 lines (63 loc) · 1.53 KB
/
stats.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
package scarf
import (
"context"
"github.com/google/uuid"
"google.golang.org/grpc/stats"
)
type (
StatsHandler struct {
handler stats.Handler
}
tokenClientID string
tokenRemoteAddr string
)
var (
TokenClientID = tokenClientID("scarf.client_id")
TokenRemoteAddr = tokenRemoteAddr("scarf.remote_addr")
)
func GetClientID(ctx context.Context) string {
if val, ok := ctx.Value(TokenClientID).(string); ok {
return val
}
return ""
}
func GetRemoteAddr(ctx context.Context) string {
if val, ok := ctx.Value(TokenRemoteAddr).(string); ok {
return val
}
return ""
}
func NewStatsHandler(handler stats.Handler) stats.Handler {
return &StatsHandler{
handler: handler,
}
}
func (h *StatsHandler) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context {
raw, err := uuid.NewRandom()
if err != nil {
// TODO - what to do with this?
}
clientID := raw.String()
ctx = context.WithValue(ctx, TokenClientID, clientID)
ctx = context.WithValue(ctx, TokenRemoteAddr, info.RemoteAddr)
if h.handler == nil {
return ctx
}
return h.handler.TagConn(ctx, info)
}
func (h *StatsHandler) HandleConn(ctx context.Context, stats stats.ConnStats) {
if h.handler != nil {
h.handler.HandleConn(ctx, stats)
}
}
func (h *StatsHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
if h.handler == nil {
return ctx
}
return h.handler.TagRPC(ctx, info)
}
func (h *StatsHandler) HandleRPC(ctx context.Context, stats stats.RPCStats) {
if h.handler != nil {
h.handler.HandleRPC(ctx, stats)
}
}