forked from connectrpc/conformance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimpl.go
568 lines (502 loc) · 17.2 KB
/
impl.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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
// Copyright 2023-2024 The Connect Authors
//
// 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 referenceclient
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
"connectrpc.com/conformance/internal"
conformancev1 "connectrpc.com/conformance/internal/gen/proto/go/connectrpc/conformance/v1"
"connectrpc.com/conformance/internal/gen/proto/go/connectrpc/conformance/v1/conformancev1connect"
"connectrpc.com/connect"
"google.golang.org/protobuf/proto"
)
const clientName = "connectconformance-referenceclient"
type invoker struct {
client conformancev1connect.ConformanceServiceClient
referenceMode bool
}
// Creates a new invoker around a ConformanceServiceClient.
func newInvoker(transport http.RoundTripper, referenceMode bool, url *url.URL, opts []connect.ClientOption) *invoker {
opts = append(opts, connect.WithInterceptors(userAgentClientInterceptor{}))
client := conformancev1connect.NewConformanceServiceClient(
&http.Client{Transport: transport},
url.String(),
opts...,
)
return &invoker{
client: client,
referenceMode: referenceMode,
}
}
func (i *invoker) Invoke(
ctx context.Context,
req *conformancev1.ClientCompatRequest,
) (*conformancev1.ClientResponseResult, error) {
// If a timeout was specified, create a derived context with that deadline
if req.TimeoutMs != nil {
deadlineCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Duration(*req.TimeoutMs)*time.Millisecond))
ctx = deadlineCtx
defer cancel()
}
switch req.GetMethod() {
case "Unary":
if len(req.RequestMessages) != 1 {
return nil, errors.New("unary calls must specify exactly one request message")
}
resp, err := i.unary(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
case "IdempotentUnary":
if len(req.RequestMessages) != 1 {
return nil, errors.New("unary calls must specify exactly one request message")
}
resp, err := i.idempotentUnary(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
case "ServerStream":
if len(req.RequestMessages) != 1 {
return nil, errors.New("server streaming calls must specify exactly one request message")
}
resp, err := i.serverStream(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
case "ClientStream":
resp, err := i.clientStream(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
case "BidiStream":
resp, err := i.bidiStream(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
case "Unimplemented":
resp, err := i.unimplemented(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
default:
return nil, fmt.Errorf("method name %s does not exist on service %s", req.GetMethod(), req.GetService())
}
}
func (i *invoker) unary(
ctx context.Context,
req *conformancev1.ClientCompatRequest,
) (*conformancev1.ClientResponseResult, error) {
return doUnary(ctx, req, i, i.client.Unary,
func(resp *conformancev1.UnaryResponse) *conformancev1.ConformancePayload {
return resp.Payload
})
}
func (i *invoker) idempotentUnary(
ctx context.Context,
req *conformancev1.ClientCompatRequest,
) (*conformancev1.ClientResponseResult, error) {
return doUnary(ctx, req, i, i.client.IdempotentUnary,
func(resp *conformancev1.IdempotentUnaryResponse) *conformancev1.ConformancePayload {
return resp.Payload
})
}
type pointerMessage[T any] interface {
*T
proto.Message
}
func doUnary[ReqT, RespT any, Req pointerMessage[ReqT]](
ctx context.Context,
req *conformancev1.ClientCompatRequest,
inv *invoker,
stub func(context.Context, *connect.Request[ReqT]) (*connect.Response[RespT], error),
getPayload func(*RespT) *conformancev1.ConformancePayload,
) (*conformancev1.ClientResponseResult, error) {
timing, err := internal.GetCancelTiming(req.Cancel)
if err != nil {
return nil, err
}
msg := req.RequestMessages[0]
rpcReq := new(ReqT)
if err := msg.UnmarshalTo(Req(rpcReq)); err != nil {
return nil, err
}
request := connect.NewRequest(rpcReq)
// Add the specified request headers to the request
internal.AddHeaders(req.RequestHeaders, request.Header())
var protoErr *conformancev1.Error
var headers []*conformancev1.Header
var trailers []*conformancev1.Header
payloads := make([]*conformancev1.ConformancePayload, 0, 1)
if timing.AfterCloseSendMs >= 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
time.AfterFunc(time.Duration(timing.AfterCloseSendMs)*time.Millisecond, cancel)
}
ctx = inv.withWireCapture(ctx)
// Invoke the Unary call
resp, err := stub(ctx, request)
if err != nil {
// If an error was returned, first convert it to a Connect error
// so that we can get the trailers from the Meta property. Then,
// convert _that_ to a proto Error so we can set it in the response.
connectErr := internal.ConvertErrorToConnectError(err)
trailers = internal.ConvertToProtoHeader(connectErr.Meta())
protoErr = internal.ConvertConnectToProtoError(connectErr)
} else {
// If the call was successful, get the headers and trailers
headers = internal.ConvertToProtoHeader(resp.Header())
trailers = internal.ConvertToProtoHeader(resp.Trailer())
// If there's a payload, add that to the response also
payload := getPayload(resp.Msg)
if payload != nil {
payloads = append(payloads, payload)
}
}
statusCode, feedback := inv.examineWireDetails(ctx, headers, trailers)
return &conformancev1.ClientResponseResult{
ResponseHeaders: headers,
ResponseTrailers: trailers,
Payloads: payloads,
Error: protoErr,
HttpStatusCode: statusCode,
Feedback: feedback,
}, nil
}
func (i *invoker) serverStream(
ctx context.Context,
req *conformancev1.ClientCompatRequest,
) (result *conformancev1.ClientResponseResult, _ error) {
timing, err := internal.GetCancelTiming(req.Cancel)
if err != nil {
return nil, err
}
msg := req.RequestMessages[0]
ssr := &conformancev1.ServerStreamRequest{}
if err := msg.UnmarshalTo(ssr); err != nil {
return nil, err
}
request := connect.NewRequest(ssr)
// Add the specified request headers to the request
internal.AddHeaders(req.RequestHeaders, request.Header())
result = &conformancev1.ClientResponseResult{}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ctx = i.withWireCapture(ctx)
stream, err := i.client.ServerStream(ctx, request)
if err != nil {
// If an error was returned, first convert it to a Connect error
// so that we can get the headers from the Meta property. Then,
// convert _that_ to a proto Error so we can set it in the response.
connectErr := internal.ConvertErrorToConnectError(err)
headers := internal.ConvertToProtoHeader(connectErr.Meta())
protoErr := internal.ConvertConnectToProtoError(connectErr)
return &conformancev1.ClientResponseResult{
ResponseHeaders: headers,
Error: protoErr,
}, nil
}
defer func() {
// Always make sure stream is closed on exit.
closeErr := stream.Close()
if err != nil {
return
}
if result.Error == nil && closeErr != nil {
result.Error = internal.ConvertErrorToProtoError(closeErr)
}
if err == nil {
// Read headers and trailers from the stream
result.ResponseHeaders = internal.ConvertToProtoHeader(stream.ResponseHeader())
result.ResponseTrailers = internal.ConvertToProtoHeader(stream.ResponseTrailer())
result.HttpStatusCode, result.Feedback = i.examineWireDetails(ctx, result.ResponseHeaders, result.ResponseTrailers)
}
}()
if timing.AfterCloseSendMs >= 0 {
time.Sleep(time.Duration(timing.AfterCloseSendMs) * time.Millisecond)
cancel()
}
if ssr.ResponseDefinition != nil {
result.Payloads = make([]*conformancev1.ConformancePayload, 0, len(ssr.ResponseDefinition.ResponseData))
}
totalRcvd := 0
for stream.Receive() {
totalRcvd++
// If the call was successful, get the returned payloads
// and the headers and trailers
result.Payloads = append(result.Payloads, stream.Msg().Payload)
// If AfterNumResponses is specified, it will be a number > 0 here.
// If it wasn't specified, it will be -1, which means the totalRcvd
// will never be equal and we won't cancel.
if totalRcvd == timing.AfterNumResponses {
cancel()
}
}
if stream.Err() != nil {
// If an error was returned, convert it to a proto Error
result.Error = internal.ConvertErrorToProtoError(stream.Err())
}
return result, nil
}
func (i *invoker) clientStream(
ctx context.Context,
req *conformancev1.ClientCompatRequest,
) (*conformancev1.ClientResponseResult, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ctx = i.withWireCapture(ctx)
stream := i.client.ClientStream(ctx)
var numUnsent int
// Add the specified request headers to the request
internal.AddHeaders(req.RequestHeaders, stream.RequestHeader())
for i, msg := range req.RequestMessages {
csr := &conformancev1.ClientStreamRequest{}
if err := msg.UnmarshalTo(csr); err != nil {
return nil, err
}
// Sleep for any specified delay
time.Sleep(time.Duration(req.RequestDelayMs) * time.Millisecond)
if err := stream.Send(csr); err != nil && errors.Is(err, io.EOF) {
numUnsent = len(req.RequestMessages) - i
break
}
}
var protoErr *conformancev1.Error
var headers []*conformancev1.Header
var trailers []*conformancev1.Header
payloads := make([]*conformancev1.ConformancePayload, 0, 1)
// Cancellation timing
timing, err := internal.GetCancelTiming(req.Cancel)
if err != nil {
return nil, err
}
if timing.BeforeCloseSend != nil {
cancel()
} else if timing.AfterCloseSendMs >= 0 {
time.AfterFunc(time.Duration(timing.AfterCloseSendMs)*time.Millisecond, cancel)
}
resp, err := stream.CloseAndReceive()
if err != nil {
// If an error was returned, first convert it to a Connect error
// so that we can get the trailers from the Meta property. Then,
// convert _that_ to a proto Error so we can set it in the response.
connectErr := internal.ConvertErrorToConnectError(err)
trailers = internal.ConvertToProtoHeader(connectErr.Meta())
protoErr = internal.ConvertConnectToProtoError(connectErr)
} else {
// If the call was successful, get the returned payloads
// and the headers and trailers
payloads = append(payloads, resp.Msg.Payload)
headers = internal.ConvertToProtoHeader(resp.Header())
trailers = internal.ConvertToProtoHeader(resp.Trailer())
}
statusCode, feedback := i.examineWireDetails(ctx, headers, trailers)
return &conformancev1.ClientResponseResult{
ResponseHeaders: headers,
ResponseTrailers: trailers,
Payloads: payloads,
NumUnsentRequests: int32(numUnsent),
Error: protoErr,
HttpStatusCode: statusCode,
Feedback: feedback,
}, nil
}
func (i *invoker) bidiStream(
ctx context.Context,
req *conformancev1.ClientCompatRequest,
) (result *conformancev1.ClientResponseResult, err error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
result = &conformancev1.ClientResponseResult{}
ctx = i.withWireCapture(ctx)
stream := i.client.BidiStream(ctx)
defer func() {
// Always make sure stream is closed on exit.
closeErr := stream.CloseResponse()
if err != nil {
return
}
if result.Error == nil && closeErr != nil {
result.Error = internal.ConvertErrorToProtoError(closeErr)
}
if err == nil {
// Read headers and trailers from the stream
result.ResponseHeaders = internal.ConvertToProtoHeader(stream.ResponseHeader())
result.ResponseTrailers = internal.ConvertToProtoHeader(stream.ResponseTrailer())
result.HttpStatusCode, result.Feedback = i.examineWireDetails(ctx, result.ResponseHeaders, result.ResponseTrailers)
}
}()
// Add the specified request headers to the request
internal.AddHeaders(req.RequestHeaders, stream.RequestHeader())
fullDuplex := req.StreamType == conformancev1.StreamType_STREAM_TYPE_FULL_DUPLEX_BIDI_STREAM
// Cancellation timing
timing, err := internal.GetCancelTiming(req.Cancel)
if err != nil {
return nil, err
}
var protoErr *conformancev1.Error
totalRcvd := 0
for i, msg := range req.RequestMessages {
bsr := &conformancev1.BidiStreamRequest{}
if err := msg.UnmarshalTo(bsr); err != nil {
// Return the error and nil result because this is an
// unmarshalling error unrelated to the RPC
return nil, err
}
// Sleep for any specified delay
time.Sleep(time.Duration(req.RequestDelayMs) * time.Millisecond)
if err := stream.Send(bsr); err != nil && errors.Is(err, io.EOF) {
// Call receive to get the error and convert it to a proto error
if _, recvErr := stream.Receive(); recvErr != nil {
protoErr = internal.ConvertErrorToProtoError(recvErr)
} else {
// Just in case the receive call doesn't return the error,
// use the error returned from Send. Note this should never
// happen, but is here as a safeguard.
protoErr = internal.ConvertErrorToProtoError(err)
}
// Break the send loop
result.NumUnsentRequests = int32(len(req.RequestMessages) - i)
break
}
if fullDuplex {
// If this is a full duplex stream, receive a response for each request
msg, err := stream.Receive()
if err != nil {
if !errors.Is(err, io.EOF) {
// If an error was returned that is not an EOF, convert it
// to a proto Error. If the error was an EOF, that just means
// reads are done.
protoErr = internal.ConvertErrorToProtoError(err)
}
// Reads are done either because we received an error or an EOF
// In either case, break the outer loop
break
}
// If the call was successful, get the returned payloads
result.Payloads = append(result.Payloads, msg.Payload)
totalRcvd++
if totalRcvd == timing.AfterNumResponses {
cancel()
}
}
}
if timing.BeforeCloseSend != nil {
cancel()
}
// Sends are done, close the send side of the stream
if err := stream.CloseRequest(); err != nil {
return nil, err
}
if timing.AfterCloseSendMs >= 0 {
time.Sleep(time.Duration(timing.AfterCloseSendMs) * time.Millisecond)
cancel()
}
// If we received an error in any of the send logic or full-duplex reads, then exit
if protoErr != nil {
result.Error = protoErr
return result, nil
}
// Receive any remaining responses
for {
msg, err := stream.Receive()
if err != nil {
if !errors.Is(err, io.EOF) {
// If an error was returned that is not an EOF, convert it
// to a proto Error. If the error was an EOF, that just means
// reads are done.
protoErr = internal.ConvertErrorToProtoError(err)
}
break
}
// If the call was successful, save the payloads
result.Payloads = append(result.Payloads, msg.Payload)
totalRcvd++
if totalRcvd == timing.AfterNumResponses {
cancel()
}
}
if protoErr != nil {
result.Error = protoErr
}
return result, nil
}
func (i *invoker) unimplemented(
ctx context.Context,
req *conformancev1.ClientCompatRequest,
) (*conformancev1.ClientResponseResult, error) {
return doUnary(ctx, req, i, i.client.Unimplemented,
func(resp *conformancev1.UnimplementedResponse) *conformancev1.ConformancePayload {
return nil
})
}
func (i *invoker) withWireCapture(ctx context.Context) context.Context {
if !i.referenceMode {
return ctx
}
return withWireCapture(ctx)
}
func (i *invoker) examineWireDetails(ctx context.Context, headers, trailers []*conformancev1.Header) (*int32, []string) {
if !i.referenceMode {
return nil, nil
}
printer := &internal.SimplePrinter{}
statusCode, ok := examineWireDetails(ctx, printer)
var statusCodePtr *int32
if ok {
statusCodePtr = proto.Int32(int32(statusCode))
}
if headers != nil {
checkBinaryMetadata("headers", headers, printer)
checkBinaryMetadata("trailers", trailers, printer)
} else {
// all metadata together in one, from an error
checkBinaryMetadata("metadata", trailers, printer)
}
return statusCodePtr, printer.Messages
}
// userAgentClientInterceptor adds to the user-agent header on outgoing requests.
type userAgentClientInterceptor struct{}
func (userAgentClientInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
if req.Spec().IsClient {
// decorate user-agent with the program name and version
userAgent := fmt.Sprintf("%s %s/%s", req.Header().Get("User-Agent"), clientName, internal.Version)
req.Header().Set("User-Agent", userAgent)
}
return next(ctx, req)
}
}
func (userAgentClientInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
return func(ctx context.Context, spec connect.Spec) connect.StreamingClientConn {
conn := next(ctx, spec)
// decorate user-agent with the program name and version
userAgent := fmt.Sprintf("%s %s/%s", conn.RequestHeader().Get("User-Agent"), clientName, internal.Version)
conn.RequestHeader().Set("User-Agent", userAgent)
return conn
}
}
func (userAgentClientInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
return next
}