forked from connectrpc/connect-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol_connect.go
1273 lines (1168 loc) · 39.6 KB
/
protocol_connect.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 2021-2023 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 connect
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"time"
"google.golang.org/protobuf/types/known/anypb"
)
const (
connectUnaryHeaderCompression = "Content-Encoding"
connectUnaryHeaderAcceptCompression = "Accept-Encoding"
connectUnaryTrailerPrefix = "Trailer-"
connectStreamingHeaderCompression = "Connect-Content-Encoding"
connectStreamingHeaderAcceptCompression = "Connect-Accept-Encoding"
connectHeaderTimeout = "Connect-Timeout-Ms"
connectHeaderProtocolVersion = "Connect-Protocol-Version"
connectProtocolVersion = "1"
headerVary = "Vary"
connectFlagEnvelopeEndStream = 0b00000010
connectUnaryContentTypePrefix = "application/"
connectUnaryContentTypeJSON = connectUnaryContentTypePrefix + "json"
connectStreamingContentTypePrefix = "application/connect+"
connectUnaryEncodingQueryParameter = "encoding"
connectUnaryMessageQueryParameter = "message"
connectUnaryBase64QueryParameter = "base64"
connectUnaryCompressionQueryParameter = "compression"
connectUnaryConnectQueryParameter = "connect"
connectUnaryConnectQueryValue = "v" + connectProtocolVersion
)
// defaultConnectUserAgent returns a User-Agent string similar to those used in gRPC.
//
//nolint:gochecknoglobals
var defaultConnectUserAgent = fmt.Sprintf("connect-go/%s (%s)", Version, runtime.Version())
type protocolConnect struct{}
// NewHandler implements protocol, so it must return an interface.
func (*protocolConnect) NewHandler(params *protocolHandlerParams) protocolHandler {
methods := make(map[string]struct{})
methods[http.MethodPost] = struct{}{}
if params.Spec.StreamType == StreamTypeUnary && params.IdempotencyLevel == IdempotencyNoSideEffects {
methods[http.MethodGet] = struct{}{}
}
contentTypes := make(map[string]struct{})
for _, name := range params.Codecs.Names() {
if params.Spec.StreamType == StreamTypeUnary {
contentTypes[canonicalizeContentType(connectUnaryContentTypePrefix+name)] = struct{}{}
continue
}
contentTypes[canonicalizeContentType(connectStreamingContentTypePrefix+name)] = struct{}{}
}
return &connectHandler{
protocolHandlerParams: *params,
methods: methods,
accept: contentTypes,
}
}
// NewClient implements protocol, so it must return an interface.
func (*protocolConnect) NewClient(params *protocolClientParams) (protocolClient, error) {
return &connectClient{
protocolClientParams: *params,
peer: newPeerFromURL(params.URL, ProtocolConnect),
}, nil
}
type connectHandler struct {
protocolHandlerParams
methods map[string]struct{}
accept map[string]struct{}
}
func (h *connectHandler) Methods() map[string]struct{} {
return h.methods
}
func (h *connectHandler) ContentTypes() map[string]struct{} {
return h.accept
}
func (*connectHandler) SetTimeout(request *http.Request) (context.Context, context.CancelFunc, error) {
timeout := getHeaderCanonical(request.Header, connectHeaderTimeout)
if timeout == "" {
return request.Context(), nil, nil
}
if len(timeout) > 10 {
return nil, nil, errorf(CodeInvalidArgument, "parse timeout: %q has >10 digits", timeout)
}
millis, err := strconv.ParseInt(timeout, 10 /* base */, 64 /* bitsize */)
if err != nil {
return nil, nil, errorf(CodeInvalidArgument, "parse timeout: %w", err)
}
ctx, cancel := context.WithTimeout(
request.Context(),
time.Duration(millis)*time.Millisecond,
)
return ctx, cancel, nil
}
func (h *connectHandler) CanHandlePayload(request *http.Request, contentType string) bool {
if request.Method == http.MethodGet {
query := request.URL.Query()
codecName := query.Get(connectUnaryEncodingQueryParameter)
contentType = connectContentTypeFromCodecName(
h.Spec.StreamType,
codecName,
)
}
_, ok := h.accept[contentType]
return ok
}
func (h *connectHandler) NewConn(
responseWriter http.ResponseWriter,
request *http.Request,
) (handlerConnCloser, bool) {
query := request.URL.Query()
// We need to parse metadata before entering the interceptor stack; we'll
// send the error to the client later on.
var contentEncoding, acceptEncoding string
if h.Spec.StreamType == StreamTypeUnary {
if request.Method == http.MethodGet {
contentEncoding = query.Get(connectUnaryCompressionQueryParameter)
} else {
contentEncoding = getHeaderCanonical(request.Header, connectUnaryHeaderCompression)
}
acceptEncoding = getHeaderCanonical(request.Header, connectUnaryHeaderAcceptCompression)
} else {
contentEncoding = getHeaderCanonical(request.Header, connectStreamingHeaderCompression)
acceptEncoding = getHeaderCanonical(request.Header, connectStreamingHeaderAcceptCompression)
}
requestCompression, responseCompression, failed := negotiateCompression(
h.CompressionPools,
contentEncoding,
acceptEncoding,
)
if failed == nil {
failed = checkServerStreamsCanFlush(h.Spec, responseWriter)
}
if failed == nil && request.Method == http.MethodGet {
version := query.Get(connectUnaryConnectQueryParameter)
if version == "" && h.RequireConnectProtocolHeader {
failed = errorf(CodeInvalidArgument, "missing required query parameter: set %s to %q", connectUnaryConnectQueryParameter, connectUnaryConnectQueryValue)
} else if version != "" && version != connectUnaryConnectQueryValue {
failed = errorf(CodeInvalidArgument, "%s must be %q: got %q", connectUnaryConnectQueryParameter, connectUnaryConnectQueryValue, version)
}
}
if failed == nil && request.Method == http.MethodPost {
version := getHeaderCanonical(request.Header, connectHeaderProtocolVersion)
if version == "" && h.RequireConnectProtocolHeader {
failed = errorf(CodeInvalidArgument, "missing required header: set %s to %q", connectHeaderProtocolVersion, connectProtocolVersion)
} else if version != "" && version != connectProtocolVersion {
failed = errorf(CodeInvalidArgument, "%s must be %q: got %q", connectHeaderProtocolVersion, connectProtocolVersion, version)
}
}
var requestBody io.ReadCloser
var contentType, codecName string
if request.Method == http.MethodGet {
if failed == nil && !query.Has(connectUnaryEncodingQueryParameter) {
failed = errorf(CodeInvalidArgument, "missing %s parameter", connectUnaryEncodingQueryParameter)
} else if failed == nil && !query.Has(connectUnaryMessageQueryParameter) {
failed = errorf(CodeInvalidArgument, "missing %s parameter", connectUnaryMessageQueryParameter)
}
msg := query.Get(connectUnaryMessageQueryParameter)
msgReader := queryValueReader(msg, query.Get(connectUnaryBase64QueryParameter) == "1")
requestBody = io.NopCloser(msgReader)
codecName = query.Get(connectUnaryEncodingQueryParameter)
contentType = connectContentTypeFromCodecName(
h.Spec.StreamType,
codecName,
)
} else {
requestBody = request.Body
contentType = getHeaderCanonical(request.Header, headerContentType)
codecName = connectCodecFromContentType(
h.Spec.StreamType,
contentType,
)
}
codec := h.Codecs.Get(codecName)
// The codec can be nil in the GET request case; that's okay: when failed
// is non-nil, codec is never used.
if failed == nil && codec == nil {
failed = errorf(CodeInvalidArgument, "invalid message encoding: %q", codecName)
}
// Write any remaining headers here:
// (1) any writes to the stream will implicitly send the headers, so we
// should get all of gRPC's required response headers ready.
// (2) interceptors should be able to see these headers.
//
// Since we know that these header keys are already in canonical form, we can
// skip the normalization in Header.Set.
header := responseWriter.Header()
header[headerContentType] = []string{contentType}
acceptCompressionHeader := connectUnaryHeaderAcceptCompression
if h.Spec.StreamType != StreamTypeUnary {
acceptCompressionHeader = connectStreamingHeaderAcceptCompression
// We only write the request encoding header here for streaming calls,
// since the streaming envelope lets us choose whether to compress each
// message individually. For unary, we won't know whether we're compressing
// the request until we see how large the payload is.
if responseCompression != compressionIdentity {
header[connectStreamingHeaderCompression] = []string{responseCompression}
}
}
header[acceptCompressionHeader] = []string{h.CompressionPools.CommaSeparatedNames()}
var conn handlerConnCloser
peer := Peer{
Addr: request.RemoteAddr,
Protocol: ProtocolConnect,
Query: query,
}
if h.Spec.StreamType == StreamTypeUnary {
conn = &connectUnaryHandlerConn{
spec: h.Spec,
peer: peer,
request: request,
responseWriter: responseWriter,
marshaler: connectUnaryMarshaler{
writer: responseWriter,
codec: codec,
compressMinBytes: h.CompressMinBytes,
compressionName: responseCompression,
compressionPool: h.CompressionPools.Get(responseCompression),
bufferPool: h.BufferPool,
header: responseWriter.Header(),
sendMaxBytes: h.SendMaxBytes,
},
unmarshaler: connectUnaryUnmarshaler{
reader: requestBody,
codec: codec,
compressionPool: h.CompressionPools.Get(requestCompression),
bufferPool: h.BufferPool,
readMaxBytes: h.ReadMaxBytes,
},
responseTrailer: make(http.Header),
}
} else {
conn = &connectStreamingHandlerConn{
spec: h.Spec,
peer: peer,
request: request,
responseWriter: responseWriter,
marshaler: connectStreamingMarshaler{
envelopeWriter: envelopeWriter{
writer: responseWriter,
codec: codec,
compressMinBytes: h.CompressMinBytes,
compressionPool: h.CompressionPools.Get(responseCompression),
bufferPool: h.BufferPool,
sendMaxBytes: h.SendMaxBytes,
},
},
unmarshaler: connectStreamingUnmarshaler{
envelopeReader: envelopeReader{
reader: requestBody,
codec: codec,
compressionPool: h.CompressionPools.Get(requestCompression),
bufferPool: h.BufferPool,
readMaxBytes: h.ReadMaxBytes,
},
},
responseTrailer: make(http.Header),
}
}
conn = wrapHandlerConnWithCodedErrors(conn)
if failed != nil {
// Negotiation failed, so we can't establish a stream.
_ = conn.Close(failed)
return nil, false
}
return conn, true
}
type connectClient struct {
protocolClientParams
peer Peer
}
func (c *connectClient) Peer() Peer {
return c.peer
}
func (c *connectClient) WriteRequestHeader(streamType StreamType, header http.Header) {
// We know these header keys are in canonical form, so we can bypass all the
// checks in Header.Set.
if getHeaderCanonical(header, headerUserAgent) == "" {
header[headerUserAgent] = []string{defaultConnectUserAgent}
}
header[connectHeaderProtocolVersion] = []string{connectProtocolVersion}
header[headerContentType] = []string{
connectContentTypeFromCodecName(streamType, c.Codec.Name()),
}
acceptCompressionHeader := connectUnaryHeaderAcceptCompression
if streamType != StreamTypeUnary {
// If we don't set Accept-Encoding, by default http.Client will ask the
// server to compress the whole stream. Since we're already compressing
// each message, this is a waste.
header[connectUnaryHeaderAcceptCompression] = []string{compressionIdentity}
acceptCompressionHeader = connectStreamingHeaderAcceptCompression
// We only write the request encoding header here for streaming calls,
// since the streaming envelope lets us choose whether to compress each
// message individually. For unary, we won't know whether we're compressing
// the request until we see how large the payload is.
if c.CompressionName != "" && c.CompressionName != compressionIdentity {
header[connectStreamingHeaderCompression] = []string{c.CompressionName}
}
}
if acceptCompression := c.CompressionPools.CommaSeparatedNames(); acceptCompression != "" {
header[acceptCompressionHeader] = []string{acceptCompression}
}
}
func (c *connectClient) NewConn(
ctx context.Context,
spec Spec,
header http.Header,
) StreamingClientConn {
if deadline, ok := ctx.Deadline(); ok {
millis := int64(time.Until(deadline) / time.Millisecond)
if millis > 0 {
encoded := strconv.FormatInt(millis, 10 /* base */)
if len(encoded) <= 10 {
header[connectHeaderTimeout] = []string{encoded}
} // else effectively unbounded
}
}
duplexCall := newDuplexHTTPCall(ctx, c.HTTPClient, c.URL, spec, header)
var conn StreamingClientConn
if spec.StreamType == StreamTypeUnary {
unaryConn := &connectUnaryClientConn{
spec: spec,
peer: c.Peer(),
duplexCall: duplexCall,
compressionPools: c.CompressionPools,
bufferPool: c.BufferPool,
marshaler: connectUnaryRequestMarshaler{
connectUnaryMarshaler: connectUnaryMarshaler{
writer: duplexCall,
codec: c.Codec,
compressMinBytes: c.CompressMinBytes,
compressionName: c.CompressionName,
compressionPool: c.CompressionPools.Get(c.CompressionName),
bufferPool: c.BufferPool,
header: duplexCall.Header(),
sendMaxBytes: c.SendMaxBytes,
},
},
unmarshaler: connectUnaryUnmarshaler{
reader: duplexCall,
codec: c.Codec,
bufferPool: c.BufferPool,
readMaxBytes: c.ReadMaxBytes,
},
responseHeader: make(http.Header),
responseTrailer: make(http.Header),
}
if spec.IdempotencyLevel == IdempotencyNoSideEffects {
unaryConn.marshaler.enableGet = c.EnableGet
unaryConn.marshaler.getURLMaxBytes = c.GetURLMaxBytes
unaryConn.marshaler.getUseFallback = c.GetUseFallback
unaryConn.marshaler.duplexCall = duplexCall
if stableCodec, ok := c.Codec.(stableCodec); ok {
unaryConn.marshaler.stableCodec = stableCodec
}
}
conn = unaryConn
duplexCall.SetValidateResponse(unaryConn.validateResponse)
} else {
streamingConn := &connectStreamingClientConn{
spec: spec,
peer: c.Peer(),
duplexCall: duplexCall,
compressionPools: c.CompressionPools,
bufferPool: c.BufferPool,
codec: c.Codec,
marshaler: connectStreamingMarshaler{
envelopeWriter: envelopeWriter{
writer: duplexCall,
codec: c.Codec,
compressMinBytes: c.CompressMinBytes,
compressionPool: c.CompressionPools.Get(c.CompressionName),
bufferPool: c.BufferPool,
sendMaxBytes: c.SendMaxBytes,
},
},
unmarshaler: connectStreamingUnmarshaler{
envelopeReader: envelopeReader{
reader: duplexCall,
codec: c.Codec,
bufferPool: c.BufferPool,
readMaxBytes: c.ReadMaxBytes,
},
},
responseHeader: make(http.Header),
responseTrailer: make(http.Header),
}
conn = streamingConn
duplexCall.SetValidateResponse(streamingConn.validateResponse)
}
return wrapClientConnWithCodedErrors(conn)
}
type connectUnaryClientConn struct {
spec Spec
peer Peer
duplexCall *duplexHTTPCall
compressionPools readOnlyCompressionPools
bufferPool *bufferPool
marshaler connectUnaryRequestMarshaler
unmarshaler connectUnaryUnmarshaler
responseHeader http.Header
responseTrailer http.Header
}
func (cc *connectUnaryClientConn) Spec() Spec {
return cc.spec
}
func (cc *connectUnaryClientConn) Peer() Peer {
return cc.peer
}
func (cc *connectUnaryClientConn) Send(msg any) error {
if err := cc.marshaler.Marshal(msg); err != nil {
return err
}
return nil // must be a literal nil: nil *Error is a non-nil error
}
func (cc *connectUnaryClientConn) RequestHeader() http.Header {
return cc.duplexCall.Header()
}
func (cc *connectUnaryClientConn) CloseRequest() error {
return cc.duplexCall.CloseWrite()
}
func (cc *connectUnaryClientConn) Receive(msg any) error {
cc.duplexCall.BlockUntilResponseReady()
if err := cc.unmarshaler.Unmarshal(msg); err != nil {
return err
}
return nil // must be a literal nil: nil *Error is a non-nil error
}
func (cc *connectUnaryClientConn) ResponseHeader() http.Header {
cc.duplexCall.BlockUntilResponseReady()
return cc.responseHeader
}
func (cc *connectUnaryClientConn) ResponseTrailer() http.Header {
cc.duplexCall.BlockUntilResponseReady()
return cc.responseTrailer
}
func (cc *connectUnaryClientConn) CloseResponse() error {
return cc.duplexCall.CloseRead()
}
func (cc *connectUnaryClientConn) validateResponse(response *http.Response) *Error {
for k, v := range response.Header {
if !strings.HasPrefix(k, connectUnaryTrailerPrefix) {
cc.responseHeader[k] = v
continue
}
cc.responseTrailer[strings.TrimPrefix(k, connectUnaryTrailerPrefix)] = v
}
compression := getHeaderCanonical(response.Header, connectUnaryHeaderCompression)
if compression != "" &&
compression != compressionIdentity &&
!cc.compressionPools.Contains(compression) {
return errorf(
CodeInternal,
"unknown encoding %q: accepted encodings are %v",
compression,
cc.compressionPools.CommaSeparatedNames(),
)
}
if response.StatusCode != http.StatusOK {
unmarshaler := connectUnaryUnmarshaler{
reader: response.Body,
compressionPool: cc.compressionPools.Get(compression),
bufferPool: cc.bufferPool,
}
var wireErr connectWireError
if err := unmarshaler.UnmarshalFunc(&wireErr, json.Unmarshal); err != nil {
return NewError(
connectHTTPToCode(response.StatusCode),
errors.New(response.Status),
)
}
serverErr := wireErr.asError()
if serverErr == nil {
return nil
}
serverErr.meta = cc.responseHeader.Clone()
mergeHeaders(serverErr.meta, cc.responseTrailer)
return serverErr
}
cc.unmarshaler.compressionPool = cc.compressionPools.Get(compression)
return nil
}
type connectStreamingClientConn struct {
spec Spec
peer Peer
duplexCall *duplexHTTPCall
compressionPools readOnlyCompressionPools
bufferPool *bufferPool
codec Codec
marshaler connectStreamingMarshaler
unmarshaler connectStreamingUnmarshaler
responseHeader http.Header
responseTrailer http.Header
}
func (cc *connectStreamingClientConn) Spec() Spec {
return cc.spec
}
func (cc *connectStreamingClientConn) Peer() Peer {
return cc.peer
}
func (cc *connectStreamingClientConn) Send(msg any) error {
if err := cc.marshaler.Marshal(msg); err != nil {
return err
}
return nil // must be a literal nil: nil *Error is a non-nil error
}
func (cc *connectStreamingClientConn) RequestHeader() http.Header {
return cc.duplexCall.Header()
}
func (cc *connectStreamingClientConn) CloseRequest() error {
return cc.duplexCall.CloseWrite()
}
func (cc *connectStreamingClientConn) Receive(msg any) error {
cc.duplexCall.BlockUntilResponseReady()
err := cc.unmarshaler.Unmarshal(msg)
if err == nil {
return nil
}
// See if the server sent an explicit error in the end-of-stream message.
mergeHeaders(cc.responseTrailer, cc.unmarshaler.Trailer())
if serverErr := cc.unmarshaler.EndStreamError(); serverErr != nil {
// This is expected from a protocol perspective, but receiving an
// end-of-stream message means that we're _not_ getting a regular message.
// For users to realize that the stream has ended, Receive must return an
// error.
serverErr.meta = cc.responseHeader.Clone()
mergeHeaders(serverErr.meta, cc.responseTrailer)
cc.duplexCall.SetError(serverErr)
return serverErr
}
// There's no error in the trailers, so this was probably an error
// converting the bytes to a message, an error reading from the network, or
// just an EOF. We're going to return it to the user, but we also want to
// setResponseError so Send errors out.
cc.duplexCall.SetError(err)
return err
}
func (cc *connectStreamingClientConn) ResponseHeader() http.Header {
cc.duplexCall.BlockUntilResponseReady()
return cc.responseHeader
}
func (cc *connectStreamingClientConn) ResponseTrailer() http.Header {
cc.duplexCall.BlockUntilResponseReady()
return cc.responseTrailer
}
func (cc *connectStreamingClientConn) CloseResponse() error {
return cc.duplexCall.CloseRead()
}
func (cc *connectStreamingClientConn) validateResponse(response *http.Response) *Error {
if response.StatusCode != http.StatusOK {
return errorf(connectHTTPToCode(response.StatusCode), "HTTP status %v", response.Status)
}
compression := getHeaderCanonical(response.Header, connectStreamingHeaderCompression)
if compression != "" &&
compression != compressionIdentity &&
!cc.compressionPools.Contains(compression) {
return errorf(
CodeInternal,
"unknown encoding %q: accepted encodings are %v",
compression,
cc.compressionPools.CommaSeparatedNames(),
)
}
cc.unmarshaler.compressionPool = cc.compressionPools.Get(compression)
mergeHeaders(cc.responseHeader, response.Header)
return nil
}
type connectUnaryHandlerConn struct {
spec Spec
peer Peer
request *http.Request
responseWriter http.ResponseWriter
marshaler connectUnaryMarshaler
unmarshaler connectUnaryUnmarshaler
responseTrailer http.Header
wroteBody bool
}
func (hc *connectUnaryHandlerConn) Spec() Spec {
return hc.spec
}
func (hc *connectUnaryHandlerConn) Peer() Peer {
return hc.peer
}
func (hc *connectUnaryHandlerConn) Receive(msg any) error {
if err := hc.unmarshaler.Unmarshal(msg); err != nil {
return err
}
return nil // must be a literal nil: nil *Error is a non-nil error
}
func (hc *connectUnaryHandlerConn) RequestHeader() http.Header {
return hc.request.Header
}
func (hc *connectUnaryHandlerConn) Send(msg any) error {
hc.wroteBody = true
hc.writeResponseHeader(nil /* error */)
if err := hc.marshaler.Marshal(msg); err != nil {
return err
}
return nil // must be a literal nil: nil *Error is a non-nil error
}
func (hc *connectUnaryHandlerConn) ResponseHeader() http.Header {
return hc.responseWriter.Header()
}
func (hc *connectUnaryHandlerConn) ResponseTrailer() http.Header {
return hc.responseTrailer
}
func (hc *connectUnaryHandlerConn) Close(err error) error {
if !hc.wroteBody {
hc.writeResponseHeader(err)
}
if err == nil {
return hc.request.Body.Close()
}
// In unary Connect, errors always use application/json.
setHeaderCanonical(hc.responseWriter.Header(), headerContentType, connectUnaryContentTypeJSON)
hc.responseWriter.WriteHeader(connectCodeToHTTP(CodeOf(err)))
data, marshalErr := json.Marshal(newConnectWireError(err))
if marshalErr != nil {
_ = hc.request.Body.Close()
return errorf(CodeInternal, "marshal error: %w", err)
}
if _, writeErr := hc.responseWriter.Write(data); writeErr != nil {
_ = hc.request.Body.Close()
return writeErr
}
return hc.request.Body.Close()
}
func (hc *connectUnaryHandlerConn) writeResponseHeader(err error) {
header := hc.responseWriter.Header()
if hc.request.Method == http.MethodGet {
// The response content varies depending on the compression that the client
// requested (if any). GETs are potentially cacheable, so we should ensure
// that the Vary header includes at least Accept-Encoding (and not overwrite any values already set).
header[headerVary] = append(header[headerVary], connectUnaryHeaderAcceptCompression)
}
if err != nil {
if connectErr, ok := asError(err); ok {
mergeHeaders(header, connectErr.meta)
}
}
for k, v := range hc.responseTrailer {
header[connectUnaryTrailerPrefix+k] = v
}
}
type connectStreamingHandlerConn struct {
spec Spec
peer Peer
request *http.Request
responseWriter http.ResponseWriter
marshaler connectStreamingMarshaler
unmarshaler connectStreamingUnmarshaler
responseTrailer http.Header
}
func (hc *connectStreamingHandlerConn) Spec() Spec {
return hc.spec
}
func (hc *connectStreamingHandlerConn) Peer() Peer {
return hc.peer
}
func (hc *connectStreamingHandlerConn) Receive(msg any) error {
if err := hc.unmarshaler.Unmarshal(msg); err != nil {
// Clients may not send end-of-stream metadata, so we don't need to handle
// errSpecialEnvelope.
return err
}
return nil // must be a literal nil: nil *Error is a non-nil error
}
func (hc *connectStreamingHandlerConn) RequestHeader() http.Header {
return hc.request.Header
}
func (hc *connectStreamingHandlerConn) Send(msg any) error {
defer flushResponseWriter(hc.responseWriter)
if err := hc.marshaler.Marshal(msg); err != nil {
return err
}
return nil // must be a literal nil: nil *Error is a non-nil error
}
func (hc *connectStreamingHandlerConn) ResponseHeader() http.Header {
return hc.responseWriter.Header()
}
func (hc *connectStreamingHandlerConn) ResponseTrailer() http.Header {
return hc.responseTrailer
}
func (hc *connectStreamingHandlerConn) Close(err error) error {
defer flushResponseWriter(hc.responseWriter)
if err := hc.marshaler.MarshalEndStream(err, hc.responseTrailer); err != nil {
_ = hc.request.Body.Close()
return err
}
// We don't want to copy unread portions of the body to /dev/null here: if
// the client hasn't closed the request body, we'll block until the server
// timeout kicks in. This could happen because the client is malicious, but
// a well-intentioned client may just not expect the server to be returning
// an error for a streaming RPC. Better to accept that we can't always reuse
// TCP connections.
if err := hc.request.Body.Close(); err != nil {
if connectErr, ok := asError(err); ok {
return connectErr
}
return NewError(CodeUnknown, err)
}
return nil // must be a literal nil: nil *Error is a non-nil error
}
type connectStreamingMarshaler struct {
envelopeWriter
}
func (m *connectStreamingMarshaler) MarshalEndStream(err error, trailer http.Header) *Error {
end := &connectEndStreamMessage{Trailer: trailer}
if err != nil {
end.Error = newConnectWireError(err)
if connectErr, ok := asError(err); ok {
mergeHeaders(end.Trailer, connectErr.meta)
}
}
data, marshalErr := json.Marshal(end)
if marshalErr != nil {
return errorf(CodeInternal, "marshal end stream: %w", marshalErr)
}
raw := bytes.NewBuffer(data)
defer m.envelopeWriter.bufferPool.Put(raw)
return m.Write(&envelope{
Data: raw,
Flags: connectFlagEnvelopeEndStream,
})
}
type connectStreamingUnmarshaler struct {
envelopeReader
endStreamErr *Error
trailer http.Header
}
func (u *connectStreamingUnmarshaler) Unmarshal(message any) *Error {
err := u.envelopeReader.Unmarshal(message)
if err == nil {
return nil
}
if !errors.Is(err, errSpecialEnvelope) {
return err
}
env := u.envelopeReader.last
if !env.IsSet(connectFlagEnvelopeEndStream) {
return errorf(CodeInternal, "protocol error: invalid envelope flags %d", env.Flags)
}
var end connectEndStreamMessage
if err := json.Unmarshal(env.Data.Bytes(), &end); err != nil {
return errorf(CodeInternal, "unmarshal end stream message: %w", err)
}
u.trailer = end.Trailer
u.endStreamErr = end.Error.asError()
return errSpecialEnvelope
}
func (u *connectStreamingUnmarshaler) Trailer() http.Header {
return u.trailer
}
func (u *connectStreamingUnmarshaler) EndStreamError() *Error {
return u.endStreamErr
}
type connectUnaryMarshaler struct {
writer io.Writer
codec Codec
compressMinBytes int
compressionName string
compressionPool *compressionPool
bufferPool *bufferPool
header http.Header
sendMaxBytes int
}
func (m *connectUnaryMarshaler) Marshal(message any) *Error {
if message == nil {
return m.write(nil)
}
data, err := m.codec.Marshal(message)
if err != nil {
return errorf(CodeInternal, "marshal message: %w", err)
}
// Can't avoid allocating the slice, but we can reuse it.
uncompressed := bytes.NewBuffer(data)
defer m.bufferPool.Put(uncompressed)
if len(data) < m.compressMinBytes || m.compressionPool == nil {
if m.sendMaxBytes > 0 && len(data) > m.sendMaxBytes {
return NewError(CodeResourceExhausted, fmt.Errorf("message size %d exceeds sendMaxBytes %d", len(data), m.sendMaxBytes))
}
return m.write(data)
}
compressed := m.bufferPool.Get()
defer m.bufferPool.Put(compressed)
if err := m.compressionPool.Compress(compressed, uncompressed); err != nil {
return err
}
if m.sendMaxBytes > 0 && compressed.Len() > m.sendMaxBytes {
return NewError(CodeResourceExhausted, fmt.Errorf("compressed message size %d exceeds sendMaxBytes %d", compressed.Len(), m.sendMaxBytes))
}
setHeaderCanonical(m.header, connectUnaryHeaderCompression, m.compressionName)
return m.write(compressed.Bytes())
}
func (m *connectUnaryMarshaler) write(data []byte) *Error {
if _, err := m.writer.Write(data); err != nil {
if connectErr, ok := asError(err); ok {
return connectErr
}
return errorf(CodeUnknown, "write message: %w", err)
}
return nil
}
type connectUnaryRequestMarshaler struct {
connectUnaryMarshaler
enableGet bool
getURLMaxBytes int
getUseFallback bool
stableCodec stableCodec
duplexCall *duplexHTTPCall
}
func (m *connectUnaryRequestMarshaler) Marshal(message any) *Error {
if m.enableGet {
if m.stableCodec == nil && !m.getUseFallback {
return errorf(CodeInternal, "codec %s doesn't support stable marshal; cam't use get", m.codec.Name())
}
if m.stableCodec != nil {
return m.marshalWithGet(message)
}
}
return m.connectUnaryMarshaler.Marshal(message)
}
func (m *connectUnaryRequestMarshaler) marshalWithGet(message any) *Error {
// TODO(jchadwick-buf): This function is mostly a superset of
// connectUnaryMarshaler.Marshal. This should be reconciled at some point.
var data []byte
var err error
if message != nil {
data, err = m.stableCodec.MarshalStable(message)
if err != nil {
return errorf(CodeInternal, "marshal message stable: %w", err)
}
}
isTooBig := m.sendMaxBytes > 0 && len(data) > m.sendMaxBytes
if isTooBig && m.compressionPool == nil {
return NewError(CodeResourceExhausted, fmt.Errorf(
"message size %d exceeds sendMaxBytes %d: enabling request compression may help",
len(data),
m.sendMaxBytes,
))
}
if !isTooBig {
url := m.buildGetURL(data, false /* compressed */)
if m.getURLMaxBytes <= 0 || len(url.String()) < m.getURLMaxBytes {
return m.writeWithGet(url)
}
if m.compressionPool == nil {
if m.getUseFallback {
return m.write(data)
}
return NewError(CodeResourceExhausted, fmt.Errorf(
"url size %d exceeds getURLMaxBytes %d: enabling request compression may help",
len(url.String()),
m.getURLMaxBytes,
))
}
}
// Compress message to try to make it fit in the URL.
uncompressed := bytes.NewBuffer(data)
defer m.bufferPool.Put(uncompressed)
compressed := m.bufferPool.Get()
defer m.bufferPool.Put(compressed)
if err := m.compressionPool.Compress(compressed, uncompressed); err != nil {
return err
}
if m.sendMaxBytes > 0 && compressed.Len() > m.sendMaxBytes {
return NewError(CodeResourceExhausted, fmt.Errorf("compressed message size %d exceeds sendMaxBytes %d", compressed.Len(), m.sendMaxBytes))
}
url := m.buildGetURL(compressed.Bytes(), true /* compressed */)
if m.getURLMaxBytes <= 0 || len(url.String()) < m.getURLMaxBytes {
return m.writeWithGet(url)
}
if m.getUseFallback {
setHeaderCanonical(m.header, connectUnaryHeaderCompression, m.compressionName)
return m.write(compressed.Bytes())
}
return NewError(CodeResourceExhausted, fmt.Errorf("compressed url size %d exceeds getURLMaxBytes %d", len(url.String()), m.getURLMaxBytes))
}
func (m *connectUnaryRequestMarshaler) buildGetURL(data []byte, compressed bool) *url.URL {
url := *m.duplexCall.URL()
query := url.Query()
query.Set(connectUnaryConnectQueryParameter, connectUnaryConnectQueryValue)
query.Set(connectUnaryEncodingQueryParameter, m.codec.Name())
if m.stableCodec.IsBinary() || compressed {
query.Set(connectUnaryMessageQueryParameter, encodeBinaryQueryValue(data))
query.Set(connectUnaryBase64QueryParameter, "1")
} else {
query.Set(connectUnaryMessageQueryParameter, string(data))
}
if compressed {
query.Set(connectUnaryCompressionQueryParameter, m.compressionName)
}
url.RawQuery = query.Encode()