-
Notifications
You must be signed in to change notification settings - Fork 388
/
context.go
72 lines (61 loc) · 1.64 KB
/
context.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
package tyber
import (
"context"
"strconv"
"time"
"github.com/gofrs/uuid"
"google.golang.org/grpc/metadata"
)
type traceIDKeyType string
const (
traceIDKey traceIDKeyType = "TyberTraceID"
noTraceID string = "no_trace_id"
uuidFallback string = "409123fa-4dd5-11eb-a4a1-675173c25b22"
)
var (
NewSessionID = newID
NewTraceID = newID
)
func ContextWithTraceID(ctx context.Context) (context.Context, bool) {
if eid := GetTraceIDFromContext(ctx); eid != noTraceID {
return ctx, false
}
if md, ok := metadata.FromIncomingContext(ctx); ok {
if vals := md.Get(string(traceIDKey)); len(vals) != 0 {
return ContextWithConstantTraceID(ctx, vals[0]), false
}
}
return ContextWithConstantTraceID(ctx, NewTraceID()), true
}
func ContextWithConstantTraceID(ctx context.Context, traceID string) context.Context {
md, ok := metadata.FromOutgoingContext(ctx)
if ok {
md = md.Copy()
} else {
md = metadata.New(nil)
}
md.Set(string(traceIDKey), traceID)
return metadata.NewOutgoingContext(context.WithValue(ctx, traceIDKey, traceID), md)
}
func GetTraceIDFromContext(ctx context.Context) string {
if val, ok := ctx.Value(traceIDKey).(string); ok {
return val
}
return noTraceID
}
func ContextWithoutTraceID(ctx context.Context) context.Context {
return ContextWithConstantTraceID(ctx, noTraceID)
}
func newID() string {
uid, err := uuid.NewV4()
// If error while reading random, fallback on uuid v5
if err != nil {
ns, err := uuid.FromString(uuidFallback)
if err != nil {
panic(err) // Should never happen
}
n := strconv.FormatInt(time.Now().UnixNano(), 10)
uid = uuid.NewV5(ns, n)
}
return uid.String()
}