/
grpc.go
210 lines (188 loc) · 6.11 KB
/
grpc.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package cloud
import (
"context"
"fmt"
"io"
"regexp"
"strconv"
"time"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
var RPCErrRegex = regexp.MustCompile(`(?U)rpc error: code = .+ desc = `)
func (c *Client) withAuth(ctx context.Context) context.Context {
return metadata.AppendToOutgoingContext(ctx, "authorization", fmt.Sprintf("Bearer %s", c.authToken))
}
func (c *Client) withReqID(ctx context.Context) context.Context {
return metadata.AppendToOutgoingContext(ctx, requestID, c.getRequestID())
}
func (c *Client) withRetryCount(ctx context.Context, count int) context.Context {
return metadata.AppendToOutgoingContext(ctx, retryCount, strconv.Itoa(count))
}
func getReqID(ctx context.Context) string {
md, ok := metadata.FromOutgoingContext(ctx)
if ok {
vals := md.Get(requestID)
if len(vals) > 0 {
return vals[0]
}
}
return ""
}
type interceptorOpts struct {
skipAuth map[string]struct{}
}
type InterceptorOpt func(opt *interceptorOpts)
func WithSkipAuth(methods ...string) InterceptorOpt {
return func(opts *interceptorOpts) {
if opts.skipAuth == nil {
opts.skipAuth = map[string]struct{}{}
}
for _, method := range methods {
opts.skipAuth[method] = struct{}{}
}
}
}
// UnaryInterceptor is a unary middleware function for the Earthly gRPC client which
// handle re-authentication when necessary, and automatically
// prints requestIDs to errors when errors are received from the server.
func (c *Client) UnaryInterceptor(opts ...InterceptorOpt) grpc.UnaryClientInterceptor {
interceptorOpts := &interceptorOpts{}
for _, opt := range opts {
opt(interceptorOpts)
}
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
ctx = c.withReqID(ctx)
if _, ok := interceptorOpts.skipAuth[method]; ok {
// It would probably be better to break this interceptor into multiple so that skipping auth doesn't affect anything else that
// might be added here in the future
return invoker(ctx, method, req, reply, cc, opts...)
}
ctx, err := c.reAuthIfExpired(ctx)
if err != nil {
return appendRequestID(ctx, err)
}
err = invoker(ctx, method, req, reply, cc, opts...)
if err != nil {
s, ok := status.FromError(err)
if !ok {
return appendRequestID(ctx, err)
}
if s.Code() == codes.Unauthenticated {
ctx, err = c.reAuthCtx(ctx)
if err != nil {
return appendRequestID(ctx, err)
}
return invoker(ctx, method, req, reply, cc, opts...)
}
return appendRequestIDStatus(ctx, s)
}
return nil
}
}
// StreamInterceptor is a stream middleware function for the Earthly gRPC client which
// handle re-authentication when necessary, and automatically
// prints requestIDs to errors when errors are received from the server.
func (c *Client) StreamInterceptor() grpc.StreamClientInterceptor {
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
ctx = c.withReqID(ctx)
ctx, err := c.reAuthIfExpired(ctx)
if err != nil {
return nil, appendRequestID(ctx, err)
}
newStreamer, err := streamer(ctx, desc, cc, method, opts...)
if err != nil {
s, ok := status.FromError(err)
if !ok {
return nil, appendRequestID(ctx, err)
}
if s.Code() == codes.Unauthenticated {
ctx, err = c.reAuthCtx(ctx)
if err != nil {
return nil, appendRequestID(ctx, err)
}
return streamer(ctx, desc, cc, method, opts...)
}
return nil, appendRequestIDStatus(ctx, s)
}
return newRequestIDWrappedStream(ctx, newStreamer), nil
}
}
// requestIDWrappedStream wraps around the embedded grpc.ClientStream.
// // Itintercepts the RecvMsg and SendMsg methods, appending the request ID when error occurs.
type requestIDWrappedStream struct {
grpc.ClientStream
ctx context.Context
}
func (w *requestIDWrappedStream) RecvMsg(m any) error {
if err := w.ClientStream.RecvMsg(m); err != nil {
if err == io.EOF {
return err
}
s, ok := status.FromError(err)
if !ok {
return fmt.Errorf("%s {reqID: %s}", err.Error(), getReqID(w.ctx))
}
return status.Errorf(s.Code(), fmt.Sprintf("%s {reqID: %s}",
cleanStatusError(err.Error()), getReqID(w.ctx)))
}
return nil
}
func (w *requestIDWrappedStream) SendMsg(m any) error {
if err := w.ClientStream.SendMsg(m); err != nil {
if err == io.EOF {
return err
}
s, ok := status.FromError(err)
if !ok {
return fmt.Errorf("%s {reqID: %s}", err.Error(), getReqID(w.ctx))
}
return status.Errorf(s.Code(), fmt.Sprintf("%s {reqID: %s}",
cleanStatusError(err.Error()), getReqID(w.ctx)))
}
return nil
}
func newRequestIDWrappedStream(ctx context.Context, s grpc.ClientStream) grpc.ClientStream {
return &requestIDWrappedStream{s, ctx}
}
// cleanStatusError returns the underlying error message from a gRPC status error
func cleanStatusError(errStr string) string {
return RPCErrRegex.ReplaceAllString(errStr, "")
}
func appendRequestID(ctx context.Context, err error) error {
return fmt.Errorf("%s {reqID: %s}", err.Error(), getReqID(ctx))
}
func appendRequestIDStatus(ctx context.Context, s *status.Status) error {
return status.Errorf(s.Code(), fmt.Sprintf("%s {reqID: %s}",
cleanStatusError(s.Err().Error()), getReqID(ctx)))
}
func (c *Client) reAuthIfExpired(ctx context.Context) (context.Context, error) {
if time.Now().UTC().After(c.authTokenExpiry) {
_, err := c.Authenticate(ctx)
if err != nil {
return ctx, errors.Wrap(err, "failed refreshing expired token")
}
ctx = c.resetAuthMeta(ctx)
}
return ctx, nil
}
func (c *Client) reAuthCtx(ctx context.Context) (context.Context, error) {
_, err := c.Authenticate(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed re-authenticating")
}
return c.resetAuthMeta(ctx), nil
}
func (c *Client) resetAuthMeta(ctx context.Context) context.Context {
md, ok := metadata.FromOutgoingContext(ctx)
if ok {
md.Delete("authorization")
} else {
md = metadata.New(map[string]string{})
}
ctx = metadata.NewOutgoingContext(ctx, md)
return c.withAuth(ctx)
}