-
Notifications
You must be signed in to change notification settings - Fork 14
/
vanguard_test.go
1100 lines (1018 loc) · 31.8 KB
/
vanguard_test.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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023-2024 Buf Technologies, Inc.
//
// 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 vanguard
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"connectrpc.com/connect"
testv1 "connectrpc.com/vanguard/internal/gen/vanguard/test/v1"
"connectrpc.com/vanguard/internal/gen/vanguard/test/v1/testv1connect"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/genproto/googleapis/api/annotations"
"google.golang.org/genproto/googleapis/api/httpbody"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/dynamicpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
const (
defaultTestTimeout = 30 * time.Second
)
func TestServiceWithSchema(t *testing.T) {
t.Parallel()
file, err := makeFile("")
require.NoError(t, err)
svcDesc := file.Services().ByName("BlahService")
require.NotNil(t, svcDesc)
methodPath := "/" + string(svcDesc.FullName()) + "/Do"
t.Run("default_bespoke_resolver", func(t *testing.T) {
t.Parallel()
svc := NewServiceWithSchema(svcDesc, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
// Make sure we can validate the service and that the default resolver is able to
// correctly resolve request and response types.
transcoder, err := NewTranscoder([]*Service{svc})
require.NoError(t, err)
res := transcoder.methods[methodPath].resolver
// Resolver can also resolve other messages in the file.
_, err = res.FindMessageByName("foo.bar.baz.v1.Blue")
require.NoError(t, err)
// And it can resolve anything in the service file's transitive dependencies.
timestampType, err := res.FindMessageByName("google.protobuf.Timestamp")
require.NoError(t, err)
// All types are dynamic.
_, ok := timestampType.New().Interface().(*dynamicpb.Message)
assert.True(t, ok)
})
t.Run("default_bespoke_resolver_service_has_no_parent_file", func(t *testing.T) {
t.Parallel()
svcDescNoParent := &serviceWithNoParentFile{ServiceDescriptor: svcDesc}
svc := NewServiceWithSchema(svcDescNoParent, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
// Still works. But now we just use dynamic message types using the
// method descriptors.
transcoder, err := NewTranscoder([]*Service{svc})
require.NoError(t, err)
res := transcoder.methods[methodPath].resolver
// It cannot resolve other types that were in the same file.
_, err = res.FindMessageByName("foo.bar.baz.v1.Blue")
require.ErrorIs(t, err, protoregistry.NotFound)
// This type can be resolved, because the default resolver will fallback to global types.
timestampType, err := res.FindMessageByName("google.protobuf.Timestamp")
require.NoError(t, err)
// But since it is from global types, it is NOT a dynamic message type.
_, ok := timestampType.New().Interface().(*timestamppb.Timestamp)
assert.True(t, ok)
})
t.Run("uses_dynamic_message_type_with_bad_resolver", func(t *testing.T) {
t.Parallel()
svc := NewServiceWithSchema(
svcDesc,
http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),
// Global registry doesn't know about these types.
WithTypeResolver(protoregistry.GlobalTypes),
)
// Still works. But now we just use dynamic message types using the
// method descriptors.
transcoder, err := NewTranscoder([]*Service{svc})
require.NoError(t, err)
res := transcoder.methods[methodPath].resolver
// It cannot resolve other types that were in the same file.
_, err = res.FindMessageByName("foo.bar.baz.v1.Blue")
require.ErrorIs(t, err, protoregistry.NotFound)
// This type can be resolved, because the default resolver will fallback to global types.
timestampType, err := res.FindMessageByName("google.protobuf.Timestamp")
require.NoError(t, err)
// But since it is from global types, it is NOT a dynamic message type.
_, ok := timestampType.New().Interface().(*timestamppb.Timestamp)
assert.True(t, ok)
})
t.Run("fails_for_rest_only_because_no_http_rules", func(t *testing.T) {
t.Parallel()
svc := NewServiceWithSchema(
svcDesc,
http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),
WithTargetProtocols(ProtocolREST),
)
_, err := NewTranscoder([]*Service{svc})
require.ErrorContains(t, err, "service foo.bar.baz.v1.BlahService only supports REST target protocol but has no methods with HTTP rules")
})
}
func TestRuleSelector(t *testing.T) {
t.Parallel()
var interceptor testInterceptor
svc := NewService(testv1connect.NewLibraryServiceHandler(
testv1connect.UnimplementedLibraryServiceHandler{},
connect.WithInterceptors(&interceptor),
))
_, err := NewTranscoder([]*Service{svc}, WithRules(&annotations.HttpRule{
Selector: "grpc.health.v1.Health.Check",
Pattern: &annotations.HttpRule_Get{
Get: "/healthz",
},
}))
assert.ErrorContains(t, err, "rule \"grpc.health.v1.Health.Check\" does not match any methods") //nolint:testifylint
_, err = NewTranscoder([]*Service{svc}, WithRules(&annotations.HttpRule{
Selector: "invalid.*.Get",
Pattern: &annotations.HttpRule_Get{
Get: "/v1/*",
},
}))
assert.ErrorContains(t, err, "wildcard selector \"invalid.*.Get\" must be at the end") //nolint:testifylint
_, err = NewTranscoder([]*Service{svc}, WithRules(&annotations.HttpRule{
Selector: "grpc.health.v1.Health.*",
Pattern: &annotations.HttpRule_Get{
Get: "/healthz",
},
}))
assert.ErrorContains(t, err, "rule \"grpc.health.v1.Health.*\" does not match any methods") //nolint:testifylint
_, err = NewTranscoder([]*Service{svc}, WithRules(&annotations.HttpRule{
Pattern: &annotations.HttpRule_Get{
Get: "/v1/*",
},
}))
assert.ErrorContains(t, err, "rule missing selector") //nolint:testifylint
handler, err := NewTranscoder(
[]*Service{svc},
WithRules(&annotations.HttpRule{
Selector: "vanguard.test.v1.LibraryService.GetBook",
Pattern: &annotations.HttpRule_Get{
Get: "/v1/selector/{name=shelves/*/books/*}",
},
}),
)
require.NoError(t, err)
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, defaultTestTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/v1/selector/shelves/123/books/456", http.NoBody)
require.NoError(t, err)
req.Header.Set("Message", "hello")
req.Header.Set("Test", t.Name()) // for interceptor
req.Header.Set("Content-Type", "application/json")
rsp := httptest.NewRecorder()
interceptor.set(t, testStream{
method: testv1connect.LibraryServiceGetBookProcedure,
reqHeader: http.Header{
"Message": []string{"hello"},
},
rspHeader: http.Header{
"Message": []string{"world"},
},
msgs: []testMsg{
{in: &testMsgIn{
msg: &testv1.GetBookRequest{Name: "shelves/123/books/456"},
}},
{out: &testMsgOut{
msg: &testv1.Book{Name: "shelves/123/books/456"},
}},
},
})
defer interceptor.del(t)
handler.ServeHTTP(rsp, req)
result := rsp.Result()
defer result.Body.Close()
dump, err := httputil.DumpResponse(result, true)
require.NoError(t, err)
t.Log(string(dump))
assert.Equal(t, http.StatusOK, result.StatusCode)
assert.Equal(t, "application/json", result.Header.Get("Content-Type"))
assert.Equal(t, "world", result.Header.Get("Message"))
}
type testStream struct {
method string
reqHeader http.Header // expected
rspHeader http.Header // out
rspTrailer http.Header // out
msgs []testMsg // in, out
// If set, the error that a client expects, overriding any other error
// (or lack thereof) in msgs.
err *connect.Error
}
type testMsg struct {
in *testMsgIn
out *testMsgOut
}
func (o *testMsg) getIn() (*testMsgIn, error) {
if o == nil || o.in == nil {
return nil, errors.New("missing input message")
}
return o.in, nil
}
func (o *testMsg) getOut() (*testMsgOut, error) {
if o == nil || o.out == nil {
return nil, errors.New("missing output message")
}
return o.out, nil
}
func (o *testMsg) get() any {
if o.in != nil {
return o.in
}
if o.out != nil {
return o.out
}
return nil
}
type testMsgIn struct {
msg proto.Message
// An error on input means that the middleware should generate an error here.
// The msg is present so that runRPCTestCase knows what message to send, but
// if err != nil then the interceptor instead accepts the operation to be
// cancelled (and the middleware will send this error back to the clent).
err *connect.Error
}
type testMsgOut struct {
msg proto.Message
// If msg is nil, the interceptor will return this error instead of sending
// a message. But if both are non-nil, then the interceptor will send the
// message but expect an error doing so. So in that case, this error is
// expected by both the server handler and the client.
err *connect.Error
}
type ttStream struct {
*testing.T
testStream
started atomic.Bool
result error
done chan struct{}
}
func (s *ttStream) start() {
// Called from the interceptor when it starts handling the stream
s.started.Store(true)
}
func (s *ttStream) finish(result error) {
// Called from the interceptor when it finishes handling the stream
s.result = result
close(s.done)
}
func (s *ttStream) await(t *testing.T, expectServerDone bool) (serverInvoked bool, serverErr error) {
t.Helper()
// Called from test code to make sure server handler has completed.
// Returns any error that the interceptor finished with.
// Should only be called after the RPC appears to have completed in
// the test client.
if !s.started.Load() {
// Interceptor never started, so nothing to wait for.
return false, nil
}
if expectServerDone {
select {
case <-s.done:
return true, s.result
default:
t.Fatal("expecting server to already be done but it's not")
}
}
select {
case <-s.done:
return true, s.result
case <-time.After(3 * time.Second):
return true, errors.New("timeout: interceptor still did not finish after 3 seconds")
}
}
type testInterceptor struct {
sync.Map
}
func (i *testInterceptor) get(testName string) (*ttStream, bool) {
val, ok := i.Load(testName)
if !ok {
return nil, false
}
stream, ok := val.(*ttStream)
return stream, ok
}
func (i *testInterceptor) set(t *testing.T, stream testStream) func(*testing.T, bool) (bool, error) {
t.Helper()
str := &ttStream{
T: t,
testStream: stream,
done: make(chan struct{}),
}
i.Store(t.Name(), str)
// The returned function can be used by test code to await server completion.
// (Useful in the event that middleware cancels the operation early, so client
// could see a completed response while server still running concurrently.)
return str.await
}
func (i *testInterceptor) del(t *testing.T) {
t.Helper()
i.Delete(t.Name())
}
func (i *testInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
return func(
ctx context.Context,
req connect.AnyRequest,
) (_ connect.AnyResponse, resultError error) {
if err := assertTestTimeoutEncoded(ctx); err != nil {
return nil, err
}
val := req.Header().Get("Test")
if val == "" {
return next(ctx, req)
}
stream, ok := i.get(val)
if !ok {
return nil, fmt.Errorf("invalid testCase header: %s", val)
}
stream.start()
defer func() {
stream.finish(resultError)
}()
if !assert.Equal(stream.T, stream.method, req.Spec().Procedure) {
return nil, connect.NewError(connect.CodeFailedPrecondition, fmt.Errorf("expected %s, got %s", stream.method, req.Spec().Procedure))
}
assert.Subset(stream.T, req.Header(), stream.reqHeader)
if len(stream.msgs) != 2 {
err := fmt.Errorf("expected 2 messages, got %d", len(stream.msgs))
return nil, err
}
inn, err := stream.msgs[0].getIn()
if err != nil {
return nil, err
}
if inn.err != nil {
return nil, errors.New("testMsgIn should not have err field set for unary request")
}
out, err := stream.msgs[1].getOut()
if err != nil {
return nil, err
}
if out.msg != nil && out.err != nil {
return nil, errors.New("testMsgOut should not have both msg and err fields set for unary request")
}
msg, ok := req.Any().(proto.Message)
if !ok {
return nil, fmt.Errorf("expected proto.Message, got %T", req.Any())
}
diff := cmp.Diff(msg, inn.msg, protocmp.Transform())
if diff != "" {
stream.Error(diff)
return nil, errors.New("unexpected message diff")
}
if out.err != nil {
err := out.err
if len(stream.rspHeader) > 0 {
// make a copy of the error and add response headers to it
err = connect.NewError(out.err.Code(), out.err.Unwrap())
for _, detail := range out.err.Details() {
err.AddDetail(detail)
}
for key, values := range stream.rspHeader {
err.Meta()[key] = values
}
}
return nil, err
}
// Build response with headers.
rsp := &AnyResponse{msg: out.msg}
for key, values := range stream.rspHeader {
rsp.Header()[key] = values
}
for key, values := range stream.rspTrailer {
rsp.Trailer()[key] = values
}
return rsp, nil
}
}
func (i *testInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
return next
}
func (i *testInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
return func(
ctx context.Context,
conn connect.StreamingHandlerConn,
) (resultError error) {
if err := assertTestTimeoutEncoded(ctx); err != nil {
return err
}
val := conn.RequestHeader().Get("Test")
if val == "" {
return next(ctx, conn)
}
stream, ok := i.get(val)
if !ok {
return fmt.Errorf("invalid testCase header: %s", val)
}
stream.start()
defer func() {
stream.finish(resultError)
}()
if !assert.Equal(stream.T, stream.method, conn.Spec().Procedure) {
return connect.NewError(connect.CodeFailedPrecondition, fmt.Errorf("expected %s, got %s", stream.method, conn.Spec().Procedure))
}
stream.Log("WrapStreamingHandler", val)
assert.Subset(stream.T, conn.RequestHeader(), stream.reqHeader)
for key, vals := range stream.rspHeader {
conn.ResponseHeader()[key] = vals
}
for _, msg := range stream.msgs {
switch msg := msg.get().(type) {
case *testMsgIn:
got := proto.Clone(msg.msg)
err := conn.Receive(got)
switch {
case msg.err != nil:
// We're expecting an error at this point, which prevented this
// message from being delivered.
if err == nil {
err = errors.New("expecting an error receiving message but got none")
}
return err
case err != nil:
return err // not expecting an error
default:
diff := cmp.Diff(got, msg.msg, protocmp.Transform())
assert.Empty(stream.T, diff, "message didn't match")
if diff != "" {
return fmt.Errorf("message didn't match: %s", diff)
}
}
case *testMsgOut:
switch {
case msg.msg != nil && msg.err != nil:
err := conn.Send(msg.msg)
if err == nil {
err = errors.New("expecting an error sending message but got none")
}
return err
case msg.err != nil:
return msg.err
default:
if err := conn.Send(msg.msg); err != nil {
return err
}
}
default:
return errors.New("expected message")
}
}
for key, vals := range stream.rspTrailer {
conn.ResponseTrailer()[key] = vals
}
return nil
}
}
func (i *testInterceptor) restUnaryHandler(
codec Codec, comp *compressionPool,
) http.HandlerFunc {
codecNames := map[string]string{
"application/json": "json",
}
handler := func(stream *ttStream, rsp http.ResponseWriter, req *http.Request) error {
if len(stream.msgs) != 2 {
return fmt.Errorf("expected 2 messages, got %d", len(stream.msgs))
}
inn, err := stream.msgs[0].getIn()
if err != nil {
return err
}
out, err := stream.msgs[1].getOut()
if err != nil {
return err
}
assert.Equal(stream.T, stream.method, req.URL.String(), "url didn't match")
assert.Subset(stream.T, req.Header, stream.reqHeader, "headers didn't match")
contentType := req.Header.Get("Content-Type")
encoding := req.Header.Get("Content-Encoding")
acceptEncoding := req.Header.Get("Accept-Encoding")
body, err := io.ReadAll(req.Body)
if err != nil {
return err
}
if comp != nil && len(body) > 0 && encoding != "" {
assert.Equal(stream.T, comp.Name(), encoding, "expected encoding")
var dst bytes.Buffer
if err := comp.decompress(&dst, bytes.NewBuffer(body)); err != nil {
return err
}
body = dst.Bytes()
}
got := proto.Clone(inn.msg)
if len(body) > 0 { //nolint:nestif
if restIsHTTPBody(got.ProtoReflect().Descriptor(), nil) {
got, _ := got.(*httpbody.HttpBody)
got.ContentType = contentType
got.Data = body
} else {
codecName := codecNames[contentType]
if !assert.Equal(stream.T, codec.Name(), codecName, "codec didn't match") {
return errors.New("codec didn't match")
}
if err := codec.Unmarshal(body, got); err != nil {
return err
}
}
}
diff := cmp.Diff(got, inn.msg, protocmp.Transform())
assert.Empty(stream.T, diff, "message didn't match")
// Write headers.
for key, values := range stream.rspHeader {
for _, value := range values {
rsp.Header().Add(key, value)
}
}
// Write error, if any.
if out.err != nil {
httpWriteError(rsp, out.err)
return nil // ignore
}
// Write body.
rsp.Header().Set("Content-Type", contentType)
rsp.Header().Set("Content-Encoding", "identity")
if restIsHTTPBody(out.msg.ProtoReflect().Descriptor(), nil) { //nolint:nestif
msg, _ := out.msg.(*httpbody.HttpBody)
rsp.Header().Set("Content-Type", msg.GetContentType())
_, err = rsp.Write(msg.GetData())
require.NoError(stream.T, err, "failed to write response")
} else {
body, err = codec.MarshalAppend(nil, out.msg)
if err != nil {
return err
}
if comp != nil && acceptEncoding != "" {
assert.Equal(stream.T, comp.Name(), acceptEncoding, "expected encoding")
rsp.Header().Set("Content-Encoding", comp.Name())
var dst bytes.Buffer
if err := comp.compress(&dst, bytes.NewBuffer(body)); err != nil {
return err
}
body = dst.Bytes()
}
_, err = rsp.Write(body)
require.NoError(stream.T, err, "failed to write response")
}
// Write trailers.
for key, values := range stream.rspTrailer {
for _, value := range values {
rsp.Header().Add(key, value)
}
}
return nil
}
return func(rsp http.ResponseWriter, req *http.Request) {
val := req.Header.Get("Test")
if val == "" {
http.Error(rsp, "missing test header", http.StatusInternalServerError)
return
}
stream, ok := i.get(val)
if !ok {
http.Error(rsp, "invalid test header", http.StatusInternalServerError)
return
}
timeoutStr := req.Header.Get("X-Server-Timeout")
timeout, err := restDecodeTimeout(timeoutStr)
if err != nil {
http.Error(rsp, "invalid timeout header", http.StatusInternalServerError)
return
}
ctx, cancel := context.WithTimeout(req.Context(), timeout)
defer cancel()
if err := assertTestTimeoutEncoded(ctx); err != nil {
http.Error(rsp, err.Error(), http.StatusInternalServerError)
return
}
req = req.WithContext(ctx)
if err := handler(stream, rsp, req); err != nil {
stream.T.Error(err)
http.Error(rsp, err.Error(), http.StatusInternalServerError)
}
}
}
type unusedType struct{}
type AnyResponse struct {
connect.Response[unusedType]
msg proto.Message
}
func (a *AnyResponse) Any() any { return a.msg }
func getCompressor(t *testing.T, name string) connect.Compressor {
t.Helper()
switch name {
case CompressionGzip:
return defaultGzipCompressor()
case CompressionIdentity:
return nil
default:
t.Fatalf("unknown compression: %s", name)
return nil
}
}
func getDecompressor(t *testing.T, name string) connect.Decompressor {
t.Helper()
switch name {
case CompressionGzip:
return defaultGzipDecompressor()
case CompressionIdentity:
return nil
default:
t.Fatalf("unknown compression: %s", name)
return nil
}
}
type testServer struct {
name string
server *httptest.Server
}
func appendClientProtocolOptions(t *testing.T, opts []connect.ClientOption, protocol Protocol) []connect.ClientOption {
t.Helper()
switch protocol { //nolint:exhaustive
case ProtocolGRPC:
return append(opts, connect.WithGRPC())
case ProtocolGRPCWeb:
return append(opts, connect.WithGRPCWeb())
case ProtocolConnect:
return opts // no option needed
default:
t.Fatalf("unknown protocol: %s", protocol)
}
return opts
}
func appendClientCodecOptions(t *testing.T, opts []connect.ClientOption, codec string) []connect.ClientOption {
t.Helper()
switch codec {
case CodecJSON:
return append(opts, connect.WithProtoJSON())
case CodecProto:
// default...
default:
t.Fatalf("unknown codec: %s", codec)
}
return opts
}
func appendClientCompressionOptions(t *testing.T, opts []connect.ClientOption, compression string) []connect.ClientOption {
t.Helper()
switch compression {
case CompressionIdentity:
return append(opts,
// nil factory functions *remove* support for gzip, which is otherwise on by default.
connect.WithAcceptCompression(
CompressionGzip, nil, nil,
),
)
case CompressionGzip:
return append(opts,
connect.WithAcceptCompression(
CompressionGzip,
func() connect.Decompressor {
return getDecompressor(t, CompressionGzip)
},
func() connect.Compressor {
return getCompressor(t, CompressionGzip)
},
),
connect.WithSendCompression(compression),
)
default:
t.Fatalf("unknown compression: %s", compression)
}
return opts
}
func makeRequest[T any](headers http.Header, msg *T) *connect.Request[T] {
req := connect.NewRequest(msg)
for k, v := range headers {
req.Header()[k] = v
}
return req
}
type unaryMethod[Req, Resp any] func(context.Context, *connect.Request[Req]) (*connect.Response[Resp], error)
type serverStreamMethod[Req, Resp any] func(context.Context, *connect.Request[Req]) (*connect.ServerStreamForClient[Resp], error)
type clientStreamMethod[Req, Resp any] func(context.Context) *connect.ClientStreamForClient[Req, Resp]
type bidiStreamMethod[Req, Resp any] func(context.Context) *connect.BidiStreamForClient[Req, Resp]
func outputFromUnary[Req, Resp any](
ctx context.Context,
method unaryMethod[Req, Resp],
headers http.Header,
reqs []proto.Message,
) (http.Header, []proto.Message, http.Header, error) {
ctx, cancel := context.WithTimeout(ctx, defaultTestTimeout)
defer cancel()
if len(reqs) != 1 {
return nil, nil, nil, fmt.Errorf("unary method takes exactly 1 request but got %d", len(reqs))
}
req := any(reqs[0])
resp, err := method(ctx, makeRequest(headers, req.(*Req)))
if err != nil {
var headers http.Header
if connErr := new(connect.Error); errors.As(err, &connErr) {
headers = connErr.Meta()
}
return headers, nil, nil, err
}
msg := any(resp.Msg)
return resp.Header(), []proto.Message{msg.(proto.Message)}, resp.Trailer(), nil
}
func outputFromServerStream[Req, Resp any](
ctx context.Context,
method serverStreamMethod[Req, Resp],
headers http.Header,
reqs []proto.Message,
) (http.Header, []proto.Message, http.Header, error) {
ctx, cancel := context.WithTimeout(ctx, defaultTestTimeout)
defer cancel()
if len(reqs) != 1 {
return nil, nil, nil, fmt.Errorf("unary method takes exactly 1 request but got %d", len(reqs))
}
req := any(reqs[0])
str, err := method(ctx, makeRequest(headers, req.(*Req)))
if err != nil {
var headers http.Header
if connErr := new(connect.Error); errors.As(err, &connErr) {
headers = connErr.Meta()
}
return headers, nil, nil, err
}
var msgs []proto.Message
for str.Receive() {
msg := any(str.Msg())
msgs = append(msgs, msg.(proto.Message))
}
return str.ResponseHeader(), msgs, str.ResponseTrailer(), str.Err()
}
func outputFromClientStream[Req, Resp any](
ctx context.Context,
method clientStreamMethod[Req, Resp],
headers http.Header,
reqs []proto.Message,
) (http.Header, []proto.Message, http.Header, error) {
ctx, cancel := context.WithTimeout(ctx, defaultTestTimeout)
defer cancel()
str := method(ctx)
for k, v := range headers {
str.RequestHeader()[k] = v
}
for _, msg := range reqs {
if str.Send(any(msg).(*Req)) != nil {
// we don't need this error; we'll get the error below
// since str.CloseAndReceive returns the actual RPC errors
break
}
}
resp, err := str.CloseAndReceive()
if err != nil {
var headers http.Header
if connErr := new(connect.Error); errors.As(err, &connErr) {
headers = connErr.Meta()
}
return headers, nil, nil, err
}
msg := any(resp.Msg)
return resp.Header(), []proto.Message{msg.(proto.Message)}, resp.Trailer(), nil
}
func outputFromBidiStream[Req, Resp any](
ctx context.Context,
method bidiStreamMethod[Req, Resp],
headers http.Header,
reqs []proto.Message,
) (http.Header, []proto.Message, http.Header, error) {
ctx, cancel := context.WithTimeout(ctx, defaultTestTimeout)
defer cancel()
str := method(ctx)
defer func() {
_ = str.CloseResponse()
}()
var msgs []proto.Message
var err error
done := make(chan struct{})
go func() {
defer close(done)
for {
var resp *Resp
resp, err = str.Receive()
if err != nil {
if errors.Is(err, io.EOF) {
err = nil
}
return
}
msg := any(resp)
msgs = append(msgs, msg.(proto.Message))
}
}()
for k, v := range headers {
str.RequestHeader()[k] = v
}
for _, msg := range reqs {
if str.Send(any(msg).(*Req)) != nil {
// we don't need this error; we'll get the error from above
// goroutine since str.Receive returns the actual RPC errors
break
}
}
<-done
return str.ResponseHeader(), msgs, str.ResponseTrailer(), err
}
func protocolAssertMiddleware(
protocol Protocol, codec string, compression string,
next http.Handler,
) http.HandlerFunc {
var allowedCompression []string
if compression != "" && compression != CompressionIdentity {
// a server expecting gzip compression also allows identity/uncompressed
allowedCompression = []string{compression, CompressionIdentity, ""}
} else {
allowedCompression = []string{CompressionIdentity, ""}
}
return func(rsp http.ResponseWriter, req *http.Request) {
var wantHdr map[string][]string
switch protocol { //nolint:exhaustive
case ProtocolGRPC:
wantContentType := []string{"application/grpc+" + codec}
if codec == CodecProto {
wantContentType = append(wantContentType, "application/grpc")
}
wantHdr = map[string][]string{
"Content-Type": wantContentType,
"Grpc-Encoding": allowedCompression,
}
case ProtocolGRPCWeb:
wantContentType := []string{"application/grpc-web+" + codec}
if codec == CodecProto {
wantContentType = append(wantContentType, "application/grpc-web")
}
wantHdr = map[string][]string{
"Content-Type": wantContentType,
"Grpc-Encoding": allowedCompression,
}
case ProtocolConnect:
if strings.HasPrefix(req.Header.Get("Content-Type"), "application/connect") {
wantHdr = map[string][]string{
"Content-Type": {"application/connect+" + codec},
"Connect-Content-Encoding": allowedCompression,
}
} else if req.Method == http.MethodPost {
wantHdr = map[string][]string{
"Content-Type": {"application/" + codec},
"Content-Encoding": allowedCompression,
}
}
default:
http.Error(rsp, "unknown protocol", http.StatusInternalServerError)
return
}
for key, vals := range wantHdr {
var found bool
gotHdr := req.Header.Get(key)
for _, val := range vals {
if gotHdr == val {
found = true
break
}
}
if !found {
http.Error(rsp, fmt.Sprintf("header %s is %q; should be one of [%v]", key, gotHdr, vals), http.StatusInternalServerError)
return
}
}
next.ServeHTTP(rsp, req)
}
}
func runRPCTestCase[Client any](
t *testing.T,
interceptor *testInterceptor,
client Client,
invoke func(Client, http.Header, []proto.Message) (http.Header, []proto.Message, http.Header, error),
stream testStream,
) {
t.Helper()
awaitServer := interceptor.set(t, stream)
defer interceptor.del(t)
reqHeaders := http.Header{}
reqHeaders.Set("Test", t.Name()) // test header
for k, v := range stream.reqHeader {
reqHeaders[k] = v
}
var reqMsgs []proto.Message
for _, streamMsg := range stream.msgs {
if streamMsg.in != nil {
reqMsgs = append(reqMsgs, streamMsg.in.msg)
}
}
headers, responses, trailers, err := invoke(client, reqHeaders, reqMsgs)
if err != nil {
t.Logf("RPC error: %v", err)
}
var expectedErr *connect.Error
expectServerDone := true
var expectServerCancel bool
for _, streamMsg := range stream.msgs {
if streamMsg.in != nil && streamMsg.in.err != nil {
expectedErr = streamMsg.in.err