-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathrequest_id_header.go
More file actions
289 lines (245 loc) · 9.35 KB
/
request_id_header.go
File metadata and controls
289 lines (245 loc) · 9.35 KB
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package spanner
import (
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"math"
"math/big"
"sync/atomic"
"time"
"github.com/googleapis/gax-go/v2"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"google.golang.org/api/iterator"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// randIDForProcess is a strongly randomly generated value derived
// from a uint64, and in the range [0, maxUint64].
var randIDForProcess string
func init() {
bigMaxInt64, _ := new(big.Int).SetString(fmt.Sprintf("%d", uint64(math.MaxUint64)), 10)
if g, w := bigMaxInt64.Uint64(), uint64(math.MaxUint64); g != w {
panic(fmt.Sprintf("mismatch in randIDForProcess.maxUint64:\n\tGot: %d\n\tWant: %d", g, w))
}
r64, err := rand.Int(rand.Reader, bigMaxInt64)
if err != nil {
panic(err)
}
randIDForProcess = fmt.Sprintf("%016x", r64.Uint64())
}
// Please bump this version whenever this implementation
// executes on the plans of a new specification.
const xSpannerRequestIDVersion uint8 = 1
const xSpannerRequestIDHeader = "x-goog-spanner-request-id"
const xSpannerRequestIDSpanAttr = "x_goog_spanner_request_id"
// optsWithNextRequestID bundles priors with a new header "x-goog-spanner-request-id"
func (g *grpcSpannerClient) optsWithNextRequestID(priors []gax.CallOption) []gax.CallOption {
return append(priors, &retryerWithRequestID{g})
}
func (g *grpcSpannerClient) prepareRequestIDTrackers(clientID int, channelID uint64, nthRequest *atomic.Uint32) {
g.id = clientID // The ID derived from the SpannerClient.
g.channelID = channelID
g.nthRequest = nthRequest
}
// retryerWithRequestID is a gax.CallOption that injects "x-goog-spanner-request-id"
// into every RPC, and it appropriately increments the RPC's ordinal number per retry.
type retryerWithRequestID struct {
gsc *grpcSpannerClient
}
var _ gax.CallOption = (*retryerWithRequestID)(nil)
func (g *grpcSpannerClient) appendRequestIDToGRPCOptions(priors []grpc.CallOption, nthRequest, attempt uint32) []grpc.CallOption {
// Each value should be added in Decimal, unpadded.
requestID := fmt.Sprintf("%d.%s.%d.%d.%d.%d", xSpannerRequestIDVersion, randIDForProcess, g.id, g.channelID, nthRequest, attempt)
md := metadata.MD{xSpannerRequestIDHeader: []string{requestID}}
return append(priors, grpc.Header(&md))
}
type requestID string
// augmentErrorWithRequestID introspects error converting it to an *.Error and
// attaching the subject requestID, unless it is one of the following:
// * nil
// * context.Canceled
// * io.EOF
// * iterator.Done
// of which in this case, the original error will be attached as is, since those
// are sentinel errors used to break sensitive conditions like ending iterations.
func (r requestID) augmentErrorWithRequestID(err error) error {
if err == nil {
return nil
}
switch err {
case iterator.Done, io.EOF, context.Canceled:
return err
default:
potentialCommit := errors.Is(err, context.DeadlineExceeded)
if code := status.Code(err); code == codes.DeadlineExceeded {
potentialCommit = true
}
sErr := toSpannerErrorWithCommitInfo(err, potentialCommit)
if sErr == nil {
return err
}
spErr := sErr.(*Error)
spErr.RequestID = string(r)
return spErr
}
}
func gRPCCallOptionsToRequestID(opts []grpc.CallOption) (md metadata.MD, reqID requestID, found bool) {
for _, opt := range opts {
hdrOpt, ok := opt.(grpc.HeaderCallOption)
if !ok {
continue
}
metadata := hdrOpt.HeaderAddr
reqIDs := metadata.Get(xSpannerRequestIDHeader)
if len(reqIDs) != 0 && len(reqIDs[0]) != 0 {
md = *metadata
reqID = requestID(reqIDs[0])
found = true
break
}
}
return
}
func (wr *requestIDHeaderInjector) interceptUnary(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
// It is imperative to search for the requestID before the call
// because gRPC's internals will consume the headers.
_, reqID, foundRequestID := gRPCCallOptionsToRequestID(opts)
if foundRequestID {
ctx = metadata.AppendToOutgoingContext(ctx, xSpannerRequestIDHeader, string(reqID))
// Associate the requestId as an attribute on the span in the current context.
span := trace.SpanFromContext(ctx)
span.SetAttributes(attribute.KeyValue{
Key: xSpannerRequestIDSpanAttr,
Value: attribute.StringValue(string(reqID)),
})
}
err := invoker(ctx, method, req, reply, cc, opts...)
if !foundRequestID {
return err
}
return reqID.augmentErrorWithRequestID(err)
}
type requestIDErrWrappingClientStream struct {
grpc.ClientStream
reqID requestID
}
func (rew *requestIDErrWrappingClientStream) processFromOutgoingContext(err error) error {
if err == nil {
return nil
}
return rew.reqID.augmentErrorWithRequestID(err)
}
func (rew *requestIDErrWrappingClientStream) SendMsg(msg any) error {
err := rew.ClientStream.SendMsg(msg)
return rew.processFromOutgoingContext(err)
}
func (rew *requestIDErrWrappingClientStream) RecvMsg(msg any) error {
err := rew.ClientStream.RecvMsg(msg)
return rew.processFromOutgoingContext(err)
}
var _ grpc.ClientStream = (*requestIDErrWrappingClientStream)(nil)
type requestIDHeaderInjector int
func (wr *requestIDHeaderInjector) interceptStream(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
// It is imperative to search for the requestID before the call
// because gRPC's internals will consume the headers.
_, reqID, foundRequestID := gRPCCallOptionsToRequestID(opts)
if foundRequestID {
ctx = metadata.AppendToOutgoingContext(ctx, xSpannerRequestIDHeader, string(reqID))
// Associate the requestId as an attribute on the span in the current context.
span := trace.SpanFromContext(ctx)
span.SetAttributes(attribute.KeyValue{
Key: xSpannerRequestIDSpanAttr,
Value: attribute.StringValue(string(reqID)),
})
}
cs, err := streamer(ctx, desc, cc, method, opts...)
if !foundRequestID {
return cs, err
}
wcs := &requestIDErrWrappingClientStream{cs, reqID}
if err == nil {
return wcs, nil
}
return wcs, reqID.augmentErrorWithRequestID(err)
}
func (wr *retryerWithRequestID) Resolve(cs *gax.CallSettings) {
nthRequest := wr.gsc.nextNthRequest()
attempt := uint32(1)
// Inject the first request-id header.
// Note: after every gax.Invoke call, all the gRPC option headers are cleared out
// and nullified, but yet cs.GRPC still contains a reference to the inserted *metadata.MD
// just that it got cleared out and nullified. However, for retries we need to retain control
// of the entry to re-insert the updated request-id on every call, hence why we are creating
// and retaining a pointer reference to the metadata and shall be re-inserting the header value
// on every retry.
md := new(metadata.MD)
wr.generateAndInsertRequestID(md, nthRequest, attempt)
// Insert our grpc.CallOption that'll be updated by reference on every retry attempt.
cs.GRPC = append(cs.GRPC, grpc.Header(md))
if cs.Retry == nil {
// If there was no retry manager, our journey has ended.
return
}
originalRetryer := cs.Retry()
newRetryer := func() gax.Retryer {
return (wrapRetryFn)(func(err error) (pause time.Duration, shouldRetry bool) {
attempt++
wr.generateAndInsertRequestID(md, nthRequest, attempt)
return originalRetryer.Retry(err)
})
}
cs.Retry = newRetryer
}
func (wr *retryerWithRequestID) generateAndInsertRequestID(md *metadata.MD, nthRequest, attempt uint32) {
wr.gsc.generateAndInsertRequestID(md, nthRequest, attempt)
}
func (gsc *grpcSpannerClient) generateAndInsertRequestID(md *metadata.MD, nthRequest, attempt uint32) {
// Google Engineering has requested that each value be added in Decimal unpadded.
// Should we have a standardized endianness: Little Endian or Big Endian?
reqID := fmt.Sprintf("%d.%s.%d.%d.%d.%d", xSpannerRequestIDVersion, randIDForProcess, gsc.id, gsc.channelID, nthRequest, attempt)
if *md == nil {
*md = metadata.MD{}
}
md.Set(xSpannerRequestIDHeader, reqID)
}
type wrapRetryFn func(err error) (time.Duration, bool)
var _ gax.Retryer = (wrapRetryFn)(nil)
func (fn wrapRetryFn) Retry(err error) (time.Duration, bool) {
return fn(err)
}
func (g *grpcSpannerClient) nextNthRequest() uint32 {
return g.nthRequest.Add(1)
}
type requestIDWrap struct {
md *metadata.MD
nthRequest uint32
gsc *grpcSpannerClient
}
func (gsc *grpcSpannerClient) generateRequestIDHeaderInjector() *requestIDWrap {
// Setup and track x-goog-request-id.
md := new(metadata.MD)
return &requestIDWrap{md: md, nthRequest: gsc.nextNthRequest(), gsc: gsc}
}
func (riw *requestIDWrap) withNextRetryAttempt(attempt uint32) gax.CallOption {
riw.gsc.generateAndInsertRequestID(riw.md, riw.nthRequest, attempt)
// If no gRPC stream is available, try to initiate one.
return gax.WithGRPCOptions(grpc.Header(riw.md))
}