-
Notifications
You must be signed in to change notification settings - Fork 14
/
transcoder.go
2201 lines (2033 loc) · 63.8 KB
/
transcoder.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/url"
"strconv"
"strings"
"sync"
"time"
"connectrpc.com/connect"
"google.golang.org/genproto/googleapis/api/annotations"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/dynamicpb"
)
var (
errFinalDataAlreadyWritten = fmt.Errorf("final RPC response data already written: %w", context.Canceled)
)
// Transcoder is a Vanguard handler which acts like a router and a middleware. It transforms
// all supported input protocols (Connect, gRPC, gRPC-Web, REST) into a protocol that the
// service handlers support. It can do simple routing based on RPC method name, for simple
// protocols like Connect, gRPC, and gRPC-Web; but it can also route based on REST-ful URI
// paths configured with HTTP transcoding annotations.
//
// See the package-level examples for sample usage.
type Transcoder struct {
bufferPool bufferPool
codecs codecMap
compressors compressionMap
methods map[string]*methodConfig
restRoutes routeTrie
unknownHandler http.Handler
}
// ServeHTTP implements http.Handler, dispatching requests for configured
// services and transcoding protocols and message encoding as needed.
func (t *Transcoder) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
op := t.newOperation(writer, request)
err := op.validate(t)
if t.unknownHandler != nil && errors.Is(err, errNotFound) {
request.Header = op.originalHeaders // restore headers, just in case initialization removed keys
t.unknownHandler.ServeHTTP(writer, request)
return
}
if err != nil {
op.reportError(err)
return
}
if op.client.protocol.protocol() == op.server.protocol.protocol() &&
op.client.codec.Name() == op.server.codec.Name() &&
op.client.reqCompression.Name() == op.server.reqCompression.Name() {
// No transformation needed. But we do need to restore the original headers first
// since extracting request metadata may have removed keys.
request.Header = op.originalHeaders
op.methodConf.handler.ServeHTTP(writer, request)
return
}
op.handle()
}
func (t *Transcoder) registerService(svc *Service, svcOpts serviceOptions) error {
if len(svcOpts.protocols) == 0 {
return fmt.Errorf("service %s was configured with no target protocols", svc.schema.FullName())
}
for protocol := range svcOpts.protocols {
_, isKnown := protocolToString[protocol]
if !isKnown {
return fmt.Errorf("protocol %d is not a valid value", protocol)
}
}
if len(svcOpts.codecNames) == 0 {
return fmt.Errorf("service %s was configured with no target codecs", svc.schema.FullName())
}
for codecName := range svcOpts.codecNames {
if _, known := t.codecs[codecName]; !known {
return fmt.Errorf("codec %s is not known; use WithCodec to configure known codecs", codecName)
}
}
// empty svcOpts.compressorNames is okay
for compressorName := range svcOpts.compressorNames {
if _, known := t.compressors[compressorName]; !known {
return fmt.Errorf("compression algorithm %s is not known; use WithCompression to configure known algorithms", compressorName)
}
}
if svcOpts.maxMsgBufferBytes <= 0 {
return fmt.Errorf("service %s is configured with an invalid max message buffer size: %d bytes", svc.schema.FullName(), svcOpts.maxMsgBufferBytes)
}
if svcOpts.maxGetURLBytes <= 0 {
return fmt.Errorf("service %s is configured with an invalid max GET URL length: %d bytes", svc.schema.FullName(), svcOpts.maxGetURLBytes)
}
if svcOpts.resolver == nil {
svcOpts.resolver = resolverForService(svc.schema)
}
methods := svc.schema.Methods()
for i, length := 0, methods.Len(); i < length; i++ {
methodDesc := methods.Get(i)
if err := t.registerMethod(svc.handler, methodDesc, &svcOpts); err != nil {
return fmt.Errorf("failed to configure method %s: %w", methodDesc.FullName(), err)
}
}
return nil
}
func (t *Transcoder) registerRules(rules []*annotations.HttpRule) error {
if len(rules) == 0 {
return nil
}
methodRules := make(map[*methodConfig][]*annotations.HttpRule)
for _, rule := range rules {
var applied bool
selector := rule.GetSelector()
if selector == "" {
return errors.New("rule missing selector")
}
if i := strings.Index(selector, "*"); i >= 0 {
if i != len(selector)-1 {
return fmt.Errorf("wildcard selector %q must be at the end", rule.GetSelector())
}
selector = selector[:len(selector)-1]
if len(selector) > 0 && !strings.HasSuffix(selector, ".") {
return fmt.Errorf("wildcard selector %q must be whole component", rule.GetSelector())
}
}
for _, methodConf := range t.methods {
methodName := string(methodConf.descriptor.FullName())
if !strings.HasPrefix(methodName, selector) {
continue
}
methodRules[methodConf] = append(methodRules[methodConf], rule)
applied = true
}
if !applied {
return fmt.Errorf("rule %q does not match any methods", rule.GetSelector())
}
}
for methodConf, rules := range methodRules {
for _, rule := range rules {
if err := t.addRule(rule, methodConf); err != nil {
// TODO: use the multi-error type errors.Join()
return err
}
}
}
return nil
}
func (t *Transcoder) registerMethod(handler http.Handler, methodDesc protoreflect.MethodDescriptor, opts *serviceOptions) error {
methodPath := methodPath(methodDesc)
if _, ok := t.methods[methodPath]; ok {
return fmt.Errorf("duplicate registration: method %s has already been configured", methodDesc.FullName())
}
requestType, err := opts.resolver.FindMessageByName(methodDesc.Input().FullName())
if errors.Is(err, protoregistry.NotFound) {
requestType = dynamicpb.NewMessageType(methodDesc.Input())
} else if err != nil {
return fmt.Errorf("request type %s, for method %s, could not be resolved: %w",
methodDesc.Input().FullName(), methodDesc.FullName(), err)
}
responseType, err := opts.resolver.FindMessageByName(methodDesc.Output().FullName())
if errors.Is(err, protoregistry.NotFound) {
responseType = dynamicpb.NewMessageType(methodDesc.Output())
} else if err != nil {
return fmt.Errorf("response type %s, for method %s, could not be resolved: %w",
methodDesc.Output().FullName(), methodDesc.FullName(), err)
}
methodConf := &methodConfig{
serviceOptions: opts,
descriptor: methodDesc,
requestType: requestType,
responseType: responseType,
methodPath: methodPath,
handler: handler,
}
if t.methods == nil {
t.methods = make(map[string]*methodConfig, 1)
}
t.methods[methodPath] = methodConf
switch {
case methodDesc.IsStreamingClient() && methodDesc.IsStreamingServer():
methodConf.streamType = connect.StreamTypeBidi
case methodDesc.IsStreamingClient():
methodConf.streamType = connect.StreamTypeClient
case methodDesc.IsStreamingServer():
methodConf.streamType = connect.StreamTypeServer
default:
methodConf.streamType = connect.StreamTypeUnary
}
if httpRule, ok := getHTTPRuleExtension(methodDesc); ok {
if err := t.addRule(httpRule, methodConf); err != nil {
return err
}
}
return nil
}
func (t *Transcoder) addRule(httpRule *annotations.HttpRule, methodConf *methodConfig) error {
methodPath := methodConf.methodPath
firstTarget, err := t.restRoutes.addRoute(methodConf, httpRule)
if err != nil {
return fmt.Errorf("failed to add REST route for method %s: %w", methodPath, err)
}
methodConf.httpRule = firstTarget
for i, rule := range httpRule.GetAdditionalBindings() {
if len(rule.GetAdditionalBindings()) > 0 {
return fmt.Errorf("nested additional bindings are not supported (method %s)", methodPath)
}
if _, err := t.restRoutes.addRoute(methodConf, rule); err != nil {
return fmt.Errorf("failed to add REST route (add'l binding #%d) for method %s: %w", i+1, methodPath, err)
}
}
return nil
}
func (t *Transcoder) newOperation(writer http.ResponseWriter, request *http.Request) *operation {
ctx, cancel := context.WithCancel(request.Context())
request = request.WithContext(ctx)
op := &operation{
writer: writer,
request: request,
cancel: cancel,
bufferPool: &t.bufferPool,
compressors: t.compressors,
}
op.requestLine.fromRequest(request)
return op
}
type clientProtocolDetails struct {
protocol clientProtocolHandler
codec Codec
reqCompression *compressionPool
respCompression *compressionPool
}
type serverProtocolDetails struct {
protocol serverProtocolHandler
codec Codec
reqCompression *compressionPool
respCompression *compressionPool
}
func classifyRequest(req *http.Request) (clientProtocolHandler, url.Values) {
contentTypes := req.Header["Content-Type"]
if len(contentTypes) == 0 { //nolint:nestif
// Empty bodies should still have content types. So this should only
// happen for requests with NO body at all. That's only allowed for
// REST calls and Connect GET calls.
connectVersion := req.Header["Connect-Protocol-Version"]
// If this header is present, the intent is clear. But Connect GET
// requests should actually encode this via query string (see below).
if len(connectVersion) == 1 && connectVersion[0] == "1" {
if req.Method == http.MethodGet {
return connectUnaryGetClientProtocol{}, nil
}
return nil, nil
}
values := req.URL.Query()
if values.Get("connect") == "v1" {
if req.Method != http.MethodGet {
return nil, nil
}
return connectUnaryGetClientProtocol{}, values
}
return restClientProtocol{}, values
}
if len(contentTypes) > 1 {
return nil, nil // Ick. Don't allow this.
}
contentType := contentTypes[0]
var values url.Values
switch {
case strings.HasPrefix(contentType, "application/connect+"):
return connectStreamClientProtocol{}, nil
case contentType == "application/grpc" || strings.HasPrefix(contentType, "application/grpc+"):
return grpcClientProtocol{}, nil
case contentType == "application/grpc-web" || strings.HasPrefix(contentType, "application/grpc-web+"):
return grpcWebClientProtocol{}, nil
case strings.HasPrefix(contentType, "application/"):
connectVersion := req.Header["Connect-Protocol-Version"]
if len(connectVersion) == 1 && connectVersion[0] == "1" {
if req.Method == http.MethodGet {
return connectUnaryGetClientProtocol{}, nil
}
return connectUnaryPostClientProtocol{}, nil
}
values = req.URL.Query()
if values.Get("connect") == "v1" {
if req.Method != http.MethodGet {
return nil, nil
}
return connectUnaryGetClientProtocol{}, values
}
// REST usually uses application/json, but use of google.api.HttpBody means it could
// also use *any* content-type.
fallthrough
default:
return restClientProtocol{}, values
}
}
// operation represents a single HTTP operation, which maps to an incoming HTTP request.
// It tracks properties needed to implement protocol transformation.
type operation struct {
writer http.ResponseWriter
request *http.Request
cancel context.CancelFunc
bufferPool *bufferPool
compressors compressionMap
queryVars url.Values
originalHeaders http.Header
reqContentType string // original content-type in incoming request headers
rspContentType string // original content-type in outgoing response headers
contentLen int64 // original content-length in incoming request headers or -1
requestLine requestLine // properties of the original incoming request line
reqMeta requestMeta
deadline time.Time
methodConf *methodConfig
client clientProtocolDetails
server serverProtocolDetails
// only used when clientProtocolDetails.protocol == ProtocolREST
restTarget *routeTarget
restVars []routeTargetVarMatch
isValid bool
// these fields memoize the results of type assertions and some method calls
clientEnveloper envelopedProtocolHandler
clientPreparer clientBodyPreparer
clientReqNeedsPrep bool
clientRespNeedsPrep bool
serverEnveloper serverEnvelopedProtocolHandler
serverPreparer serverBodyPreparer
serverReqNeedsPrep bool
serverRespNeedsPrep bool
}
func (o *operation) validate(transcoder *Transcoder) error {
// Identify the protocol.
clientProtoHandler, queryVars := classifyRequest(o.request)
if clientProtoHandler == nil {
return newHTTPError(http.StatusUnsupportedMediaType, "could not classify protocol")
}
o.client.protocol = clientProtoHandler
if queryVars != nil {
// memoize this, so we don't have to parse query string again later
o.queryVars = queryVars
}
o.originalHeaders = o.request.Header.Clone()
o.reqContentType = o.originalHeaders.Get("Content-Type")
o.contentLen = o.request.ContentLength
o.request.ContentLength = -1 // transforming it will likely change it
// Identify the method being invoked.
err := o.resolveMethod(transcoder)
if err != nil {
return err
}
if !o.client.protocol.acceptsStreamType(o, o.methodConf.streamType) {
return newHTTPError(http.StatusUnsupportedMediaType, "stream type %s not supported with %s protocol", o.methodConf.streamType, o.client.protocol)
}
if o.methodConf.streamType == connect.StreamTypeBidi && o.request.ProtoMajor < 2 {
return newHTTPError(http.StatusHTTPVersionNotSupported, "bidi streams require HTTP/2")
}
if clientProtoHandler.protocol() == ProtocolGRPC && o.request.ProtoMajor != 2 {
return newHTTPError(http.StatusHTTPVersionNotSupported, "gRPC requires HTTP/2")
}
// Identify the request encoding and compression.
reqMeta, err := clientProtoHandler.extractProtocolRequestHeaders(o, o.request.Header)
if err != nil {
return newHTTPError(http.StatusBadRequest, "%w", err)
}
// Remove other headers that might mess up the next leg
if enc := o.request.Header.Get("Content-Encoding"); enc != "" && enc != CompressionIdentity {
// If the protocol didn't remove the "Content-Encoding" header in above step,
// that's because it models encoding in a different way. In that case, encoding
// of the whole response with this header is not valid.
return newHTTPError(http.StatusUnsupportedMediaType, "content-encoding %q not allowed for this protocol", enc)
}
o.request.Header.Del("Content-Encoding")
o.request.Header.Del("Accept-Encoding")
o.request.Header.Del("Content-Length")
o.reqMeta = reqMeta
if reqMeta.hasTimeout {
o.deadline = time.Now().Add(reqMeta.timeout)
}
if reqMeta.compression == CompressionIdentity {
reqMeta.compression = "" // normalize to empty string
}
if reqMeta.compression != "" {
var ok bool
o.client.reqCompression, ok = o.compressors[reqMeta.compression]
if !ok {
return newHTTPError(http.StatusUnsupportedMediaType, "%q compression not supported", reqMeta.compression)
}
}
o.client.codec = transcoder.codecs.get(reqMeta.codec, o.methodConf.resolver)
if o.client.codec == nil {
return newHTTPError(http.StatusUnsupportedMediaType, "%q sub-format not supported", reqMeta.codec)
}
// Now we can determine the destination protocol details
if _, supportsProtocol := o.methodConf.protocols[clientProtoHandler.protocol()]; supportsProtocol {
o.server.protocol = clientProtoHandler.protocol().serverHandler(o)
} else {
for _, protocol := range allProtocols {
if _, supportsProtocol := o.methodConf.protocols[protocol]; supportsProtocol {
o.server.protocol = protocol.serverHandler(o)
break
}
}
}
if o.server.protocol.protocol() == ProtocolREST && o.restTarget == nil {
// This method cannot be implemented this way. So serve a 404 for this method's URI path.
return errNotFound
}
// Now that we've ruled out the use of bidi streaming above, it's safe to simulate HTTP/2
// for the benefit of gRPC handlers, which require HTTP/2.
if o.server.protocol.protocol() == ProtocolGRPC {
o.request.Proto, o.request.ProtoMajor, o.request.ProtoMinor = "HTTP/2", 2, 0
}
if o.server.protocol.protocol() == ProtocolREST {
// REST always defaults to JSON.
// This is fine to set even if a custom content-type is used via
// the use of google.api.HttpBody. The actual content-type and body
// data will be written via serverBodyPreparer implementation.
o.server.codec = transcoder.codecs.get(CodecJSON, o.methodConf.resolver)
} else if _, supportsCodec := o.methodConf.codecNames[reqMeta.codec]; supportsCodec {
o.server.codec = o.client.codec
} else {
o.server.codec = transcoder.codecs.get(o.methodConf.preferredCodec, o.methodConf.resolver)
}
if reqMeta.compression != "" {
if _, supportsCompression := o.methodConf.compressorNames[reqMeta.compression]; supportsCompression {
o.server.reqCompression = o.client.reqCompression
}
// If the server doesn't support the compression scheme, we'll just
// decompress and not recompress.
}
o.isValid = true // Successfully validated!
return nil
}
func (o *operation) queryValues() url.Values {
if o.queryVars == nil && o.request.URL.RawQuery != "" {
o.queryVars = o.request.URL.Query()
}
return o.queryVars
}
func (o *operation) handle() {
o.clientEnveloper, _ = o.client.protocol.(envelopedProtocolHandler)
o.clientPreparer, _ = o.client.protocol.(clientBodyPreparer)
if o.clientPreparer != nil {
o.clientReqNeedsPrep = o.clientPreparer.requestNeedsPrep(o)
}
o.serverEnveloper, _ = o.server.protocol.(serverEnvelopedProtocolHandler)
o.serverPreparer, _ = o.server.protocol.(serverBodyPreparer)
if o.serverPreparer != nil {
o.serverReqNeedsPrep = o.serverPreparer.requestNeedsPrep(o)
}
serverRequestBuilder, _ := o.server.protocol.(requestLineBuilder)
var requireMessageForRequestLine bool
if serverRequestBuilder != nil {
requireMessageForRequestLine = serverRequestBuilder.requiresMessageToProvideRequestLine(o)
}
sameRequestCompression := o.client.reqCompression.Name() == o.server.reqCompression.Name()
sameCodec := o.client.codec.Name() == o.server.codec.Name()
// even if body encoding uses same content type, we can't treat them as the same
// (which means re-using encoded data) if either side needs to prep the data first
sameRequestCodec := sameCodec && !o.clientReqNeedsPrep && !o.serverReqNeedsPrep
mustDecodeRequest := !sameRequestCodec || requireMessageForRequestLine
reqMsg := message{
sameCompression: sameRequestCompression,
sameCodec: sameRequestCodec,
}
if mustDecodeRequest {
// Need the message type to decode
reqMsg.msg = o.methodConf.requestType.New().Interface()
}
if requireMessageForRequestLine {
// Go ahead and process first request message
switch err := o.readRequestMessage(nil, o.request.Body, &reqMsg); {
case errors.Is(err, io.EOF):
// okay for the first message: means empty message data
reqMsg.markReady()
case err != nil:
o.reportError(err)
return
}
if err := reqMsg.advanceToStage(o, stageDecoded); err != nil {
o.reportError(err)
return
}
}
var skipBody bool
if serverRequestBuilder != nil {
var hasBody bool
var err error
o.request.URL.Path, o.request.URL.RawQuery, o.request.Method, hasBody, err =
serverRequestBuilder.requestLine(o, reqMsg.msg)
if err != nil {
o.reportError(err)
return
}
skipBody = !hasBody
// Recompute if the server needs to prep the request, now that we've modified
// properties of op.request.
if o.serverPreparer != nil {
o.serverReqNeedsPrep = o.serverPreparer.requestNeedsPrep(o)
}
} else {
// if no request line builder, use simple request layout
o.request.URL.Path = o.methodConf.methodPath
o.request.URL.RawQuery = ""
o.request.Method = http.MethodPost
}
o.request.URL.ForceQuery = false
serverReqMeta := o.reqMeta
serverReqMeta.codec = o.server.codec.Name()
serverReqMeta.compression = o.server.reqCompression.Name()
serverReqMeta.acceptCompression = o.compressors.intersection(o.reqMeta.acceptCompression)
o.server.protocol.addProtocolRequestHeaders(serverReqMeta, o.request.Header)
// Now we can define the transformed response writer (which delays
// much of its logic until it sees the response headers).
flusher := asFlusher(o.writer)
if flusher == nil {
o.reportError(errors.New("http.ResponseWriter must implement http.Flusher"))
return
}
rw := &responseWriter{op: o, delegate: o.writer, flusher: flusher}
defer rw.close()
o.writer = rw
// And finally we can define the transformed request bodies.
switch {
case skipBody:
// drain any contents of body so downstream handler sees empty
o.drainBody(o.request.Body)
case sameRequestCompression && sameRequestCodec && !mustDecodeRequest:
// we do not need to decompress or decode; just transforming envelopes
o.request.Body = &envelopingReader{rw: rw, r: o.request.Body}
default:
tw := &transformingReader{rw: rw, msg: &reqMsg, r: o.request.Body}
o.request.Body = tw
if reqMsg.stage != stageEmpty {
if err := tw.prepareMessage(); err != nil {
tw.err = err
}
}
}
o.methodConf.handler.ServeHTTP(o.writer, o.request)
}
func (o *operation) resolveMethod(transcoder *Transcoder) error {
uriPath := o.request.URL.Path
if o.client.protocol.protocol() == ProtocolREST {
var methods routeMethods
o.restTarget, o.restVars, methods = transcoder.restRoutes.match(uriPath, o.request.Method)
if o.restTarget != nil {
o.methodConf = o.restTarget.config
return nil
}
if len(methods) == 0 {
return errNotFound
}
var sb strings.Builder
for method := range methods {
if sb.Len() > 0 {
sb.WriteByte(',')
}
sb.WriteString(method)
}
return &httpError{
code: http.StatusMethodNotAllowed,
header: http.Header{
"Allow": []string{sb.String()},
},
}
}
methodConf := transcoder.methods[uriPath]
if methodConf == nil {
return errNotFound
}
o.restTarget = methodConf.httpRule
if o.request.Method != http.MethodPost {
mayAllowGet, ok := o.client.protocol.(clientProtocolAllowsGet)
allowsGet := ok && mayAllowGet.allowsGetRequests(methodConf)
if !allowsGet {
return &httpError{
code: http.StatusMethodNotAllowed,
header: http.Header{
"Allow": []string{http.MethodPost},
},
}
}
if allowsGet && o.request.Method != http.MethodGet {
return &httpError{
code: http.StatusMethodNotAllowed,
header: http.Header{
"Allow": []string{http.MethodGet + "," + http.MethodPost},
},
}
}
}
o.methodConf = methodConf
return nil
}
// reportError handles an error that occurs while setting up the operation. It should not be used
// once the underlying server handler has been invoked. For those errors, responseWriter.reportError
// must be used instead.
func (o *operation) reportError(err error) {
defer o.cancel()
if !o.isValid {
// We don't have enough operation details to render an RPC error,
// so just send a simple HTTP error.
asHTTPError(err).Encode(o.writer)
return
}
rw, ok := o.writer.(*responseWriter)
if ok {
rw.reportError(err)
return
}
// No responseWriter created yet, so we duplicate some of its behavior to write an error.
httpErr := asHTTPError(err)
httpErr.EncodeHeaders(o.writer.Header())
connErr := asConnectError(err)
end := &responseEnd{err: connErr, httpCode: httpErr.code}
code := o.client.protocol.addProtocolResponseHeaders(responseMeta{end: end}, o.writer.Header())
o.writer.WriteHeader(code)
trailers := o.client.protocol.encodeEnd(o, end, o.writer, true)
httpMergeTrailers(o.writer.Header(), trailers)
}
func (o *operation) readRequestMessage(rw *responseWriter, reader io.Reader, msg *message) error {
msgLen := -1
compressed := o.client.reqCompression != nil
if o.clientEnveloper != nil {
var envBuf envelopeBytes
_, err := io.ReadFull(reader, envBuf[:])
if err != nil {
return err
}
msgLen, compressed, err = o.processRequestEnvelope(envBuf)
if err != nil {
if rw != nil {
rw.reportError(err)
}
return err
}
}
buffer := msg.reset(o.bufferPool, true, compressed)
var err error
if msgLen == -1 { //nolint:nestif
limit, grow, makeError, limitErr := o.determineReadLimit()
if limitErr != nil {
if rw != nil {
rw.reportError(limitErr)
}
return limitErr
}
if grow {
buffer.Grow(int(limit))
}
_, err = io.Copy(buffer, &hardLimitReader{r: reader, rw: rw, limit: limit, makeError: makeError})
if err == nil && buffer.Len() == 0 {
err = io.EOF
}
} else {
buffer.Grow(msgLen)
_, err = io.CopyN(buffer, reader, int64(msgLen))
if errors.Is(err, io.EOF) {
// EOF is a sentinel that means normal end of stream; replace it so callers know an error occurred
err = io.ErrUnexpectedEOF
}
}
if err != nil {
return err
}
msg.markReady()
return nil
}
func (o *operation) processRequestEnvelope(envBuf envelopeBytes) (msgLen int, compressed bool, err error) {
env, err := o.clientEnveloper.decodeEnvelope(envBuf)
if err != nil {
return 0, false, malformedRequestError(err)
}
if env.trailer {
return 0, false, malformedRequestError(errors.New("client stream cannot include status/trailer message"))
}
if limit := o.methodConf.maxMsgBufferBytes; env.length > limit {
return 0, false, bufferLimitError(int64(limit))
}
return int(env.length), env.compressed, nil
}
func (o *operation) determineReadLimit() (limit int64, grow bool, makeError func(int64) error, err error) {
limit = int64(o.methodConf.maxMsgBufferBytes)
if o.contentLen == -1 {
return limit, false, bufferLimitError, nil
}
if o.contentLen > limit {
// content-length header tells us that entity is too large
err := bufferLimitError(limit)
return 0, false, nil, err
}
return o.contentLen, true, contentLengthError, nil
}
func (o *operation) drainBody(body io.ReadCloser) {
if wt, ok := body.(io.WriterTo); ok {
_, _ = wt.WriteTo(io.Discard)
return
}
buf := o.bufferPool.Get()
defer o.bufferPool.Put(buf)
b := buf.Bytes()[0:buf.Cap()]
_, _ = io.CopyBuffer(io.Discard, body, b)
}
// envelopingReader will translate between envelope styles as data is read.
// It does not do any decompressing or deserializing of data.
type envelopingReader struct {
rw *responseWriter
r io.ReadCloser
mu sync.Mutex
err error
current io.Reader
mustReleaseCurrent bool
env envelopeBytes
envRemain int
}
func (r *envelopingReader) Read(data []byte) (n int, err error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.err != nil {
return 0, r.err
}
if r.current != nil {
bytesRead, err := r.current.Read(data)
isEOF := errors.Is(err, io.EOF)
if bytesRead > 0 && (err == nil || isEOF) {
return bytesRead, nil
}
if err != nil && !isEOF {
r.err = err
return bytesRead, err
}
// otherwise EOF, fall through
}
if err := r.prepareNext(); err != nil {
r.err = err
return 0, err
}
if len(data) < r.envRemain {
copy(data, r.env[envelopeLen-r.envRemain:])
r.envRemain -= len(data)
return len(data), nil
}
var offset int
if r.envRemain > 0 {
copy(data, r.env[envelopeLen-r.envRemain:])
offset = r.envRemain
r.envRemain = 0
}
if len(data) > offset {
n, err = r.current.Read(data[offset:])
}
return offset + n, err
}
func (r *envelopingReader) Close() error {
r.mu.Lock()
defer r.mu.Unlock()
if r.mustReleaseCurrent {
buf, ok := r.current.(*bytes.Buffer)
if ok {
r.rw.op.bufferPool.Put(buf)
}
r.current = nil
r.mustReleaseCurrent = false
}
r.err = errors.New("body is closed")
return r.r.Close()
}
func (r *envelopingReader) prepareNext() error {
var env envelope
switch {
case r.rw.op.clientEnveloper == nil && r.rw.op.serverEnveloper == nil:
// no envelopes to transform, just pass the body through w/ no change
r.current = r.r
r.envRemain = 0
return nil
case r.rw.op.clientEnveloper == nil:
if r.current != nil {
// If there is no enveloping, the entire body is part of a single
// message. And we've already prepared that message once. So there
// is no more.
return io.EOF
}
env.compressed = r.rw.op.client.reqCompression != nil
if r.rw.op.contentLen != -1 {
limit := int64(r.rw.op.methodConf.maxMsgBufferBytes)
if r.rw.op.contentLen > limit {
return bufferLimitError(limit)
}
r.current = &hardLimitReader{r: r.r, rw: r.rw, limit: r.rw.op.contentLen, makeError: contentLengthError}
env.length = uint32(r.rw.op.contentLen)
} else {
// Oof. We have to buffer entire request in order to measure it.
limit := int64(r.rw.op.methodConf.maxMsgBufferBytes)
buf := r.rw.op.bufferPool.Get()
_, err := io.Copy(buf, &hardLimitReader{r: r.r, rw: r.rw, limit: limit})
if err != nil {
r.rw.op.bufferPool.Put(buf)
r.err = err
return err
}
r.current = buf
r.mustReleaseCurrent = true
env.length = uint32(buf.Len())
}
default: // clientEnveloper != nil
var envBytes envelopeBytes
_, err := io.ReadFull(r.r, envBytes[:])
if err != nil {
return err
}
env, err = r.rw.op.clientEnveloper.decodeEnvelope(envBytes)
if err != nil {
err = malformedRequestError(err)
r.rw.reportError(err)
return err
}
r.current = io.LimitReader(r.r, int64(env.length))
}
if r.rw.op.serverEnveloper == nil {
r.envRemain = 0
} else {
r.envRemain = envelopeLen
r.env = r.rw.op.serverEnveloper.encodeEnvelope(env)
}
return nil
}
// transformingReader transforms the data from the original request
// into a new protocol form as the data is read. It must decompress
// and deserialize each message and then re-serialize (and optionally
// recompress) each message. Since the original incoming protocol may
// have different envelope conventions than the outgoing protocol, it
// also rewrites envelopes.
type transformingReader struct {
rw *responseWriter
msg *message
r io.ReadCloser
mu sync.Mutex
consumedFirst bool
err error
buffer *bytes.Buffer
env envelopeBytes
envRemain int
}
func (r *transformingReader) Read(data []byte) (n int, err error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.err != nil {
return 0, r.err
}
for {
if len(data) < r.envRemain {
copy(data, r.env[envelopeLen-r.envRemain:])
r.envRemain -= len(data)
return len(data), nil
}
var offset int
if r.envRemain > 0 {
copy(data, r.env[envelopeLen-r.envRemain:])
offset = r.envRemain
r.envRemain = 0
}
var err error
if len(data) > offset && r.buffer != nil {
n, err = r.buffer.Read(data[offset:])
}
if offset+n > 0 {
return offset + n, err
}
// If we get here, there was nothing in tr.buffer to read, so
// we need to prepare the next message and try again.
if err := r.rw.op.readRequestMessage(r.rw, r.r, r.msg); err != nil {
// If this is the first request message, the error is EOF, and there's a body
// preparer, we'll allow it and let the preparer produce a message from zero
// request bytes.
if !r.consumedFirst && errors.Is(err, io.EOF) && r.rw.op.clientReqNeedsPrep {
r.msg.markReady()
} else {
r.err = err
return 0, err
}
}
if err := r.prepareMessage(); err != nil {
r.err = err
r.rw.reportError(err)
return 0, io.EOF
}
}
}
func (r *transformingReader) Close() error {
r.mu.Lock()
defer r.mu.Unlock()
r.err = errors.New("body is closed")
r.msg.release(r.rw.op.bufferPool)
return r.r.Close()
}
func (r *transformingReader) prepareMessage() error {
r.consumedFirst = true
if err := r.msg.advanceToStage(r.rw.op, stageSend); err != nil {
return err
}
r.buffer = r.msg.sendBuffer()
if r.rw.op.serverEnveloper == nil {
r.envRemain = 0
return nil
}
// Need to prefix the buffer with an envelope
env := envelope{
compressed: r.msg.wasCompressed && r.rw.op.server.reqCompression != nil,
length: uint32(r.buffer.Len()),