-
Notifications
You must be signed in to change notification settings - Fork 110
/
context.go
76 lines (64 loc) · 2.44 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
73
74
75
76
// Package contextutils provides utilities for dealing with contexts such as adding and
// retrieving metadata to/from a context, and handling context timeouts.
package contextutils
import (
"context"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
type contextKey string
const (
// MetadataContextKey is the key used to access metadata from a context with metadata.
MetadataContextKey = contextKey("viam-metadata")
// TimeRequestedMetadataKey is optional metadata in the gRPC response header that correlates
// to the time right before the point cloud was captured.
TimeRequestedMetadataKey = "viam-time-requested"
// TimeReceivedMetadataKey is optional metadata in the gRPC response header that correlates
// to the time right after the point cloud was captured.
TimeReceivedMetadataKey = "viam-time-received"
)
// ContextWithMetadata attaches a metadata map to the context.
func ContextWithMetadata(ctx context.Context) (context.Context, map[string][]string) {
// If the context already has metadata, return that and leave the context untouched.
existingMD := ctx.Value(MetadataContextKey)
if mdMap, ok := existingMD.(map[string][]string); ok {
return ctx, mdMap
}
// Otherwise, add a metadata map to the context.
md := make(map[string][]string)
ctx = context.WithValue(ctx, MetadataContextKey, md)
return ctx, md
}
// ContextWithMetadataUnaryClientInterceptor attempts to read metadata from the gRPC header and
// injects the metadata into the context if the caller has passed in a context with metadata.
func ContextWithMetadataUnaryClientInterceptor(
ctx context.Context,
method string,
req, reply interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
var header metadata.MD
opts = append(opts, grpc.Header(&header))
err := invoker(ctx, method, req, reply, cc, opts...)
if err != nil {
return err
}
md := ctx.Value(MetadataContextKey)
if mdMap, ok := md.(map[string][]string); ok {
for key, value := range header {
mdMap[key] = value
}
}
return nil
}
// ContextWithTimeoutIfNoDeadline returns a child timeout context derived from `ctx` if a
// deadline does not exist. Returns a cancel context and cancel func from `ctx` if deadline exists.
func ContextWithTimeoutIfNoDeadline(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
if _, ok := ctx.Deadline(); !ok {
return context.WithTimeout(ctx, timeout)
}
return context.WithCancel(ctx)
}