blob: 6b04c9e873579b77e4e8db7660944dd8bb00efc0 [file] [log] [blame]
William Kurkianea869482019-04-09 15:16:11 -04001/*
2 *
3 * Copyright 2014 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19package grpc
20
21import (
William Kurkianea869482019-04-09 15:16:11 -040022 "compress/gzip"
23 "context"
24 "encoding/binary"
25 "fmt"
26 "io"
William Kurkianea869482019-04-09 15:16:11 -040027 "math"
William Kurkianea869482019-04-09 15:16:11 -040028 "strings"
29 "sync"
30 "time"
31
32 "google.golang.org/grpc/codes"
33 "google.golang.org/grpc/credentials"
34 "google.golang.org/grpc/encoding"
35 "google.golang.org/grpc/encoding/proto"
36 "google.golang.org/grpc/internal/transport"
Abhay Kumara61c5222025-11-10 07:32:50 +000037 "google.golang.org/grpc/mem"
William Kurkianea869482019-04-09 15:16:11 -040038 "google.golang.org/grpc/metadata"
39 "google.golang.org/grpc/peer"
40 "google.golang.org/grpc/stats"
41 "google.golang.org/grpc/status"
42)
43
44// Compressor defines the interface gRPC uses to compress a message.
45//
46// Deprecated: use package encoding.
47type Compressor interface {
48 // Do compresses p into w.
49 Do(w io.Writer, p []byte) error
50 // Type returns the compression algorithm the Compressor uses.
51 Type() string
52}
53
54type gzipCompressor struct {
55 pool sync.Pool
56}
57
58// NewGZIPCompressor creates a Compressor based on GZIP.
59//
60// Deprecated: use package encoding/gzip.
61func NewGZIPCompressor() Compressor {
62 c, _ := NewGZIPCompressorWithLevel(gzip.DefaultCompression)
63 return c
64}
65
66// NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead
67// of assuming DefaultCompression.
68//
69// The error returned will be nil if the level is valid.
70//
71// Deprecated: use package encoding/gzip.
72func NewGZIPCompressorWithLevel(level int) (Compressor, error) {
73 if level < gzip.DefaultCompression || level > gzip.BestCompression {
74 return nil, fmt.Errorf("grpc: invalid compression level: %d", level)
75 }
76 return &gzipCompressor{
77 pool: sync.Pool{
Abhay Kumara61c5222025-11-10 07:32:50 +000078 New: func() any {
79 w, err := gzip.NewWriterLevel(io.Discard, level)
William Kurkianea869482019-04-09 15:16:11 -040080 if err != nil {
81 panic(err)
82 }
83 return w
84 },
85 },
86 }, nil
87}
88
89func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
90 z := c.pool.Get().(*gzip.Writer)
91 defer c.pool.Put(z)
92 z.Reset(w)
93 if _, err := z.Write(p); err != nil {
94 return err
95 }
96 return z.Close()
97}
98
99func (c *gzipCompressor) Type() string {
100 return "gzip"
101}
102
103// Decompressor defines the interface gRPC uses to decompress a message.
104//
105// Deprecated: use package encoding.
106type Decompressor interface {
107 // Do reads the data from r and uncompress them.
108 Do(r io.Reader) ([]byte, error)
109 // Type returns the compression algorithm the Decompressor uses.
110 Type() string
111}
112
113type gzipDecompressor struct {
114 pool sync.Pool
115}
116
117// NewGZIPDecompressor creates a Decompressor based on GZIP.
118//
119// Deprecated: use package encoding/gzip.
120func NewGZIPDecompressor() Decompressor {
121 return &gzipDecompressor{}
122}
123
124func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
125 var z *gzip.Reader
126 switch maybeZ := d.pool.Get().(type) {
127 case nil:
128 newZ, err := gzip.NewReader(r)
129 if err != nil {
130 return nil, err
131 }
132 z = newZ
133 case *gzip.Reader:
134 z = maybeZ
135 if err := z.Reset(r); err != nil {
136 d.pool.Put(z)
137 return nil, err
138 }
139 }
140
141 defer func() {
142 z.Close()
143 d.pool.Put(z)
144 }()
Abhay Kumara61c5222025-11-10 07:32:50 +0000145 return io.ReadAll(z)
William Kurkianea869482019-04-09 15:16:11 -0400146}
147
148func (d *gzipDecompressor) Type() string {
149 return "gzip"
150}
151
152// callInfo contains all related configuration and information about an RPC.
153type callInfo struct {
Abhay Kumara61c5222025-11-10 07:32:50 +0000154 compressorName string
William Kurkianea869482019-04-09 15:16:11 -0400155 failFast bool
William Kurkianea869482019-04-09 15:16:11 -0400156 maxReceiveMessageSize *int
157 maxSendMessageSize *int
158 creds credentials.PerRPCCredentials
159 contentSubtype string
160 codec baseCodec
161 maxRetryRPCBufferSize int
Abhay Kumara61c5222025-11-10 07:32:50 +0000162 onFinish []func(err error)
163 authority string
William Kurkianea869482019-04-09 15:16:11 -0400164}
165
166func defaultCallInfo() *callInfo {
167 return &callInfo{
168 failFast: true,
169 maxRetryRPCBufferSize: 256 * 1024, // 256KB
170 }
171}
172
173// CallOption configures a Call before it starts or extracts information from
174// a Call after it completes.
175type CallOption interface {
176 // before is called before the call is sent to any server. If before
177 // returns a non-nil error, the RPC fails with that error.
178 before(*callInfo) error
179
180 // after is called after the call has completed. after cannot return an
181 // error, so any failures should be reported via output parameters.
Abhay Kumara61c5222025-11-10 07:32:50 +0000182 after(*callInfo, *csAttempt)
William Kurkianea869482019-04-09 15:16:11 -0400183}
184
185// EmptyCallOption does not alter the Call configuration.
186// It can be embedded in another structure to carry satellite data for use
187// by interceptors.
188type EmptyCallOption struct{}
189
Abhay Kumara61c5222025-11-10 07:32:50 +0000190func (EmptyCallOption) before(*callInfo) error { return nil }
191func (EmptyCallOption) after(*callInfo, *csAttempt) {}
192
193// StaticMethod returns a CallOption which specifies that a call is being made
194// to a method that is static, which means the method is known at compile time
195// and doesn't change at runtime. This can be used as a signal to stats plugins
196// that this method is safe to include as a key to a measurement.
197func StaticMethod() CallOption {
198 return StaticMethodCallOption{}
199}
200
201// StaticMethodCallOption is a CallOption that specifies that a call comes
202// from a static method.
203type StaticMethodCallOption struct {
204 EmptyCallOption
205}
William Kurkianea869482019-04-09 15:16:11 -0400206
207// Header returns a CallOptions that retrieves the header metadata
208// for a unary RPC.
209func Header(md *metadata.MD) CallOption {
210 return HeaderCallOption{HeaderAddr: md}
211}
212
213// HeaderCallOption is a CallOption for collecting response header metadata.
214// The metadata field will be populated *after* the RPC completes.
Abhay Kumara61c5222025-11-10 07:32:50 +0000215//
216// # Experimental
217//
218// Notice: This type is EXPERIMENTAL and may be changed or removed in a
219// later release.
William Kurkianea869482019-04-09 15:16:11 -0400220type HeaderCallOption struct {
221 HeaderAddr *metadata.MD
222}
223
Abhay Kumara61c5222025-11-10 07:32:50 +0000224func (o HeaderCallOption) before(*callInfo) error { return nil }
225func (o HeaderCallOption) after(_ *callInfo, attempt *csAttempt) {
226 *o.HeaderAddr, _ = attempt.transportStream.Header()
William Kurkianea869482019-04-09 15:16:11 -0400227}
228
229// Trailer returns a CallOptions that retrieves the trailer metadata
230// for a unary RPC.
231func Trailer(md *metadata.MD) CallOption {
232 return TrailerCallOption{TrailerAddr: md}
233}
234
235// TrailerCallOption is a CallOption for collecting response trailer metadata.
236// The metadata field will be populated *after* the RPC completes.
Abhay Kumara61c5222025-11-10 07:32:50 +0000237//
238// # Experimental
239//
240// Notice: This type is EXPERIMENTAL and may be changed or removed in a
241// later release.
William Kurkianea869482019-04-09 15:16:11 -0400242type TrailerCallOption struct {
243 TrailerAddr *metadata.MD
244}
245
Abhay Kumara61c5222025-11-10 07:32:50 +0000246func (o TrailerCallOption) before(*callInfo) error { return nil }
247func (o TrailerCallOption) after(_ *callInfo, attempt *csAttempt) {
248 *o.TrailerAddr = attempt.transportStream.Trailer()
William Kurkianea869482019-04-09 15:16:11 -0400249}
250
251// Peer returns a CallOption that retrieves peer information for a unary RPC.
252// The peer field will be populated *after* the RPC completes.
253func Peer(p *peer.Peer) CallOption {
254 return PeerCallOption{PeerAddr: p}
255}
256
257// PeerCallOption is a CallOption for collecting the identity of the remote
258// peer. The peer field will be populated *after* the RPC completes.
Abhay Kumara61c5222025-11-10 07:32:50 +0000259//
260// # Experimental
261//
262// Notice: This type is EXPERIMENTAL and may be changed or removed in a
263// later release.
William Kurkianea869482019-04-09 15:16:11 -0400264type PeerCallOption struct {
265 PeerAddr *peer.Peer
266}
267
Abhay Kumara61c5222025-11-10 07:32:50 +0000268func (o PeerCallOption) before(*callInfo) error { return nil }
269func (o PeerCallOption) after(_ *callInfo, attempt *csAttempt) {
270 if x, ok := peer.FromContext(attempt.transportStream.Context()); ok {
271 *o.PeerAddr = *x
William Kurkianea869482019-04-09 15:16:11 -0400272 }
273}
274
Abhay Kumara61c5222025-11-10 07:32:50 +0000275// WaitForReady configures the RPC's behavior when the client is in
276// TRANSIENT_FAILURE, which occurs when all addresses fail to connect. If
277// waitForReady is false, the RPC will fail immediately. Otherwise, the client
278// will wait until a connection becomes available or the RPC's deadline is
279// reached.
William Kurkianea869482019-04-09 15:16:11 -0400280//
Abhay Kumara61c5222025-11-10 07:32:50 +0000281// By default, RPCs do not "wait for ready".
William Kurkianea869482019-04-09 15:16:11 -0400282func WaitForReady(waitForReady bool) CallOption {
283 return FailFastCallOption{FailFast: !waitForReady}
284}
285
286// FailFast is the opposite of WaitForReady.
287//
288// Deprecated: use WaitForReady.
289func FailFast(failFast bool) CallOption {
290 return FailFastCallOption{FailFast: failFast}
291}
292
293// FailFastCallOption is a CallOption for indicating whether an RPC should fail
294// fast or not.
Abhay Kumara61c5222025-11-10 07:32:50 +0000295//
296// # Experimental
297//
298// Notice: This type is EXPERIMENTAL and may be changed or removed in a
299// later release.
William Kurkianea869482019-04-09 15:16:11 -0400300type FailFastCallOption struct {
301 FailFast bool
302}
303
304func (o FailFastCallOption) before(c *callInfo) error {
305 c.failFast = o.FailFast
306 return nil
307}
Abhay Kumara61c5222025-11-10 07:32:50 +0000308func (o FailFastCallOption) after(*callInfo, *csAttempt) {}
William Kurkianea869482019-04-09 15:16:11 -0400309
Abhay Kumara61c5222025-11-10 07:32:50 +0000310// OnFinish returns a CallOption that configures a callback to be called when
311// the call completes. The error passed to the callback is the status of the
312// RPC, and may be nil. The onFinish callback provided will only be called once
313// by gRPC. This is mainly used to be used by streaming interceptors, to be
314// notified when the RPC completes along with information about the status of
315// the RPC.
316//
317// # Experimental
318//
319// Notice: This API is EXPERIMENTAL and may be changed or removed in a
320// later release.
321func OnFinish(onFinish func(err error)) CallOption {
322 return OnFinishCallOption{
323 OnFinish: onFinish,
324 }
325}
326
327// OnFinishCallOption is CallOption that indicates a callback to be called when
328// the call completes.
329//
330// # Experimental
331//
332// Notice: This type is EXPERIMENTAL and may be changed or removed in a
333// later release.
334type OnFinishCallOption struct {
335 OnFinish func(error)
336}
337
338func (o OnFinishCallOption) before(c *callInfo) error {
339 c.onFinish = append(c.onFinish, o.OnFinish)
340 return nil
341}
342
343func (o OnFinishCallOption) after(*callInfo, *csAttempt) {}
344
345// MaxCallRecvMsgSize returns a CallOption which sets the maximum message size
346// in bytes the client can receive. If this is not set, gRPC uses the default
347// 4MB.
348func MaxCallRecvMsgSize(bytes int) CallOption {
349 return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: bytes}
William Kurkianea869482019-04-09 15:16:11 -0400350}
351
352// MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message
Abhay Kumara61c5222025-11-10 07:32:50 +0000353// size in bytes the client can receive.
354//
355// # Experimental
356//
357// Notice: This type is EXPERIMENTAL and may be changed or removed in a
358// later release.
William Kurkianea869482019-04-09 15:16:11 -0400359type MaxRecvMsgSizeCallOption struct {
360 MaxRecvMsgSize int
361}
362
363func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error {
364 c.maxReceiveMessageSize = &o.MaxRecvMsgSize
365 return nil
366}
Abhay Kumara61c5222025-11-10 07:32:50 +0000367func (o MaxRecvMsgSizeCallOption) after(*callInfo, *csAttempt) {}
William Kurkianea869482019-04-09 15:16:11 -0400368
Abhay Kumara61c5222025-11-10 07:32:50 +0000369// CallAuthority returns a CallOption that sets the HTTP/2 :authority header of
370// an RPC to the specified value. When using CallAuthority, the credentials in
371// use must implement the AuthorityValidator interface.
372//
373// # Experimental
374//
375// Notice: This API is EXPERIMENTAL and may be changed or removed in a later
376// release.
377func CallAuthority(authority string) CallOption {
378 return AuthorityOverrideCallOption{Authority: authority}
379}
380
381// AuthorityOverrideCallOption is a CallOption that indicates the HTTP/2
382// :authority header value to use for the call.
383//
384// # Experimental
385//
386// Notice: This type is EXPERIMENTAL and may be changed or removed in a later
387// release.
388type AuthorityOverrideCallOption struct {
389 Authority string
390}
391
392func (o AuthorityOverrideCallOption) before(c *callInfo) error {
393 c.authority = o.Authority
394 return nil
395}
396
397func (o AuthorityOverrideCallOption) after(*callInfo, *csAttempt) {}
398
399// MaxCallSendMsgSize returns a CallOption which sets the maximum message size
400// in bytes the client can send. If this is not set, gRPC uses the default
401// `math.MaxInt32`.
402func MaxCallSendMsgSize(bytes int) CallOption {
403 return MaxSendMsgSizeCallOption{MaxSendMsgSize: bytes}
William Kurkianea869482019-04-09 15:16:11 -0400404}
405
406// MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message
Abhay Kumara61c5222025-11-10 07:32:50 +0000407// size in bytes the client can send.
408//
409// # Experimental
410//
411// Notice: This type is EXPERIMENTAL and may be changed or removed in a
412// later release.
William Kurkianea869482019-04-09 15:16:11 -0400413type MaxSendMsgSizeCallOption struct {
414 MaxSendMsgSize int
415}
416
417func (o MaxSendMsgSizeCallOption) before(c *callInfo) error {
418 c.maxSendMessageSize = &o.MaxSendMsgSize
419 return nil
420}
Abhay Kumara61c5222025-11-10 07:32:50 +0000421func (o MaxSendMsgSizeCallOption) after(*callInfo, *csAttempt) {}
William Kurkianea869482019-04-09 15:16:11 -0400422
423// PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
424// for a call.
425func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption {
426 return PerRPCCredsCallOption{Creds: creds}
427}
428
429// PerRPCCredsCallOption is a CallOption that indicates the per-RPC
430// credentials to use for the call.
Abhay Kumara61c5222025-11-10 07:32:50 +0000431//
432// # Experimental
433//
434// Notice: This type is EXPERIMENTAL and may be changed or removed in a
435// later release.
William Kurkianea869482019-04-09 15:16:11 -0400436type PerRPCCredsCallOption struct {
437 Creds credentials.PerRPCCredentials
438}
439
440func (o PerRPCCredsCallOption) before(c *callInfo) error {
441 c.creds = o.Creds
442 return nil
443}
Abhay Kumara61c5222025-11-10 07:32:50 +0000444func (o PerRPCCredsCallOption) after(*callInfo, *csAttempt) {}
William Kurkianea869482019-04-09 15:16:11 -0400445
446// UseCompressor returns a CallOption which sets the compressor used when
447// sending the request. If WithCompressor is also set, UseCompressor has
448// higher priority.
449//
Abhay Kumara61c5222025-11-10 07:32:50 +0000450// # Experimental
451//
452// Notice: This API is EXPERIMENTAL and may be changed or removed in a
453// later release.
William Kurkianea869482019-04-09 15:16:11 -0400454func UseCompressor(name string) CallOption {
455 return CompressorCallOption{CompressorType: name}
456}
457
458// CompressorCallOption is a CallOption that indicates the compressor to use.
Abhay Kumara61c5222025-11-10 07:32:50 +0000459//
460// # Experimental
461//
462// Notice: This type is EXPERIMENTAL and may be changed or removed in a
463// later release.
William Kurkianea869482019-04-09 15:16:11 -0400464type CompressorCallOption struct {
465 CompressorType string
466}
467
468func (o CompressorCallOption) before(c *callInfo) error {
Abhay Kumara61c5222025-11-10 07:32:50 +0000469 c.compressorName = o.CompressorType
William Kurkianea869482019-04-09 15:16:11 -0400470 return nil
471}
Abhay Kumara61c5222025-11-10 07:32:50 +0000472func (o CompressorCallOption) after(*callInfo, *csAttempt) {}
William Kurkianea869482019-04-09 15:16:11 -0400473
474// CallContentSubtype returns a CallOption that will set the content-subtype
475// for a call. For example, if content-subtype is "json", the Content-Type over
476// the wire will be "application/grpc+json". The content-subtype is converted
477// to lowercase before being included in Content-Type. See Content-Type on
478// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
479// more details.
480//
481// If ForceCodec is not also used, the content-subtype will be used to look up
482// the Codec to use in the registry controlled by RegisterCodec. See the
483// documentation on RegisterCodec for details on registration. The lookup of
484// content-subtype is case-insensitive. If no such Codec is found, the call
485// will result in an error with code codes.Internal.
486//
487// If ForceCodec is also used, that Codec will be used for all request and
488// response messages, with the content-subtype set to the given contentSubtype
489// here for requests.
490func CallContentSubtype(contentSubtype string) CallOption {
491 return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)}
492}
493
494// ContentSubtypeCallOption is a CallOption that indicates the content-subtype
495// used for marshaling messages.
Abhay Kumara61c5222025-11-10 07:32:50 +0000496//
497// # Experimental
498//
499// Notice: This type is EXPERIMENTAL and may be changed or removed in a
500// later release.
William Kurkianea869482019-04-09 15:16:11 -0400501type ContentSubtypeCallOption struct {
502 ContentSubtype string
503}
504
505func (o ContentSubtypeCallOption) before(c *callInfo) error {
506 c.contentSubtype = o.ContentSubtype
507 return nil
508}
Abhay Kumara61c5222025-11-10 07:32:50 +0000509func (o ContentSubtypeCallOption) after(*callInfo, *csAttempt) {}
William Kurkianea869482019-04-09 15:16:11 -0400510
Abhay Kumara61c5222025-11-10 07:32:50 +0000511// ForceCodec returns a CallOption that will set codec to be used for all
512// request and response messages for a call. The result of calling Name() will
513// be used as the content-subtype after converting to lowercase, unless
514// CallContentSubtype is also used.
William Kurkianea869482019-04-09 15:16:11 -0400515//
516// See Content-Type on
517// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
518// more details. Also see the documentation on RegisterCodec and
519// CallContentSubtype for more details on the interaction between Codec and
520// content-subtype.
521//
522// This function is provided for advanced users; prefer to use only
523// CallContentSubtype to select a registered codec instead.
524//
Abhay Kumara61c5222025-11-10 07:32:50 +0000525// # Experimental
526//
527// Notice: This API is EXPERIMENTAL and may be changed or removed in a
528// later release.
William Kurkianea869482019-04-09 15:16:11 -0400529func ForceCodec(codec encoding.Codec) CallOption {
530 return ForceCodecCallOption{Codec: codec}
531}
532
533// ForceCodecCallOption is a CallOption that indicates the codec used for
534// marshaling messages.
535//
Abhay Kumara61c5222025-11-10 07:32:50 +0000536// # Experimental
537//
538// Notice: This type is EXPERIMENTAL and may be changed or removed in a
539// later release.
William Kurkianea869482019-04-09 15:16:11 -0400540type ForceCodecCallOption struct {
541 Codec encoding.Codec
542}
543
544func (o ForceCodecCallOption) before(c *callInfo) error {
Abhay Kumara61c5222025-11-10 07:32:50 +0000545 c.codec = newCodecV1Bridge(o.Codec)
William Kurkianea869482019-04-09 15:16:11 -0400546 return nil
547}
Abhay Kumara61c5222025-11-10 07:32:50 +0000548func (o ForceCodecCallOption) after(*callInfo, *csAttempt) {}
549
550// ForceCodecV2 returns a CallOption that will set codec to be used for all
551// request and response messages for a call. The result of calling Name() will
552// be used as the content-subtype after converting to lowercase, unless
553// CallContentSubtype is also used.
554//
555// See Content-Type on
556// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
557// more details. Also see the documentation on RegisterCodec and
558// CallContentSubtype for more details on the interaction between Codec and
559// content-subtype.
560//
561// This function is provided for advanced users; prefer to use only
562// CallContentSubtype to select a registered codec instead.
563//
564// # Experimental
565//
566// Notice: This API is EXPERIMENTAL and may be changed or removed in a
567// later release.
568func ForceCodecV2(codec encoding.CodecV2) CallOption {
569 return ForceCodecV2CallOption{CodecV2: codec}
570}
571
572// ForceCodecV2CallOption is a CallOption that indicates the codec used for
573// marshaling messages.
574//
575// # Experimental
576//
577// Notice: This type is EXPERIMENTAL and may be changed or removed in a
578// later release.
579type ForceCodecV2CallOption struct {
580 CodecV2 encoding.CodecV2
581}
582
583func (o ForceCodecV2CallOption) before(c *callInfo) error {
584 c.codec = o.CodecV2
585 return nil
586}
587
588func (o ForceCodecV2CallOption) after(*callInfo, *csAttempt) {}
William Kurkianea869482019-04-09 15:16:11 -0400589
590// CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of
591// an encoding.Codec.
592//
593// Deprecated: use ForceCodec instead.
594func CallCustomCodec(codec Codec) CallOption {
595 return CustomCodecCallOption{Codec: codec}
596}
597
598// CustomCodecCallOption is a CallOption that indicates the codec used for
599// marshaling messages.
600//
Abhay Kumara61c5222025-11-10 07:32:50 +0000601// # Experimental
602//
603// Notice: This type is EXPERIMENTAL and may be changed or removed in a
604// later release.
William Kurkianea869482019-04-09 15:16:11 -0400605type CustomCodecCallOption struct {
606 Codec Codec
607}
608
609func (o CustomCodecCallOption) before(c *callInfo) error {
Abhay Kumara61c5222025-11-10 07:32:50 +0000610 c.codec = newCodecV0Bridge(o.Codec)
William Kurkianea869482019-04-09 15:16:11 -0400611 return nil
612}
Abhay Kumara61c5222025-11-10 07:32:50 +0000613func (o CustomCodecCallOption) after(*callInfo, *csAttempt) {}
William Kurkianea869482019-04-09 15:16:11 -0400614
615// MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory
616// used for buffering this RPC's requests for retry purposes.
617//
Abhay Kumara61c5222025-11-10 07:32:50 +0000618// # Experimental
619//
620// Notice: This API is EXPERIMENTAL and may be changed or removed in a
621// later release.
William Kurkianea869482019-04-09 15:16:11 -0400622func MaxRetryRPCBufferSize(bytes int) CallOption {
623 return MaxRetryRPCBufferSizeCallOption{bytes}
624}
625
626// MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of
627// memory to be used for caching this RPC for retry purposes.
Abhay Kumara61c5222025-11-10 07:32:50 +0000628//
629// # Experimental
630//
631// Notice: This type is EXPERIMENTAL and may be changed or removed in a
632// later release.
William Kurkianea869482019-04-09 15:16:11 -0400633type MaxRetryRPCBufferSizeCallOption struct {
634 MaxRetryRPCBufferSize int
635}
636
637func (o MaxRetryRPCBufferSizeCallOption) before(c *callInfo) error {
638 c.maxRetryRPCBufferSize = o.MaxRetryRPCBufferSize
639 return nil
640}
Abhay Kumara61c5222025-11-10 07:32:50 +0000641func (o MaxRetryRPCBufferSizeCallOption) after(*callInfo, *csAttempt) {}
William Kurkianea869482019-04-09 15:16:11 -0400642
643// The format of the payload: compressed or not?
644type payloadFormat uint8
645
646const (
647 compressionNone payloadFormat = 0 // no compression
648 compressionMade payloadFormat = 1 // compressed
649)
650
Abhay Kumara61c5222025-11-10 07:32:50 +0000651func (pf payloadFormat) isCompressed() bool {
652 return pf == compressionMade
653}
654
655type streamReader interface {
656 ReadMessageHeader(header []byte) error
657 Read(n int) (mem.BufferSlice, error)
658}
659
bseeniva0b9cbcb2026-02-12 19:11:11 +0530660// noCopy may be embedded into structs which must not be copied
661// after the first use.
662//
663// See https://golang.org/issues/8005#issuecomment-190753527
664// for details.
665type noCopy struct {
666}
667
668func (*noCopy) Lock() {}
669func (*noCopy) Unlock() {}
670
William Kurkianea869482019-04-09 15:16:11 -0400671// parser reads complete gRPC messages from the underlying reader.
672type parser struct {
bseeniva0b9cbcb2026-02-12 19:11:11 +0530673 _ noCopy
William Kurkianea869482019-04-09 15:16:11 -0400674 // r is the underlying reader.
675 // See the comment on recvMsg for the permissible
676 // error types.
Abhay Kumara61c5222025-11-10 07:32:50 +0000677 r streamReader
William Kurkianea869482019-04-09 15:16:11 -0400678
679 // The header of a gRPC message. Find more detail at
680 // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
681 header [5]byte
Abhay Kumara61c5222025-11-10 07:32:50 +0000682
683 // bufferPool is the pool of shared receive buffers.
684 bufferPool mem.BufferPool
William Kurkianea869482019-04-09 15:16:11 -0400685}
686
687// recvMsg reads a complete gRPC message from the stream.
688//
689// It returns the message and its payload (compression/encoding)
690// format. The caller owns the returned msg memory.
691//
692// If there is an error, possible values are:
Abhay Kumara61c5222025-11-10 07:32:50 +0000693// - io.EOF, when no messages remain
694// - io.ErrUnexpectedEOF
695// - of type transport.ConnectionError
696// - an error from the status package
697//
William Kurkianea869482019-04-09 15:16:11 -0400698// No other error values or types must be returned, which also means
Abhay Kumara61c5222025-11-10 07:32:50 +0000699// that the underlying streamReader must not return an incompatible
William Kurkianea869482019-04-09 15:16:11 -0400700// error.
Abhay Kumara61c5222025-11-10 07:32:50 +0000701func (p *parser) recvMsg(maxReceiveMessageSize int) (payloadFormat, mem.BufferSlice, error) {
702 err := p.r.ReadMessageHeader(p.header[:])
703 if err != nil {
William Kurkianea869482019-04-09 15:16:11 -0400704 return 0, nil, err
705 }
706
Abhay Kumara61c5222025-11-10 07:32:50 +0000707 pf := payloadFormat(p.header[0])
William Kurkianea869482019-04-09 15:16:11 -0400708 length := binary.BigEndian.Uint32(p.header[1:])
709
William Kurkianea869482019-04-09 15:16:11 -0400710 if int64(length) > int64(maxInt) {
711 return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt)
712 }
713 if int(length) > maxReceiveMessageSize {
714 return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize)
715 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000716
717 data, err := p.r.Read(int(length))
718 if err != nil {
William Kurkianea869482019-04-09 15:16:11 -0400719 if err == io.EOF {
720 err = io.ErrUnexpectedEOF
721 }
722 return 0, nil, err
723 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000724 return pf, data, nil
William Kurkianea869482019-04-09 15:16:11 -0400725}
726
727// encode serializes msg and returns a buffer containing the message, or an
728// error if it is too large to be transmitted by grpc. If msg is nil, it
729// generates an empty message.
Abhay Kumara61c5222025-11-10 07:32:50 +0000730func encode(c baseCodec, msg any) (mem.BufferSlice, error) {
William Kurkianea869482019-04-09 15:16:11 -0400731 if msg == nil { // NOTE: typed nils will not be caught by this check
732 return nil, nil
733 }
734 b, err := c.Marshal(msg)
735 if err != nil {
736 return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error())
737 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000738 if bufSize := uint(b.Len()); bufSize > math.MaxUint32 {
739 b.Free()
740 return nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", bufSize)
William Kurkianea869482019-04-09 15:16:11 -0400741 }
742 return b, nil
743}
744
Abhay Kumara61c5222025-11-10 07:32:50 +0000745// compress returns the input bytes compressed by compressor or cp.
746// If both compressors are nil, or if the message has zero length, returns nil,
747// indicating no compression was done.
William Kurkianea869482019-04-09 15:16:11 -0400748//
749// TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
Abhay Kumara61c5222025-11-10 07:32:50 +0000750func compress(in mem.BufferSlice, cp Compressor, compressor encoding.Compressor, pool mem.BufferPool) (mem.BufferSlice, payloadFormat, error) {
751 if (compressor == nil && cp == nil) || in.Len() == 0 {
752 return nil, compressionNone, nil
William Kurkianea869482019-04-09 15:16:11 -0400753 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000754 var out mem.BufferSlice
755 w := mem.NewWriter(&out, pool)
William Kurkianea869482019-04-09 15:16:11 -0400756 wrapErr := func(err error) error {
Abhay Kumara61c5222025-11-10 07:32:50 +0000757 out.Free()
William Kurkianea869482019-04-09 15:16:11 -0400758 return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
759 }
William Kurkianea869482019-04-09 15:16:11 -0400760 if compressor != nil {
Abhay Kumara61c5222025-11-10 07:32:50 +0000761 z, err := compressor.Compress(w)
William Kurkianea869482019-04-09 15:16:11 -0400762 if err != nil {
Abhay Kumara61c5222025-11-10 07:32:50 +0000763 return nil, 0, wrapErr(err)
William Kurkianea869482019-04-09 15:16:11 -0400764 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000765 for _, b := range in {
766 if _, err := z.Write(b.ReadOnlyData()); err != nil {
767 return nil, 0, wrapErr(err)
768 }
William Kurkianea869482019-04-09 15:16:11 -0400769 }
770 if err := z.Close(); err != nil {
Abhay Kumara61c5222025-11-10 07:32:50 +0000771 return nil, 0, wrapErr(err)
William Kurkianea869482019-04-09 15:16:11 -0400772 }
773 } else {
Abhay Kumara61c5222025-11-10 07:32:50 +0000774 // This is obviously really inefficient since it fully materializes the data, but
775 // there is no way around this with the old Compressor API. At least it attempts
776 // to return the buffer to the provider, in the hopes it can be reused (maybe
777 // even by a subsequent call to this very function).
778 buf := in.MaterializeToBuffer(pool)
779 defer buf.Free()
780 if err := cp.Do(w, buf.ReadOnlyData()); err != nil {
781 return nil, 0, wrapErr(err)
William Kurkianea869482019-04-09 15:16:11 -0400782 }
783 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000784 return out, compressionMade, nil
William Kurkianea869482019-04-09 15:16:11 -0400785}
786
787const (
788 payloadLen = 1
789 sizeLen = 4
790 headerLen = payloadLen + sizeLen
791)
792
793// msgHeader returns a 5-byte header for the message being transmitted and the
794// payload, which is compData if non-nil or data otherwise.
Abhay Kumara61c5222025-11-10 07:32:50 +0000795func msgHeader(data, compData mem.BufferSlice, pf payloadFormat) (hdr []byte, payload mem.BufferSlice) {
William Kurkianea869482019-04-09 15:16:11 -0400796 hdr = make([]byte, headerLen)
Abhay Kumara61c5222025-11-10 07:32:50 +0000797 hdr[0] = byte(pf)
798
799 var length uint32
800 if pf.isCompressed() {
801 length = uint32(compData.Len())
802 payload = compData
William Kurkianea869482019-04-09 15:16:11 -0400803 } else {
Abhay Kumara61c5222025-11-10 07:32:50 +0000804 length = uint32(data.Len())
805 payload = data
William Kurkianea869482019-04-09 15:16:11 -0400806 }
807
808 // Write length of payload into buf
Abhay Kumara61c5222025-11-10 07:32:50 +0000809 binary.BigEndian.PutUint32(hdr[payloadLen:], length)
810 return hdr, payload
William Kurkianea869482019-04-09 15:16:11 -0400811}
812
Abhay Kumara61c5222025-11-10 07:32:50 +0000813func outPayload(client bool, msg any, dataLength, payloadLength int, t time.Time) *stats.OutPayload {
William Kurkianea869482019-04-09 15:16:11 -0400814 return &stats.OutPayload{
Abhay Kumara61c5222025-11-10 07:32:50 +0000815 Client: client,
816 Payload: msg,
817 Length: dataLength,
818 WireLength: payloadLength + headerLen,
819 CompressedLength: payloadLength,
820 SentTime: t,
William Kurkianea869482019-04-09 15:16:11 -0400821 }
822}
823
Abhay Kumara61c5222025-11-10 07:32:50 +0000824func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool, isServer bool) *status.Status {
William Kurkianea869482019-04-09 15:16:11 -0400825 switch pf {
826 case compressionNone:
827 case compressionMade:
828 if recvCompress == "" || recvCompress == encoding.Identity {
829 return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding")
830 }
831 if !haveCompressor {
Abhay Kumara61c5222025-11-10 07:32:50 +0000832 if isServer {
833 return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
834 }
835 return status.Newf(codes.Internal, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
William Kurkianea869482019-04-09 15:16:11 -0400836 }
837 default:
838 return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf)
839 }
840 return nil
841}
842
843type payloadInfo struct {
Abhay Kumara61c5222025-11-10 07:32:50 +0000844 compressedLength int // The compressed length got from wire.
845 uncompressedBytes mem.BufferSlice
William Kurkianea869482019-04-09 15:16:11 -0400846}
847
Abhay Kumara61c5222025-11-10 07:32:50 +0000848func (p *payloadInfo) free() {
849 if p != nil && p.uncompressedBytes != nil {
850 p.uncompressedBytes.Free()
851 }
852}
853
854// recvAndDecompress reads a message from the stream, decompressing it if necessary.
855//
856// Cancelling the returned cancel function releases the buffer back to the pool. So the caller should cancel as soon as
857// the buffer is no longer needed.
858// TODO: Refactor this function to reduce the number of arguments.
859// See: https://google.github.io/styleguide/go/best-practices.html#function-argument-lists
860func recvAndDecompress(p *parser, s recvCompressor, dc Decompressor, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor, isServer bool,
861) (out mem.BufferSlice, err error) {
862 pf, compressed, err := p.recvMsg(maxReceiveMessageSize)
William Kurkianea869482019-04-09 15:16:11 -0400863 if err != nil {
864 return nil, err
865 }
William Kurkianea869482019-04-09 15:16:11 -0400866
Abhay Kumara61c5222025-11-10 07:32:50 +0000867 compressedLength := compressed.Len()
868
869 if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil, isServer); st != nil {
870 compressed.Free()
William Kurkianea869482019-04-09 15:16:11 -0400871 return nil, st.Err()
872 }
873
Abhay Kumara61c5222025-11-10 07:32:50 +0000874 if pf.isCompressed() {
875 defer compressed.Free()
William Kurkianea869482019-04-09 15:16:11 -0400876 // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor,
877 // use this decompressor as the default.
Abhay Kumara61c5222025-11-10 07:32:50 +0000878 out, err = decompress(compressor, compressed, dc, maxReceiveMessageSize, p.bufferPool)
Devmalya Pauldd23a992019-11-14 07:06:31 +0000879 if err != nil {
Abhay Kumara61c5222025-11-10 07:32:50 +0000880 return nil, err
Devmalya Pauldd23a992019-11-14 07:06:31 +0000881 }
882 } else {
Abhay Kumara61c5222025-11-10 07:32:50 +0000883 out = compressed
William Kurkianea869482019-04-09 15:16:11 -0400884 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000885
886 if payInfo != nil {
887 payInfo.compressedLength = compressedLength
888 out.Ref()
889 payInfo.uncompressedBytes = out
William Kurkianea869482019-04-09 15:16:11 -0400890 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000891
892 return out, nil
William Kurkianea869482019-04-09 15:16:11 -0400893}
894
Abhay Kumara61c5222025-11-10 07:32:50 +0000895// decompress processes the given data by decompressing it using either a custom decompressor or a standard compressor.
896// If a custom decompressor is provided, it takes precedence. The function validates that the decompressed data
897// does not exceed the specified maximum size and returns an error if this limit is exceeded.
898// On success, it returns the decompressed data. Otherwise, it returns an error if decompression fails or the data exceeds the size limit.
899func decompress(compressor encoding.Compressor, d mem.BufferSlice, dc Decompressor, maxReceiveMessageSize int, pool mem.BufferPool) (mem.BufferSlice, error) {
900 if dc != nil {
901 uncompressed, err := dc.Do(d.Reader())
902 if err != nil {
903 return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message: %v", err)
Devmalya Pauldd23a992019-11-14 07:06:31 +0000904 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000905 if len(uncompressed) > maxReceiveMessageSize {
906 return nil, status.Errorf(codes.ResourceExhausted, "grpc: message after decompression larger than max (%d vs. %d)", len(uncompressed), maxReceiveMessageSize)
907 }
908 return mem.BufferSlice{mem.SliceBuffer(uncompressed)}, nil
Devmalya Pauldd23a992019-11-14 07:06:31 +0000909 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000910 if compressor != nil {
911 dcReader, err := compressor.Decompress(d.Reader())
912 if err != nil {
913 return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the message: %v", err)
914 }
915
916 // Read at most one byte more than the limit from the decompressor.
917 // Unless the limit is MaxInt64, in which case, that's impossible, so
918 // apply no limit.
919 if limit := int64(maxReceiveMessageSize); limit < math.MaxInt64 {
920 dcReader = io.LimitReader(dcReader, limit+1)
921 }
922 out, err := mem.ReadAll(dcReader, pool)
923 if err != nil {
924 out.Free()
925 return nil, status.Errorf(codes.Internal, "grpc: failed to read decompressed data: %v", err)
926 }
927
928 if out.Len() > maxReceiveMessageSize {
929 out.Free()
930 return nil, status.Errorf(codes.ResourceExhausted, "grpc: received message after decompression larger than max %d", maxReceiveMessageSize)
931 }
932 return out, nil
933 }
934 return nil, status.Errorf(codes.Internal, "grpc: no decompressor available for compressed payload")
935}
936
937type recvCompressor interface {
938 RecvCompress() string
Devmalya Pauldd23a992019-11-14 07:06:31 +0000939}
940
William Kurkianea869482019-04-09 15:16:11 -0400941// For the two compressor parameters, both should not be set, but if they are,
942// dc takes precedence over compressor.
943// TODO(dfawley): wrap the old compressor/decompressor using the new API?
Abhay Kumara61c5222025-11-10 07:32:50 +0000944func recv(p *parser, c baseCodec, s recvCompressor, dc Decompressor, m any, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor, isServer bool) error {
945 data, err := recvAndDecompress(p, s, dc, maxReceiveMessageSize, payInfo, compressor, isServer)
William Kurkianea869482019-04-09 15:16:11 -0400946 if err != nil {
947 return err
948 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000949
950 // If the codec wants its own reference to the data, it can get it. Otherwise, always
951 // free the buffers.
952 defer data.Free()
953
954 if err := c.Unmarshal(data, m); err != nil {
955 return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message: %v", err)
William Kurkianea869482019-04-09 15:16:11 -0400956 }
Abhay Kumara61c5222025-11-10 07:32:50 +0000957
William Kurkianea869482019-04-09 15:16:11 -0400958 return nil
959}
960
Abhilash S.L3b494632019-07-16 15:51:09 +0530961// Information about RPC
William Kurkianea869482019-04-09 15:16:11 -0400962type rpcInfo struct {
Abhilash S.L3b494632019-07-16 15:51:09 +0530963 failfast bool
bseeniva0b9cbcb2026-02-12 19:11:11 +0530964 preloaderInfo compressorInfo
Abhilash S.L3b494632019-07-16 15:51:09 +0530965}
966
967// Information about Preloader
968// Responsible for storing codec, and compressors
969// If stream (s) has context s.Context which stores rpcInfo that has non nil
970// pointers to codec, and compressors, then we can use preparedMsg for Async message prep
971// and reuse marshalled bytes
972type compressorInfo struct {
973 codec baseCodec
974 cp Compressor
975 comp encoding.Compressor
William Kurkianea869482019-04-09 15:16:11 -0400976}
977
978type rpcInfoContextKey struct{}
979
Abhilash S.L3b494632019-07-16 15:51:09 +0530980func newContextWithRPCInfo(ctx context.Context, failfast bool, codec baseCodec, cp Compressor, comp encoding.Compressor) context.Context {
981 return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{
982 failfast: failfast,
bseeniva0b9cbcb2026-02-12 19:11:11 +0530983 preloaderInfo: compressorInfo{
Abhilash S.L3b494632019-07-16 15:51:09 +0530984 codec: codec,
985 cp: cp,
986 comp: comp,
987 },
988 })
William Kurkianea869482019-04-09 15:16:11 -0400989}
990
991func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
992 s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
993 return
994}
995
996// Code returns the error code for err if it was produced by the rpc system.
997// Otherwise, it returns codes.Unknown.
998//
999// Deprecated: use status.Code instead.
1000func Code(err error) codes.Code {
1001 return status.Code(err)
1002}
1003
1004// ErrorDesc returns the error description of err if it was produced by the rpc system.
1005// Otherwise, it returns err.Error() or empty string when err is nil.
1006//
1007// Deprecated: use status.Convert and Message method instead.
1008func ErrorDesc(err error) string {
1009 return status.Convert(err).Message()
1010}
1011
1012// Errorf returns an error containing an error code and a description;
1013// Errorf returns nil if c is OK.
1014//
1015// Deprecated: use status.Errorf instead.
Abhay Kumara61c5222025-11-10 07:32:50 +00001016func Errorf(c codes.Code, format string, a ...any) error {
William Kurkianea869482019-04-09 15:16:11 -04001017 return status.Errorf(c, format, a...)
1018}
1019
Abhay Kumara61c5222025-11-10 07:32:50 +00001020var errContextCanceled = status.Error(codes.Canceled, context.Canceled.Error())
1021var errContextDeadline = status.Error(codes.DeadlineExceeded, context.DeadlineExceeded.Error())
1022
William Kurkianea869482019-04-09 15:16:11 -04001023// toRPCErr converts an error into an error from the status package.
1024func toRPCErr(err error) error {
Abhay Kumara61c5222025-11-10 07:32:50 +00001025 switch err {
1026 case nil, io.EOF:
William Kurkianea869482019-04-09 15:16:11 -04001027 return err
Abhay Kumara61c5222025-11-10 07:32:50 +00001028 case context.DeadlineExceeded:
1029 return errContextDeadline
1030 case context.Canceled:
1031 return errContextCanceled
1032 case io.ErrUnexpectedEOF:
William Kurkianea869482019-04-09 15:16:11 -04001033 return status.Error(codes.Internal, err.Error())
1034 }
Abhay Kumara61c5222025-11-10 07:32:50 +00001035
William Kurkianea869482019-04-09 15:16:11 -04001036 switch e := err.(type) {
1037 case transport.ConnectionError:
1038 return status.Error(codes.Unavailable, e.Desc)
Abhay Kumara61c5222025-11-10 07:32:50 +00001039 case *transport.NewStreamError:
1040 return toRPCErr(e.Err)
William Kurkianea869482019-04-09 15:16:11 -04001041 }
Abhay Kumara61c5222025-11-10 07:32:50 +00001042
1043 if _, ok := status.FromError(err); ok {
1044 return err
1045 }
1046
William Kurkianea869482019-04-09 15:16:11 -04001047 return status.Error(codes.Unknown, err.Error())
1048}
1049
1050// setCallInfoCodec should only be called after CallOptions have been applied.
1051func setCallInfoCodec(c *callInfo) error {
1052 if c.codec != nil {
Abhay Kumara61c5222025-11-10 07:32:50 +00001053 // codec was already set by a CallOption; use it, but set the content
1054 // subtype if it is not set.
1055 if c.contentSubtype == "" {
1056 // c.codec is a baseCodec to hide the difference between grpc.Codec and
1057 // encoding.Codec (Name vs. String method name). We only support
1058 // setting content subtype from encoding.Codec to avoid a behavior
1059 // change with the deprecated version.
1060 if ec, ok := c.codec.(encoding.CodecV2); ok {
1061 c.contentSubtype = strings.ToLower(ec.Name())
1062 }
1063 }
William Kurkianea869482019-04-09 15:16:11 -04001064 return nil
1065 }
1066
1067 if c.contentSubtype == "" {
1068 // No codec specified in CallOptions; use proto by default.
Abhay Kumara61c5222025-11-10 07:32:50 +00001069 c.codec = getCodec(proto.Name)
William Kurkianea869482019-04-09 15:16:11 -04001070 return nil
1071 }
1072
1073 // c.contentSubtype is already lowercased in CallContentSubtype
Abhay Kumara61c5222025-11-10 07:32:50 +00001074 c.codec = getCodec(c.contentSubtype)
William Kurkianea869482019-04-09 15:16:11 -04001075 if c.codec == nil {
1076 return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype)
1077 }
1078 return nil
1079}
1080
William Kurkianea869482019-04-09 15:16:11 -04001081// The SupportPackageIsVersion variables are referenced from generated protocol
1082// buffer files to ensure compatibility with the gRPC version used. The latest
Abhay Kumara61c5222025-11-10 07:32:50 +00001083// support package version is 9.
William Kurkianea869482019-04-09 15:16:11 -04001084//
Abhay Kumara61c5222025-11-10 07:32:50 +00001085// Older versions are kept for compatibility.
William Kurkianea869482019-04-09 15:16:11 -04001086//
1087// These constants should not be referenced from any other code.
1088const (
1089 SupportPackageIsVersion3 = true
1090 SupportPackageIsVersion4 = true
1091 SupportPackageIsVersion5 = true
Abhay Kumara61c5222025-11-10 07:32:50 +00001092 SupportPackageIsVersion6 = true
1093 SupportPackageIsVersion7 = true
1094 SupportPackageIsVersion8 = true
1095 SupportPackageIsVersion9 = true
William Kurkianea869482019-04-09 15:16:11 -04001096)
1097
1098const grpcUA = "grpc-go/" + Version