-
Notifications
You must be signed in to change notification settings - Fork 8
/
requestid.go
86 lines (67 loc) · 2.13 KB
/
requestid.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package requestid
import (
"context"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
"namespacelabs.dev/foundation/std/go/core"
"namespacelabs.dev/foundation/std/protocol"
"namespacelabs.dev/go-ids"
)
type contextKey string
var ck contextKey = "ns.ctx.request-id"
type RequestData struct {
Started time.Time
RequestID string
}
func RequestIDFromContext(ctx context.Context) string {
if data, has := RequestDataFromContext(ctx); has {
return data.RequestID
}
return "<unknown>"
}
func RequestDataFromContext(ctx context.Context) (RequestData, bool) {
v := ctx.Value(ck)
if v != nil {
return v.(RequestData), true
}
return RequestData{}, false
}
func allocateRequestID(ctx context.Context) (context.Context, RequestData) {
rdata := RequestData{
Started: time.Now(),
RequestID: ids.NewRandomBase32ID(16),
}
return context.WithValue(ctx, ck, rdata), rdata
}
func attachRequestIDToError(err error, reqid string) error {
if err == nil {
return nil
}
st, _ := status.FromError(err)
tSt, tErr := st.WithDetails(&protocol.RequestID{Id: reqid})
if tErr == nil {
return tSt.Err()
}
core.Log.Printf("[warning] failed to attach %q to error: %v", reqid, tErr)
return err
}
type Interceptor struct{}
func (Interceptor) Unary(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
ctx, rdata := allocateRequestID(ctx)
resp, unaryErr := handler(ctx, req)
return resp, attachRequestIDToError(unaryErr, rdata.RequestID)
}
func (Interceptor) Streaming(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
ctx, rdata := allocateRequestID(stream.Context())
streamErr := handler(srv, serverStream{stream, ctx})
return attachRequestIDToError(streamErr, rdata.RequestID)
}
type serverStream struct {
grpc.ServerStream
ctx context.Context
}
func (s serverStream) Context() context.Context { return s.ctx }