Package-Level Type Names (total 124, in which 64 are exported)
/* sort exporteds by: | */
AuthorityOverrideCallOption is a CallOption that indicates the HTTP/2
:authority header value to use for the call.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a later
release.Authoritystring( AuthorityOverrideCallOption) after(*callInfo, *csAttempt)( AuthorityOverrideCallOption) before(c *callInfo) error
AuthorityOverrideCallOption : CallOption
BackoffConfig defines the parameters for the default gRPC backoff strategy.
Deprecated: use ConnectParams instead. Will be supported throughout 1.x. MaxDelay is the upper bound of backoff delay.
func WithBackoffConfig(b BackoffConfig) DialOption
var DefaultBackoffConfig
Type Parameters:
Req: any
Res: any BidiStreamingClient represents the client side of a bidirectional-streaming
(many requests, many responses) RPC. It is generic over both the type of the
request message stream and the type of the response message stream. It is
used in generated code. CloseSend closes the send direction of the stream. It closes the stream
when non-nil error is met. It is also not safe to call CloseSend
concurrently with SendMsg. Context returns the context for this stream.
It should not be called until after Header or RecvMsg has returned. Once
called, subsequent client-side retries are disabled. Header returns the header metadata received from the server if there
is any. It blocks if the metadata is not ready to read. Recv receives the next response message from the server. The client may
repeatedly call Recv to read messages from the response stream. If
io.EOF is returned, the stream has terminated with an OK status. Any
other error is compatible with the status package and indicates the
RPC's status code and message. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the stream completes successfully. On
any other error, the stream is aborted and the error contains the RPC
status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. Send sends a request message to the server. The client may call Send
multiple times to send multiple messages to the server. On error, Send
aborts the stream. If the error was generated by the client, the status
is returned directly. Otherwise, io.EOF is returned, and the status of
the stream may be discovered using Recv(). SendMsg is generally called by generated code. On error, SendMsg aborts
the stream. If the error was generated by the client, the status is
returned directly; otherwise, io.EOF is returned and the status of
the stream may be discovered using RecvMsg.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the server. An
untimely stream closure may result in lost messages. To ensure delivery,
users should ensure the RPC completed successfully using RecvMsg.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines. It is also
not safe to call CloseSend concurrently with SendMsg. Trailer returns the trailer metadata from the server, if there is any.
It must only be called after stream.CloseAndRecv has returned, or
stream.Recv has returned a non-nil error (including io.EOF).
BidiStreamingClient : ClientStream[grpc_health_v1.HealthCheckResponse]
BidiStreamingClient : Stream
BidiStreamingClient : google.golang.org/grpc/internal/resolver.ClientStream
Type Parameters:
Req: any
Res: any BidiStreamingServer represents the server side of a bidirectional-streaming
(many requests, many responses) RPC. It is generic over both the type of the
request message stream and the type of the response message stream. It is
used in generated code.
To terminate the stream, return from the handler method and return
an error from the status package, or use nil to indicate an OK status code. Context returns the context for this stream. Recv receives the next request message from the client. The server may
repeatedly call Recv to read messages from the request stream. If
io.EOF is returned, it indicates the client called CloseSend on its
BidiStreamingClient. Any other error indicates the stream was
terminated unexpectedly, and the handler method should return, as the
stream is no longer usable. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the client has performed a CloseSend. On
any non-EOF error, the stream is aborted and the error contains the
RPC status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. Send sends a response message to the client. The server handler may
call Send multiple times to send multiple messages to the client. An
error is returned if the stream was terminated unexpectedly, and the
handler method should return, as the stream is no longer usable. SendHeader sends the header metadata.
The provided md and headers set by SetHeader() will be sent.
It fails if called multiple times. SendMsg sends a message. On error, SendMsg aborts the stream and the
error is returned directly.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the client. An
untimely stream closure may result in lost messages.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines.
It is not safe to modify the message after calling SendMsg. Tracing
libraries and stats handlers may use the message lazily. SetHeader sets the header metadata. It may be called multiple times.
When call multiple times, all the provided metadata will be merged.
All the metadata will be sent out when one of the following happens:
- ServerStream.SendHeader() is called;
- The first response is sent out;
- An RPC status is sent out (error or success). SetTrailer sets the trailer metadata which will be sent with the RPC status.
When called more than once, all the provided metadata will be merged.
BidiStreamingServer : ServerStream[grpc_health_v1.HealthCheckResponse]
BidiStreamingServer : Stream
ClientConn represents a virtual connection to a conceptual endpoint, to
perform RPCs.
A ClientConn is free to have zero or more actual connections to the endpoint
based on configuration, load, etc. It is also free to determine which actual
endpoints to use and may change it every RPC, permitting client-side load
balancing.
A ClientConn encapsulates a range of functionality including name
resolution, TCP connection establishment (with retries and backoff) and TLS
handshakes. It also handles errors on established connections by
re-resolving the name and reconnecting. // See initAuthority(). // Always recreated whenever entering idle to simplify Close. // Cancelled on close. // Channelz object. // Set to nil on close. The following provide their own synchronization, and therefore don't
require cc.mu to be held to access them. // Initialized using the background context at dial time. // Default and user specified dial options. firstResolveEvent is used to track whether the name resolver sent us at
least one update. RPCs block on this event. May be accessed without mu
if we know we cannot be asked to enter idle mode while accessing it (e.g.
when the idle manager has already been closed, or if we are already
entering idle mode).idlenessMgr*idle.Manager // May be updated upon receipt of a GoAway.lastConnectionErrorerror // protects lastConnectionErrormetricsRecorderList*stats.MetricsRecorderList mu protects the following fields.
TODO: split mu so the same mutex isn't used for everything. // See initParsedTargetAndResolverBuilder().pickerWrapper*pickerWrapper // See initParsedTargetAndResolverBuilder(). // Always recreated whenever entering idle to simplify Close. // Updated from service config.safeConfigSelectoriresolver.SafeConfigSelector // Latest service config received from the resolver. The following are initialized at dial time, and are read-only after that. // User's dial target. CanonicalTarget returns the canonical target string used when creating cc.
This always has the form "<scheme>://[authority]/<endpoint>". For example:
- "dns:///example.com:42"
- "dns://8.8.8.8/example.com:42"
- "unix:///path/to/socket" Close tears down the ClientConn and all underlying connections. Connect causes all subchannels in the ClientConn to attempt to connect if
the channel is idle. Does not wait for the connection attempts to begin
before returning.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a later
release. GetMethodConfig gets the method config of the input method.
If there's an exact match for input method (i.e. /service/method), we return
the corresponding MethodConfig.
If there isn't an exact match for the input method, we look for the service's default
config under the service (i.e /service/) and then for the default for all services (empty string).
If there is a default MethodConfig for the service, we return it.
Otherwise, we return an empty MethodConfig. GetState returns the connectivity.State of ClientConn. Invoke sends the RPC request on the wire and returns after response is
received. This is typically called by generated code.
All errors returned by Invoke are compatible with the status package. NewStream creates a new Stream for the client side. This is typically
called by generated code. ctx is used for the lifetime of the stream.
To ensure resources are not leaked due to the stream returned, one of the following
actions must be performed:
1. Call Close on the ClientConn.
2. Cancel the context provided.
3. Call RecvMsg until a non-nil error is returned. A protobuf-generated
client-streaming RPC, for instance, might use the helper function
CloseAndRecv (note that CloseSend does not Recv, therefore is not
guaranteed to release all resources).
4. Receive a non-nil, non-io.EOF error from Header or SendMsg.
If none of the above happen, a goroutine and a context will be leaked, and grpc
will not call the optionally-configured stats handler with a stats.End message. ResetConnectBackoff wakes up all subchannels in transient failure and causes
them to attempt another connection immediately. It also resets the backoff
times used for subsequent attempts regardless of the current state.
In general, this function should not be used. Typical service or network
outages result in a reasonable client reconnection strategy by default.
However, if a previously unavailable network becomes available, this may be
used to trigger an immediate reconnect.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release. Target returns the target string of the ClientConn. WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or
ctx expires. A true value is returned in former case and false in latter. addTraceEvent is a helper method to add a trace event on the channel. If the
channel is a nested one, the same event is also added on the parent channel. applyFailingLBLocked is akin to configuring an LB policy on the channel which
always fails RPCs. Here, an actual LB policy is not configured, but an always
erroring picker is configured, which returns errors with information about
what was invalid in the received service config. A config selector with no
service config is configured, and the connectivity state of the channel is
set to TransientFailure.(*ClientConn) applyServiceConfigAndBalancer(sc *ServiceConfig, configSelector iresolver.ConfigSelector) channelzRegistration registers the newly created ClientConn with channelz and
stores the returned identifier in `cc.channelz`. A channelz trace event is
emitted for ClientConn creation. If the newly created ClientConn is a nested
one, i.e a valid parent ClientConn ID is specified via a dial option, the
trace event is also added to the parent.
Doesn't grab cc.mu as this method is expected to be called only at Dial time.(*ClientConn) connectionError() error enterIdleMode puts the channel in idle mode, and as part of it shuts down the
name resolver, load balancer, and any subchannels. This should never be
called directly; use cc.idlenessMgr.EnterIdleMode instead. exitIdleMode moves the channel out of idle mode by recreating the name
resolver and load balancer. This should never be called directly; use
cc.idlenessMgr.ExitIdleMode instead. getResolver finds the scheme in the cc's resolvers or the global registry.
scheme should always be lowercase (typically by virtue of url.Parse()
performing proper RFC3986 behavior). getServerName determines the serverName to be used in the connection
handshake. The default value for the serverName is the authority on the
ClientConn, which either comes from the user's dial target or through an
authority override specified using the WithAuthority dial option. Name
resolvers can specify a per-address override for the serverName through the
resolver.Address.ServerName field which is used only if the WithAuthority
dial option was not used. The rationale is that per-address authority
overrides specified by the name resolver can represent a security risk, while
an override specified by the user is more dependable since they probably know
what they are doing.(*ClientConn) healthCheckConfig() *healthCheckConfig(*ClientConn) incrCallsFailed()(*ClientConn) incrCallsStarted()(*ClientConn) incrCallsSucceeded() Determine channel authority. The order of precedence is as follows:
- user specified authority override using `WithAuthority` dial option
- creds' notion of server name for the authentication handshake
- endpoint from dial target of the form "scheme://[authority]/endpoint"
Stores the determined authority in `cc.authority`.
Returns a non-nil error if the authority returned by the transport
credentials do not match the authority configured through the dial option.
Doesn't grab cc.mu as this method is expected to be called only at Dial time. initIdleStateLocked initializes common state to how it should be while idle. initParsedTargetAndResolverBuilder parses the user's dial target and stores
the parsed target in `cc.parsedTarget`.
The resolver to use is determined based on the scheme in the parsed target
and the same is stored in `cc.resolverBuilder`.
Doesn't grab cc.mu as this method is expected to be called only at Dial time.(*ClientConn) maybeApplyDefaultServiceConfig() newAddrConnLocked creates an addrConn for addrs and adds it to cc.conns.
Caller needs to make sure len(addrs) > 0. removeAddrConn removes the addrConn in the subConn from clientConn.
It also tears down the ac with the given error.(*ClientConn) resolveNow(o resolver.ResolveNowOptions)(*ClientConn) resolveNowLocked(o resolver.ResolveNowOptions)(*ClientConn) updateConnectionError(err error)(*ClientConn) updateResolverStateAndUnlock(s resolver.State, err error) error validateTransportCredentials performs a series of checks on the configured
transport credentials. It returns a non-nil error if any of these conditions
are met:
- no transport creds and no creds bundle is configured
- both transport creds and creds bundle are configured
- creds bundle is configured, but it lacks a transport credentials
- insecure transport creds configured alongside call creds that require
transport level security
If none of the above conditions are met, the configured credentials are
deemed valid and a nil error is returned. waitForResolvedAddrs blocks until the resolver provides addresses or the
context expires, whichever happens first.
Error is nil unless the context expires first; otherwise returns a status
error based on the context.
The returned boolean indicates whether it did block or not. If the
resolution has already happened once before, it returns false without
blocking. Otherwise, it wait for the resolution and return true if
resolution has succeeded or return false along with error if resolution has
failed.
*ClientConn : ClientConnInterface
*ClientConn : io.Closer
func Dial(target string, opts ...DialOption) (*ClientConn, error)
func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error)
func NewClient(target string, opts ...DialOption) (conn *ClientConn, err error)
func Invoke(ctx context.Context, method string, args, reply any, cc *ClientConn, opts ...CallOption) error
func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)
func chainStreamClientInterceptors(cc *ClientConn)
func chainUnaryClientInterceptors(cc *ClientConn)
func invoke(ctx context.Context, method string, req, reply any, cc *ClientConn, opts ...CallOption) error
func newCCBalancerWrapper(cc *ClientConn) *ccBalancerWrapper
func newCCResolverWrapper(cc *ClientConn) *ccResolverWrapper
func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error)
func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, mc serviceconfig.MethodConfig, onCommit, doneFunc func(), nameResolutionDelayed bool, opts ...CallOption) (_ iresolver.ClientStream, err error)
ClientConnInterface defines the functions clients need to perform unary and
streaming RPCs. It is implemented by *ClientConn, and is only intended to
be referenced by generated code. Invoke performs a unary RPC and returns after the response is received
into reply. NewStream begins a streaming RPC.
*ClientConn
*acBalancerWrapper
func google.golang.org/grpc/health/grpc_health_v1.NewHealthClient(cc ClientConnInterface) grpc_health_v1.HealthClient
ClientStream defines the client-side behavior of a streaming RPC.
All errors returned from ClientStream methods are compatible with the
status package. CloseSend closes the send direction of the stream. It closes the stream
when non-nil error is met. It is also not safe to call CloseSend
concurrently with SendMsg. Context returns the context for this stream.
It should not be called until after Header or RecvMsg has returned. Once
called, subsequent client-side retries are disabled. Header returns the header metadata received from the server if there
is any. It blocks if the metadata is not ready to read. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the stream completes successfully. On
any other error, the stream is aborted and the error contains the RPC
status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. SendMsg is generally called by generated code. On error, SendMsg aborts
the stream. If the error was generated by the client, the status is
returned directly; otherwise, io.EOF is returned and the status of
the stream may be discovered using RecvMsg.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the server. An
untimely stream closure may result in lost messages. To ensure delivery,
users should ensure the RPC completed successfully using RecvMsg.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines. It is also
not safe to call CloseSend concurrently with SendMsg. Trailer returns the trailer metadata from the server, if there is any.
It must only be called after stream.CloseAndRecv has returned, or
stream.Recv has returned a non-nil error (including io.EOF).BidiStreamingClient[...] (interface)ClientStreamingClient[...] (interface)GenericClientStream[...]ServerStreamingClient[...] (interface)
google.golang.org/grpc/internal/resolver.ClientStream(interface)
*addrConnStream
*clientStream
ClientStream : Stream
ClientStream : google.golang.org/grpc/internal/resolver.ClientStream
func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)
func (*ClientConn).NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
func ClientConnInterface.NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error)
func newNonRetryClientStream(ctx context.Context, desc *StreamDesc, method string, t transport.ClientTransport, ac *addrConn, opts ...CallOption) (_ ClientStream, err error)
Type Parameters:
Req: any
Res: any ClientStreamingClient represents the client side of a client-streaming (many
requests, one response) RPC. It is generic over both the type of the request
message stream and the type of the unary response message. It is used in
generated code. CloseAndRecv closes the request stream and waits for the server's
response. This method must be called once and only once after sending
all request messages. Any error returned is implemented by the status
package. CloseSend closes the send direction of the stream. It closes the stream
when non-nil error is met. It is also not safe to call CloseSend
concurrently with SendMsg. Context returns the context for this stream.
It should not be called until after Header or RecvMsg has returned. Once
called, subsequent client-side retries are disabled. Header returns the header metadata received from the server if there
is any. It blocks if the metadata is not ready to read. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the stream completes successfully. On
any other error, the stream is aborted and the error contains the RPC
status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. Send sends a request message to the server. The client may call Send
multiple times to send multiple messages to the server. On error, Send
aborts the stream. If the error was generated by the client, the status
is returned directly. Otherwise, io.EOF is returned, and the status of
the stream may be discovered using CloseAndRecv(). SendMsg is generally called by generated code. On error, SendMsg aborts
the stream. If the error was generated by the client, the status is
returned directly; otherwise, io.EOF is returned and the status of
the stream may be discovered using RecvMsg.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the server. An
untimely stream closure may result in lost messages. To ensure delivery,
users should ensure the RPC completed successfully using RecvMsg.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines. It is also
not safe to call CloseSend concurrently with SendMsg. Trailer returns the trailer metadata from the server, if there is any.
It must only be called after stream.CloseAndRecv has returned, or
stream.Recv has returned a non-nil error (including io.EOF).
ClientStreamingClient : ClientStream[grpc_health_v1.HealthCheckResponse]
ClientStreamingClient : Stream
ClientStreamingClient : google.golang.org/grpc/internal/resolver.ClientStream
Type Parameters:
Req: any
Res: any ClientStreamingServer represents the server side of a client-streaming (many
requests, one response) RPC. It is generic over both the type of the request
message stream and the type of the unary response message. It is used in
generated code.
To terminate the RPC, call SendAndClose and return nil from the method
handler or do not call SendAndClose and return an error from the status
package. Context returns the context for this stream. Recv receives the next request message from the client. The server may
repeatedly call Recv to read messages from the request stream. If
io.EOF is returned, it indicates the client called CloseAndRecv on its
ClientStreamingClient. Any other error indicates the stream was
terminated unexpectedly, and the handler method should return, as the
stream is no longer usable. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the client has performed a CloseSend. On
any non-EOF error, the stream is aborted and the error contains the
RPC status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. SendAndClose sends a single response message to the client and closes
the stream. This method must be called once and only once after all
request messages have been processed. Recv should not be called after
calling SendAndClose. SendHeader sends the header metadata.
The provided md and headers set by SetHeader() will be sent.
It fails if called multiple times. SendMsg sends a message. On error, SendMsg aborts the stream and the
error is returned directly.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the client. An
untimely stream closure may result in lost messages.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines.
It is not safe to modify the message after calling SendMsg. Tracing
libraries and stats handlers may use the message lazily. SetHeader sets the header metadata. It may be called multiple times.
When call multiple times, all the provided metadata will be merged.
All the metadata will be sent out when one of the following happens:
- ServerStream.SendHeader() is called;
- The first response is sent out;
- An RPC status is sent out (error or success). SetTrailer sets the trailer metadata which will be sent with the RPC status.
When called more than once, all the provided metadata will be merged.
ClientStreamingServer : ServerStream[grpc_health_v1.HealthCheckResponse]
ClientStreamingServer : Stream
Codec defines the interface gRPC uses to encode and decode messages.
Note that implementations of this interface must be thread safe;
a Codec's methods can be called from concurrent goroutines.
Deprecated: use encoding.Codec instead. Marshal returns the wire format of v. String returns the name of the Codec implementation. This is unused by
gRPC. Unmarshal parses the wire format into v.
Codec : expvar.Var
Codec : fmt.Stringer
Codec : context.stringer
Codec : runtime.stringer
func CallCustomCodec(codec Codec) CallOption
func CustomCodec(codec Codec) ServerOption
func WithCodec(c Codec) DialOption
func newCodecV0Bridge(c Codec) baseCodec
CompressorCallOption is a CallOption that indicates the compressor to use.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.CompressorTypestring( CompressorCallOption) after(*callInfo, *csAttempt)( CompressorCallOption) before(c *callInfo) error
CompressorCallOption : CallOption
ConnectParams defines the parameters for connecting and retrying. Users are
encouraged to use this instead of the BackoffConfig type defined above. See
here for more details:
https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release. Backoff specifies the configuration options for connection backoff. MinConnectTimeout is the minimum amount of time we are willing to give a
connection to complete.
func WithConnectParams(p ConnectParams) DialOption
ContentSubtypeCallOption is a CallOption that indicates the content-subtype
used for marshaling messages.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.ContentSubtypestring( ContentSubtypeCallOption) after(*callInfo, *csAttempt)( ContentSubtypeCallOption) before(c *callInfo) error
ContentSubtypeCallOption : CallOption
CustomCodecCallOption is a CallOption that indicates the codec used for
marshaling messages.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.CodecCodec( CustomCodecCallOption) after(*callInfo, *csAttempt)( CustomCodecCallOption) before(c *callInfo) error
CustomCodecCallOption : CallOption
EmptyCallOption does not alter the Call configuration.
It can be embedded in another structure to carry satellite data for use
by interceptors.( EmptyCallOption) after(*callInfo, *csAttempt)( EmptyCallOption) before(*callInfo) error
EmptyCallOption : CallOption
EmptyDialOption does not alter the dial configuration. It can be embedded in
another structure to build custom dial options.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.( EmptyDialOption) apply(*dialOptions)
EmptyDialOption : DialOption
EmptyServerOption does not alter the server configuration. It can be embedded
in another structure to build custom server options.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.( EmptyServerOption) apply(*serverOptions)
EmptyServerOption : ServerOption
FailFastCallOption is a CallOption for indicating whether an RPC should fail
fast or not.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.FailFastbool( FailFastCallOption) after(*callInfo, *csAttempt)( FailFastCallOption) before(c *callInfo) error
FailFastCallOption : CallOption
ForceCodecCallOption is a CallOption that indicates the codec used for
marshaling messages.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.Codecencoding.Codec( ForceCodecCallOption) after(*callInfo, *csAttempt)( ForceCodecCallOption) before(c *callInfo) error
ForceCodecCallOption : CallOption
ForceCodecV2CallOption is a CallOption that indicates the codec used for
marshaling messages.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.CodecV2encoding.CodecV2( ForceCodecV2CallOption) after(*callInfo, *csAttempt)( ForceCodecV2CallOption) before(c *callInfo) error
ForceCodecV2CallOption : CallOption
Type Parameters:
Req: any
Res: any GenericClientStream implements the ServerStreamingClient, ClientStreamingClient,
and BidiStreamingClient interfaces. It is used in generated code.ClientStreamClientStream CloseAndRecv closes the sending side of the stream, then receives the unary
response from the server. The type of message which it returns is determined
by the Res type parameter of the GenericClientStream receiver. CloseSend closes the send direction of the stream. It closes the stream
when non-nil error is met. It is also not safe to call CloseSend
concurrently with SendMsg. Context returns the context for this stream.
It should not be called until after Header or RecvMsg has returned. Once
called, subsequent client-side retries are disabled. Header returns the header metadata received from the server if there
is any. It blocks if the metadata is not ready to read. Recv reads one message from the stream of responses generated by the server.
The type of the message returned is determined by the Res type parameter
of the GenericClientStream receiver. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the stream completes successfully. On
any other error, the stream is aborted and the error contains the RPC
status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. Send pushes one message into the stream of requests to be consumed by the
server. The type of message which can be sent is determined by the Req type
parameter of the GenericClientStream receiver. SendMsg is generally called by generated code. On error, SendMsg aborts
the stream. If the error was generated by the client, the status is
returned directly; otherwise, io.EOF is returned and the status of
the stream may be discovered using RecvMsg.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the server. An
untimely stream closure may result in lost messages. To ensure delivery,
users should ensure the RPC completed successfully using RecvMsg.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines. It is also
not safe to call CloseSend concurrently with SendMsg. Trailer returns the trailer metadata from the server, if there is any.
It must only be called after stream.CloseAndRecv has returned, or
stream.Recv has returned a non-nil error (including io.EOF).
GenericClientStream : ClientStream[grpc_health_v1.HealthCheckResponse]
GenericClientStream : Stream
GenericClientStream : google.golang.org/grpc/internal/resolver.ClientStream
Type Parameters:
Req: any
Res: any GenericServerStream implements the ServerStreamingServer, ClientStreamingServer,
and BidiStreamingServer interfaces. It is used in generated code.ServerStreamServerStream Context returns the context for this stream. Recv reads one message from the stream of requests generated by the client.
The type of the message returned is determined by the Req type parameter
of the clientStreamServer receiver. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the client has performed a CloseSend. On
any non-EOF error, the stream is aborted and the error contains the
RPC status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. Send pushes one message into the stream of responses to be consumed by the
client. The type of message which can be sent is determined by the Res
type parameter of the serverStreamServer receiver. SendAndClose pushes the unary response to the client. The type of message
which can be sent is determined by the Res type parameter of the
clientStreamServer receiver. SendHeader sends the header metadata.
The provided md and headers set by SetHeader() will be sent.
It fails if called multiple times. SendMsg sends a message. On error, SendMsg aborts the stream and the
error is returned directly.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the client. An
untimely stream closure may result in lost messages.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines.
It is not safe to modify the message after calling SendMsg. Tracing
libraries and stats handlers may use the message lazily. SetHeader sets the header metadata. It may be called multiple times.
When call multiple times, all the provided metadata will be merged.
All the metadata will be sent out when one of the following happens:
- ServerStream.SendHeader() is called;
- The first response is sent out;
- An RPC status is sent out (error or success). SetTrailer sets the trailer metadata which will be sent with the RPC status.
When called more than once, all the provided metadata will be merged.
GenericServerStream : ServerStream[grpc_health_v1.HealthCheckResponse]
GenericServerStream : Stream
HeaderCallOption is a CallOption for collecting response header metadata.
The metadata field will be populated *after* the RPC completes.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.HeaderAddr*metadata.MD( HeaderCallOption) after(_ *callInfo, attempt *csAttempt)( HeaderCallOption) before(*callInfo) error
HeaderCallOption : CallOption
MaxHeaderListSizeDialOption is a DialOption that specifies the maximum
(uncompressed) size of header list that the client is prepared to accept.MaxHeaderListSizeuint32( MaxHeaderListSizeDialOption) apply(do *dialOptions)
MaxHeaderListSizeDialOption : DialOption
MaxHeaderListSizeServerOption is a ServerOption that sets the max
(uncompressed) size of header list that the server is prepared to accept.MaxHeaderListSizeuint32( MaxHeaderListSizeServerOption) apply(so *serverOptions)
MaxHeaderListSizeServerOption : ServerOption
MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message
size in bytes the client can receive.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.MaxRecvMsgSizeint( MaxRecvMsgSizeCallOption) after(*callInfo, *csAttempt)( MaxRecvMsgSizeCallOption) before(c *callInfo) error
MaxRecvMsgSizeCallOption : CallOption
MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of
memory to be used for caching this RPC for retry purposes.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.MaxRetryRPCBufferSizeint( MaxRetryRPCBufferSizeCallOption) after(*callInfo, *csAttempt)( MaxRetryRPCBufferSizeCallOption) before(c *callInfo) error
MaxRetryRPCBufferSizeCallOption : CallOption
MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message
size in bytes the client can send.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.MaxSendMsgSizeint( MaxSendMsgSizeCallOption) after(*callInfo, *csAttempt)( MaxSendMsgSizeCallOption) before(c *callInfo) error
MaxSendMsgSizeCallOption : CallOption
MethodConfig defines the configuration recommended by the service providers for a
particular method.
Deprecated: Users should not use this struct. Service config should be received
through name resolver, as specified here
https://github.com/grpc/grpc/blob/master/doc/service_config.md
MethodHandler is a function type that processes a unary RPC method call.
MethodInfo contains the information of an RPC including its method name and type. IsClientStream indicates whether the RPC is a client streaming RPC. IsServerStream indicates whether the RPC is a server streaming RPC. Name is the method name only, without the service name or package name.
OnFinishCallOption is CallOption that indicates a callback to be called when
the call completes.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.OnFinishfunc(error)( OnFinishCallOption) after(*callInfo, *csAttempt)( OnFinishCallOption) before(c *callInfo) error
OnFinishCallOption : CallOption
PeerCallOption is a CallOption for collecting the identity of the remote
peer. The peer field will be populated *after* the RPC completes.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.PeerAddr*peer.Peer( PeerCallOption) after(_ *callInfo, attempt *csAttempt)( PeerCallOption) before(*callInfo) error
PeerCallOption : CallOption
PerRPCCredsCallOption is a CallOption that indicates the per-RPC
credentials to use for the call.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.Credscredentials.PerRPCCredentials( PerRPCCredsCallOption) after(*callInfo, *csAttempt)( PerRPCCredsCallOption) before(c *callInfo) error
PerRPCCredsCallOption : CallOption
PreparedMsg is responsible for creating a Marshalled and Compressed object.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release. Struct for preparing msg before sending themhdr[]bytepayloadmem.BufferSlicepfpayloadFormat Encode marshalls and compresses the message using the codec and compressor for the stream.
Server is a gRPC server to serve RPC requests.channelz*channelz.ServerchannelzRemoveOncesync.Once conns contains all active server transports. It is a map keyed on a
listener address with the value being the set of active transports
belonging to that listener. // signaled when connections close for GracefulStopdone*grpcsync.EventdrainbooleventstraceEventLog // counts active method handler goroutineslismap[net.Listener]bool // guards followingoptsserverOptionsquit*grpcsync.Eventservebool // counts active Serve goroutines for Stop/GracefulStopserverWorkerChannelchan func()serverWorkerChannelClosefunc() // service name -> service info GetServiceInfo returns a map from service names to ServiceInfo.
Service names include the package names, in the form of <package>.<service>. GracefulStop stops the gRPC server gracefully. It stops the server from
accepting new connections and RPCs and blocks until all the pending RPCs are
finished. RegisterService registers a service and its implementation to the gRPC
server. It is called from the IDL generated code. This must be called before
invoking Serve. If ss is non-nil (for legacy code), its type is checked to
ensure it implements sd.HandlerType. Serve accepts incoming connections on the listener lis, creating a new
ServerTransport and service goroutine for each. The service goroutines
read gRPC requests and then call the registered handlers to reply to them.
Serve returns when lis.Accept fails with fatal errors. lis will be closed when
this method returns.
Serve will return a non-nil error unless Stop or GracefulStop is called.
Note: All supported releases of Go (as of December 2023) override the OS
defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive
with OS defaults for keepalive time and interval, callers need to do the
following two things:
- pass a net.Listener created by calling the Listen method on a
net.ListenConfig with the `KeepAlive` field set to a negative value. This
will result in the Go standard library not overriding OS defaults for TCP
keepalive interval and time. But this will also result in the Go standard
library not enabling TCP keepalives by default.
- override the Accept method on the passed in net.Listener and set the
SO_KEEPALIVE socket option to enable TCP keepalives, with OS defaults. ServeHTTP implements the Go standard library's http.Handler
interface by responding to the gRPC request r, by looking up
the requested gRPC method in the gRPC server s.
The provided HTTP request must have arrived on an HTTP/2
connection. When using the Go standard library's server,
practically this means that the Request must also have arrived
over TLS.
To share one port (such as 443 for https) between gRPC and an
existing http.Handler, use a root http.Handler such as:
if r.ProtoMajor == 2 && strings.HasPrefix(
r.Header.Get("Content-Type"), "application/grpc") {
grpcServer.ServeHTTP(w, r)
} else {
yourMux.ServeHTTP(w, r)
}
Note that ServeHTTP uses Go's HTTP/2 server implementation which is totally
separate from grpc-go's HTTP/2 server. Performance and features may vary
between the two paths. ServeHTTP does not support some gRPC features
available through grpc-go's HTTP/2 server.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release. Stop stops the gRPC server. It immediately closes all open
connections and listeners.
It cancels all active RPCs on the server side and the corresponding
pending RPCs on the client side will get notified by connection
errors.(*Server) addConn(addr string, st transport.ServerTransport) bool s.mu must be held by the caller. s.mu must be held by the caller. s.mu must be held by the caller. errorf records an error in s's event log, unless s has been stopped.
REQUIRES s.mu is held. contentSubtype must be lowercase
cannot return nil handleRawConn forks a goroutine to handle a just-accepted connection that
has not had any I/O performed on it yet.(*Server) handleStream(t transport.ServerTransport, stream *transport.ServerStream)(*Server) incrCallsFailed()(*Server) incrCallsStarted()(*Server) incrCallsSucceeded() initServerWorkers creates worker goroutines and a channel to process incoming
connections to reduce the time spent overall on runtime.morestack. isRegisteredMethod returns whether the passed in method is registered as a
method on the server. /service/method and service/method will match if the
service and method are registered on the server. newHTTP2Transport sets up a http/2 transport (using the
gRPC http2 server transport in transport/http2_server.go). printf records an event in s's event log, unless s has been stopped.
REQUIRES s.mu is held.(*Server) processStreamingRPC(ctx context.Context, stream *transport.ServerStream, info *serviceInfo, sd *StreamDesc, trInfo *traceInfo) (err error)(*Server) processUnaryRPC(ctx context.Context, stream *transport.ServerStream, info *serviceInfo, md *MethodDesc, trInfo *traceInfo) (err error)(*Server) register(sd *ServiceDesc, ss any)(*Server) removeConn(addr string, st transport.ServerTransport)(*Server) sendResponse(ctx context.Context, stream *transport.ServerStream, msg any, cp Compressor, opts *transport.WriteOptions, comp encoding.Compressor) error(*Server) serveStreams(ctx context.Context, st transport.ServerTransport, rawConn net.Conn) serverWorker blocks on a *transport.ServerStream channel forever and waits
for data to be fed by serveStreams. This allows multiple requests to be
processed by the same goroutine, removing the need for expensive stack
re-allocations (see the runtime.morestack problem [1]).
[1] https://github.com/golang/go/issues/18138(*Server) stop(graceful bool)
*Server : ServiceRegistrar
*Server : net/http.Handler
func NewServer(opt ...ServerOption) *Server
func serverFromContext(ctx context.Context) *Server
func go.pact.im/x/grpcprocess.Server(srv *Server, lis net.Listener) process.Runner
func chainStreamServerInterceptors(s *Server)
func chainUnaryServerInterceptors(s *Server)
func contextWithServer(ctx context.Context, server *Server) context.Context
ServerStream defines the server-side behavior of a streaming RPC.
Errors returned from ServerStream methods are compatible with the status
package. However, the status code will often not match the RPC status as
seen by the client application, and therefore, should not be relied upon for
this purpose. Context returns the context for this stream. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the client has performed a CloseSend. On
any non-EOF error, the stream is aborted and the error contains the
RPC status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. SendHeader sends the header metadata.
The provided md and headers set by SetHeader() will be sent.
It fails if called multiple times. SendMsg sends a message. On error, SendMsg aborts the stream and the
error is returned directly.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the client. An
untimely stream closure may result in lost messages.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines.
It is not safe to modify the message after calling SendMsg. Tracing
libraries and stats handlers may use the message lazily. SetHeader sets the header metadata. It may be called multiple times.
When call multiple times, all the provided metadata will be merged.
All the metadata will be sent out when one of the following happens:
- ServerStream.SendHeader() is called;
- The first response is sent out;
- An RPC status is sent out (error or success). SetTrailer sets the trailer metadata which will be sent with the RPC status.
When called more than once, all the provided metadata will be merged.BidiStreamingServer[...] (interface)ClientStreamingServer[...] (interface)GenericServerStream[...]ServerStreamingServer[...] (interface)
ServerStream : Stream
func MethodFromServerStream(stream ServerStream) (string, bool)
func google.golang.org/grpc/health/grpc_health_v1._Health_Watch_Handler(srv interface{}, stream ServerStream) error
Type Parameters:
Res: any ServerStreamingClient represents the client side of a server-streaming (one
request, many responses) RPC. It is generic over the type of the response
message. It is used in generated code. CloseSend closes the send direction of the stream. It closes the stream
when non-nil error is met. It is also not safe to call CloseSend
concurrently with SendMsg. Context returns the context for this stream.
It should not be called until after Header or RecvMsg has returned. Once
called, subsequent client-side retries are disabled. Header returns the header metadata received from the server if there
is any. It blocks if the metadata is not ready to read. Recv receives the next response message from the server. The client may
repeatedly call Recv to read messages from the response stream. If
io.EOF is returned, the stream has terminated with an OK status. Any
other error is compatible with the status package and indicates the
RPC's status code and message. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the stream completes successfully. On
any other error, the stream is aborted and the error contains the RPC
status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. SendMsg is generally called by generated code. On error, SendMsg aborts
the stream. If the error was generated by the client, the status is
returned directly; otherwise, io.EOF is returned and the status of
the stream may be discovered using RecvMsg.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the server. An
untimely stream closure may result in lost messages. To ensure delivery,
users should ensure the RPC completed successfully using RecvMsg.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines. It is also
not safe to call CloseSend concurrently with SendMsg. Trailer returns the trailer metadata from the server, if there is any.
It must only be called after stream.CloseAndRecv has returned, or
stream.Recv has returned a non-nil error (including io.EOF).
ServerStreamingClient : ClientStream[grpc_health_v1.HealthCheckResponse]
ServerStreamingClient : Stream
ServerStreamingClient : google.golang.org/grpc/internal/resolver.ClientStream
func google.golang.org/grpc/health/grpc_health_v1.HealthClient[Res].Watch(ctx context.Context, in *grpc_health_v1.HealthCheckRequest, opts ...CallOption) (ServerStreamingClient[grpc_health_v1.HealthCheckResponse], error)
Type Parameters:
Res: any ServerStreamingServer represents the server side of a server-streaming (one
request, many responses) RPC. It is generic over the type of the response
message. It is used in generated code.
To terminate the response stream, return from the handler method and return
an error from the status package, or use nil to indicate an OK status code. Context returns the context for this stream. RecvMsg blocks until it receives a message into m or the stream is
done. It returns io.EOF when the client has performed a CloseSend. On
any non-EOF error, the stream is aborted and the error contains the
RPC status.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not
safe to call RecvMsg on the same stream in different goroutines. Send sends a response message to the client. The server handler may
call Send multiple times to send multiple messages to the client. An
error is returned if the stream was terminated unexpectedly, and the
handler method should return, as the stream is no longer usable. SendHeader sends the header metadata.
The provided md and headers set by SetHeader() will be sent.
It fails if called multiple times. SendMsg sends a message. On error, SendMsg aborts the stream and the
error is returned directly.
SendMsg blocks until:
- There is sufficient flow control to schedule m with the transport, or
- The stream is done, or
- The stream breaks.
SendMsg does not wait until the message is received by the client. An
untimely stream closure may result in lost messages.
It is safe to have a goroutine calling SendMsg and another goroutine
calling RecvMsg on the same stream at the same time, but it is not safe
to call SendMsg on the same stream in different goroutines.
It is not safe to modify the message after calling SendMsg. Tracing
libraries and stats handlers may use the message lazily. SetHeader sets the header metadata. It may be called multiple times.
When call multiple times, all the provided metadata will be merged.
All the metadata will be sent out when one of the following happens:
- ServerStream.SendHeader() is called;
- The first response is sent out;
- An RPC status is sent out (error or success). SetTrailer sets the trailer metadata which will be sent with the RPC status.
When called more than once, all the provided metadata will be merged.
ServerStreamingServer : ServerStream[grpc_health_v1.HealthCheckResponse]
ServerStreamingServer : Stream
func google.golang.org/grpc/health.(*Server).Watch(in *healthpb.HealthCheckRequest, stream healthgrpc.Health_WatchServer) error
func google.golang.org/grpc/health/grpc_health_v1.HealthServer[Res].Watch(*grpc_health_v1.HealthCheckRequest, ServerStreamingServer[grpc_health_v1.HealthCheckResponse]) error
func google.golang.org/grpc/health/grpc_health_v1.UnimplementedHealthServer.Watch(*grpc_health_v1.HealthCheckRequest, ServerStreamingServer[grpc_health_v1.HealthCheckResponse]) error
ServerTransportStream is a minimal interface that a transport stream must
implement. This can be used to mock an actual transport stream for tests of
handler code that use, for example, grpc.SetHeader (which requires some
stream to be in context).
See also NewContextWithServerTransportStream.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.( ServerTransportStream) Method() string( ServerTransportStream) SendHeader(md metadata.MD) error( ServerTransportStream) SetHeader(md metadata.MD) error( ServerTransportStream) SetTrailer(md metadata.MD) error
*google.golang.org/grpc/internal/transport.ServerStream
func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream
func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context
ServiceConfig is provided by the service provider and contains parameters for how
clients that connect to the service should behave.
Deprecated: Users should not use this struct. Service config should be received
through name resolver, as specified here
https://github.com/grpc/grpc/blob/master/doc/service_config.mdConfigserviceconfig.Config Methods contains a map for the methods in this service. If there is an
exact match for a method (i.e. /service/method) in the map, use the
corresponding MethodConfig. If there's no exact match, look for the
default config for the service (/service/) and use the corresponding
MethodConfig if it exists. Otherwise, the method has no MethodConfig to
use. healthCheckConfig must be set as one of the requirement to enable LB channel
health check. lbConfig is the service config's load balancing configuration. If
lbConfig and LB are both present, lbConfig will be used. rawJSONString stores service config json string that get parsed into
this service config struct. If a retryThrottlingPolicy is provided, gRPC will automatically throttle
retry attempts and hedged RPCs when the client’s ratio of failures to
successes exceeds a threshold.
For each server name, the gRPC client will maintain a token_count which is
initially set to maxTokens, and can take values between 0 and maxTokens.
Every outgoing RPC (regardless of service or method invoked) will change
token_count as follows:
- Every failed RPC will decrement the token_count by 1.
- Every successful RPC will increment the token_count by tokenRatio.
If token_count is less than or equal to maxTokens / 2, then RPCs will not
be retried and hedged RPCs will not be sent.( ServiceConfig) isServiceConfig()
ServiceConfig : google.golang.org/grpc/serviceconfig.Config
func getMethodConfig(sc *ServiceConfig, method string) MethodConfig
func (*ClientConn).applyServiceConfigAndBalancer(sc *ServiceConfig, configSelector iresolver.ConfigSelector)
var emptyServiceConfig *ServiceConfig
ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service. Metadata is the metadata specified in ServiceDesc when registering service.Methods[]MethodInfo
func (*Server).GetServiceInfo() map[string]ServiceInfo
ServiceRegistrar wraps a single method that supports service registration. It
enables users to pass concrete types other than grpc.Server to the service
registration methods exported by the IDL generated code. RegisterService registers a service and its implementation to the
concrete type implementing this interface. It may not be called
once the server has started serving.
desc describes the service and its methods and handlers. impl is the
service implementation which is passed to the method handlers.
*Server
func google.golang.org/grpc/health/grpc_health_v1.RegisterHealthServer(s ServiceRegistrar, srv grpc_health_v1.HealthServer)
StreamClientInterceptor intercepts the creation of a ClientStream. Stream
interceptors can be specified as a DialOption, using WithStreamInterceptor()
or WithChainStreamInterceptor(), when creating a ClientConn. When a stream
interceptor(s) is set on the ClientConn, gRPC delegates all stream creations
to the interceptor, and it is the responsibility of the interceptor to call
streamer.
desc contains a description of the stream. cc is the ClientConn on which the
RPC was invoked. streamer is the handler to create a ClientStream and it is
the responsibility of the interceptor to call it. opts contain all applicable
call options, including defaults from the ClientConn as well as per-call
options.
StreamClientInterceptor may return a custom ClientStream to intercept all I/O
operations. The returned error must be compatible with the status package.
func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption
func WithStreamInterceptor(f StreamClientInterceptor) DialOption
func getChainStreamer(interceptors []StreamClientInterceptor, curr int, finalStreamer Streamer) Streamer
StreamHandler defines the handler called by gRPC server to complete the
execution of a streaming RPC.
If a StreamHandler returns an error, it should either be produced by the
status package, or be one of the context errors. Otherwise, gRPC will use
codes.Unknown as the status code and err.Error() as the status message of the
RPC.
func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, info *StreamServerInfo, finalHandler StreamHandler) StreamHandler
func UnknownServiceHandler(streamHandler StreamHandler) ServerOption
func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, info *StreamServerInfo, finalHandler StreamHandler) StreamHandler
StreamServerInfo consists of various information about a streaming RPC on
server side. All per-rpc information may be mutated by the interceptor. FullMethod is the full RPC method string, i.e., /package.service/method. IsClientStream indicates whether the RPC is a client streaming RPC. IsServerStream indicates whether the RPC is a server streaming RPC.
func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, info *StreamServerInfo, finalHandler StreamHandler) StreamHandler
StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server.
info contains all the information of this RPC the interceptor can operate on. And handler is the
service method implementation. It is the responsibility of the interceptor to invoke handler to
complete the RPC.
func chainStreamInterceptors(interceptors []StreamServerInterceptor) StreamServerInterceptor
func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption
func StreamInterceptor(i StreamServerInterceptor) ServerOption
func chainStreamInterceptors(interceptors []StreamServerInterceptor) StreamServerInterceptor
func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, info *StreamServerInfo, finalHandler StreamHandler) StreamHandler
TrailerCallOption is a CallOption for collecting response trailer metadata.
The metadata field will be populated *after* the RPC completes.
# Experimental
Notice: This type is EXPERIMENTAL and may be changed or removed in a
later release.TrailerAddr*metadata.MD( TrailerCallOption) after(_ *callInfo, attempt *csAttempt)( TrailerCallOption) before(*callInfo) error
TrailerCallOption : CallOption
UnaryClientInterceptor intercepts the execution of a unary RPC on the client.
Unary interceptors can be specified as a DialOption, using
WithUnaryInterceptor() or WithChainUnaryInterceptor(), when creating a
ClientConn. When a unary interceptor(s) is set on a ClientConn, gRPC
delegates all unary RPC invocations to the interceptor, and it is the
responsibility of the interceptor to call invoker to complete the processing
of the RPC.
method is the RPC name. req and reply are the corresponding request and
response messages. cc is the ClientConn on which the RPC was invoked. invoker
is the handler to complete the RPC and it is the responsibility of the
interceptor to call it. opts contain all applicable call options, including
defaults from the ClientConn as well as per-call options.
The returned error must be compatible with the status package.
func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption
func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption
func getChainUnaryInvoker(interceptors []UnaryClientInterceptor, curr int, finalInvoker UnaryInvoker) UnaryInvoker
UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal
execution of a unary RPC.
If a UnaryHandler returns an error, it should either be produced by the
status package, or be one of the context errors. Otherwise, gRPC will use
codes.Unknown as the status code and err.Error() as the status message of the
RPC.
func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info *UnaryServerInfo, finalHandler UnaryHandler) UnaryHandler
func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info *UnaryServerInfo, finalHandler UnaryHandler) UnaryHandler
UnaryServerInfo consists of various information about a unary RPC on
server side. All per-rpc information may be mutated by the interceptor. FullMethod is the full RPC method string, i.e., /package.service/method. Server is the service implementation the user provides. This is read-only.
func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info *UnaryServerInfo, finalHandler UnaryHandler) UnaryHandler
UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info
contains all the information of this RPC the interceptor can operate on. And handler is the wrapper
of the service method implementation. It is the responsibility of the interceptor to invoke handler
to complete the RPC.
func chainUnaryInterceptors(interceptors []UnaryServerInterceptor) UnaryServerInterceptor
func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption
func UnaryInterceptor(i UnaryServerInterceptor) ServerOption
func chainUnaryInterceptors(interceptors []UnaryServerInterceptor) UnaryServerInterceptor
func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info *UnaryServerInfo, finalHandler UnaryHandler) UnaryHandler
func google.golang.org/grpc/health/grpc_health_v1._Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error)
func google.golang.org/grpc/health/grpc_health_v1._Health_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error)
acBalancerWrapper is a wrapper on top of ac for balancers.
It implements balancer.SubConn interface.EnforceSubConnEmbeddinginternal.EnforceSubConnEmbedding // read-only // read-only healthData is stored as a pointer to detect when the health listener is
dropped or updated. This is required as closures can't be compared for
equality. Access to healthData is protected by healthMu.producersmap[balancer.ProducerBuilder]*refCountedProducerproducersMusync.MutexstateListenerfunc(balancer.SubConnState)(*acBalancerWrapper) Connect()(*acBalancerWrapper) GetOrBuildProducer(pb balancer.ProducerBuilder) (balancer.Producer, func()) Invoke performs a unary RPC. If the addrConn is not ready, returns
errSubConnNotReady. NewStream begins a streaming RPC on the addrConn. If the addrConn is not
ready, blocks until it is or ctx expires. Returns an error when the context
expires or the addrConn is shut down. RegisterHealthListener accepts a health listener from the LB policy. It sends
updates to the health listener as long as the SubConn's connectivity state
doesn't change and a new health listener is not registered. To invalidate
the currently registered health listener, acbw updates the healthData. If a
nil listener is registered, the active health listener is dropped.(*acBalancerWrapper) Shutdown()(*acBalancerWrapper) String() string(*acBalancerWrapper) UpdateAddresses(addrs []resolver.Address)(*acBalancerWrapper) closeProducers()( acBalancerWrapper) enforceSubConnEmbedding() healthListenerRegFn returns a function to register a listener for health
updates. If client side health checks are disabled, the registered listener
will get a single READY (raw connectivity state) update.
Client side health checking is enabled when all the following
conditions are satisfied:
1. Health checking is not disabled using the dial option.
2. The health package is imported.
3. The health check config is present in the service config. updateState is invoked by grpc to push a subConn state update to the
underlying balancer.
*acBalancerWrapper : ClientConnInterface
*acBalancerWrapper : google.golang.org/grpc/balancer.SubConn
acBalancerWrapper : google.golang.org/grpc/internal.EnforceSubConnEmbedding
*acBalancerWrapper : expvar.Var
*acBalancerWrapper : fmt.Stringer
*acBalancerWrapper : context.stringer
*acBalancerWrapper : runtime.stringer
func doneChannelzWrapper(acbw *acBalancerWrapper, result *balancer.PickResult)
addrConn is a network connection to a given address.acbw*acBalancerWrapper // All addresses that the resolver resolved to. // Needs to be stateful for resetConnectBackoff.cancelcontext.CancelFunccc*ClientConnchannelz*channelz.SubChannelctxcontext.Context // The current address.doptsdialOptions This mutex is used on the RPC path, so its usage should be minimized as
much as possible.
TODO: Find a lock-free way to retrieve the transport and state from the
addrConn.resetBackoffchan struct{}scoptsbalancer.NewSubConnOptions Use updateConnectivityState for updating addrConn's connectivity state. transport is set when there's a viable transport (note: ac state may not be READY as LB channel
health checking may require server to report healthy to set ac to READY), and is reset
to nil when the current transport should no longer be used to create a stream (e.g. after GoAway
is received, transport is closed, ac has been torn down). // The current transport. adjustParams updates parameters used to create transports upon
receiving a GoAway. connect starts creating a transport.
It does nothing if the ac is not IDLE.
TODO(bar) Move this to the addrConn section. createTransport creates a connection to addr. It returns an error if the
address was not successfully connected, or updates ac appropriately with the
new transport. getReadyTransport returns the transport if ac's state is READY or nil if not.(*addrConn) incrCallsFailed()(*addrConn) incrCallsStarted()(*addrConn) incrCallsSucceeded()(*addrConn) resetConnectBackoff() resetTransportAndUnlock unconditionally connects the addrConn.
ac.mu must be held by the caller, and this function will guarantee it is released. startHealthCheck starts the health checking stream (RPC) to watch the health
stats of this connection if health checking is requested and configured.
LB channel health checking is enabled when all requirements below are met:
1. it is not disabled by the user with the WithDisableHealthCheck DialOption
2. internal.HealthCheckFunc is set by importing the grpc/health package
3. a service config with non-empty healthCheckConfig field is provided
4. the load balancer requests it
It sets addrConn to READY if the health checking stream is not started.
Caller must hold ac.mu. tearDown starts to tear down the addrConn.
Note that tearDown doesn't remove ac from ac.cc.conns, so the addrConn struct
will leak. In most cases, call cc.removeAddrConn() instead. tryAllAddrs tries to create a connection to the addresses, and stop when at
the first successful one. It returns an error if no address was successfully
connected, or updates ac appropriately with the new transport. updateAddrs updates ac.addrs with the new addresses list and handles active
connections or connection attempts. Note: this requires a lock on ac.mu.
func (*ClientConn).newAddrConnLocked(addrs []resolver.Address, opts balancer.NewSubConnOptions) (*addrConn, error)
func newNonRetryClientStream(ctx context.Context, desc *StreamDesc, method string, t transport.ClientTransport, ac *addrConn, opts ...CallOption) (_ ClientStream, err error)
func (*ClientConn).removeAddrConn(ac *addrConn, err error)
atomicSemaphore implements a blocking, counting semaphore. acquire should be
called synchronously; release may be called asynchronously.natomic.Int64waitchan struct{}(*atomicSemaphore) acquire()(*atomicSemaphore) release()
func newHandlerQuota(n uint32) *atomicSemaphore
ccBalancerWrapper sits between the ClientConn and the Balancer.
ccBalancerWrapper implements methods corresponding to the ones on the
balancer.Balancer interface. The ClientConn is free to call these methods
concurrently and the ccBalancerWrapper ensures that calls from the ClientConn
to the Balancer happen in order by performing them in the serializer, without
any mutexes held.
ccBalancerWrapper also implements the balancer.ClientConn interface and is
passed to the Balancer implementations. It invokes unexported methods on the
ClientConn to handle these calls from the Balancer.
It uses the gracefulswitch.Balancer internally to ensure that balancer
switches happen in a graceful manner.EnforceClientConnEmbeddinginternal.EnforceClientConnEmbeddingbalancer*gracefulswitch.Balancer The following fields are initialized when the wrapper is created and are
read-only afterwards, and therefore can be accessed without a mutex.closedbool The following fields are only accessed within the serializer or during
initialization. The following field is protected by mu. Caller must take cc.mu before
taking mu.optsbalancer.BuildOptionsserializer*grpcsync.CallbackSerializerserializerCancelcontext.CancelFunc(*ccBalancerWrapper) MetricsRecorder() stats.MetricsRecorder(*ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error)(*ccBalancerWrapper) RemoveSubConn(balancer.SubConn)(*ccBalancerWrapper) ResolveNow(o resolver.ResolveNowOptions)(*ccBalancerWrapper) Target() string(*ccBalancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address)(*ccBalancerWrapper) UpdateState(s balancer.State) close initiates async shutdown of the wrapper. cc.mu must be held when
calling this function. To determine the wrapper has finished shutting down,
the channel should block on ccb.serializer.Done() without cc.mu held.( ccBalancerWrapper) enforceClientConnEmbedding() exitIdle invokes the balancer's exitIdle method in the serializer. resolverError is invoked by grpc to push a resolver error to the underlying
balancer. The call to the balancer is executed from the serializer. updateClientConnState is invoked by grpc to push a ClientConnState update to
the underlying balancer. This is always executed from the serializer, so
it is safe to call into the balancer here.
*ccBalancerWrapper : google.golang.org/grpc/balancer.ClientConn
ccBalancerWrapper : google.golang.org/grpc/internal.EnforceClientConnEmbedding
func newCCBalancerWrapper(cc *ClientConn) *ccBalancerWrapper
ccResolverWrapper is a wrapper on top of cc for resolvers.
It implements resolver.ClientConn interface. The following fields are initialized when the wrapper is created and are
read-only afterwards, and therefore can be accessed without a mutex.closedboolcurStateresolver.StateignoreServiceConfigbool The following fields are protected by mu. Caller must take cc.mu before
taking mu. // only accessed within the serializerserializer*grpcsync.CallbackSerializerserializerCancelcontext.CancelFunc NewAddress is called by the resolver implementation to send addresses to
gRPC. ParseServiceConfig is called by resolver implementations to parse a JSON
representation of the service config. ReportError is called by resolver implementations to report errors
encountered during name resolution to gRPC. UpdateState is called by resolver implementations to report new state to gRPC
which includes addresses and service config. addChannelzTraceEvent adds a channelz trace event containing the new
state received from resolver implementations. close initiates async shutdown of the wrapper. To determine the wrapper has
finished shutting down, the channel should block on ccr.serializer.Done()
without cc.mu held.(*ccResolverWrapper) resolveNow(o resolver.ResolveNowOptions) start builds the name resolver using the resolver.Builder in cc and returns
any error encountered. It must always be the first operation performed on
any newly created ccResolverWrapper, except that close may be called instead.
*ccResolverWrapper : google.golang.org/grpc/resolver.ClientConn
func newCCResolverWrapper(cc *ClientConn) *ccResolverWrapper
clientStream implements a client side Stream. attempt is the active client stream attempt.
The only place where it is written is the newAttemptLocked method and this method never writes nil.
So, attempt can be nil only inside newClientStream function when clientStream is first created.
One of the first things done after clientStream's creation, is to call newAttemptLocked which either
assigns a non nil value to the attempt or returns an error. If an error is returned from newAttemptLocked,
then newClientStream calls finish on the clientStream and returns. So, finish method is the only
place where we need to check if the attempt is nil.binlogs[]binarylog.MethodLoggercallHdr*transport.CallHdrcallInfo*callInfo // cancels all attemptscc*ClientConncodecbaseCodec TODO(hedging): hedging will have multiple attempts simultaneously. // active attempt committed for retry?compressorV0CompressorcompressorV1encoding.Compressor // the application's context, wrapped by stats/tracingdesc*StreamDesc // TODO: replace with atomic cmpxchg or sync.Once? // if true, transparent retry is validmethodConfig*MethodConfigmusync.Mutex nameResolutionDelay indicates if there was a delay in the name resolution.
This field is only valid on client side, it's always false on server side. // exclusive of transparent retry attempt(s) // retries since pushback; to reset backoffonCommitfunc()opts[]CallOption // operations to replay on retry // current size of replayBuffer // The throttler active when the RPC began. // sent an end stream serverHeaderBinlogged is a boolean for whether server header has been
logged. Server header will be logged when the first time one of those
happens: stream.Header(), stream.Recv().
It's only read and used by Recv() and Header(), so it doesn't need to be
synchronized.(*clientStream) CloseSend() error(*clientStream) Context() context.Context(*clientStream) Header() (metadata.MD, error)(*clientStream) RecvMsg(m any) error(*clientStream) SendMsg(m any) (err error)(*clientStream) Trailer() metadata.MD(*clientStream) bufferForRetryLocked(sz int, op func(a *csAttempt) error, cleanup func())(*clientStream) commitAttempt()(*clientStream) commitAttemptLocked()(*clientStream) finish(err error) newAttemptLocked creates a new csAttempt without a transport or stream.(*clientStream) replayBufferLocked(attempt *csAttempt) error Returns nil if a retry was performed and succeeded; error otherwise.(*clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) error
*clientStream : ClientStream[grpc_health_v1.HealthCheckResponse]
*clientStream : Stream
*clientStream : google.golang.org/grpc/internal/resolver.ClientStream
Information about Preloader
Responsible for storing codec, and compressors
If stream (s) has context s.Context which stores rpcInfo that has non nil
pointers to codec, and compressors, then we can use preparedMsg for Async message prep
and reuse marshalled bytescodecbaseCodeccompencoding.CompressorcpCompressor
connectivityStateManager keeps the connectivity.State of ClientConn.
This struct will eventually be exported so the balancers can access it.
TODO: If possible, get rid of the `connectivityStateManager` type, and
provide this functionality using the `PubSub`, to avoid keeping track of
the connectivity state at two places.channelz*channelz.Channelmusync.MutexnotifyChanchan struct{}pubSub*grpcsync.PubSubstateconnectivity.State(*connectivityStateManager) getNotifyChan() <-chan struct{}(*connectivityStateManager) getState() connectivity.State updateState updates the connectivity.State of ClientConn.
If there's a change it notifies goroutines waiting on state change to
happen.
func newConnectivityStateManager(ctx context.Context, channel *channelz.Channel) *connectivityStateManager
dropError is a wrapper error that indicates the LB policy wishes to drop the
RPC and not retry it.errorerror( dropError) Error() builtin.string
dropError : error
firstLine is the first line of an RPC trace.
It may be mutated after construction; remoteAddr specifically may change
during client-side use. // whether this is a client (outgoing) RPC // may be zeromusync.MutexremoteAddrnet.Addr(*firstLine) SetRemoteAddr(addr net.Addr)(*firstLine) String() string
*firstLine : expvar.Var
*firstLine : fmt.Stringer
*firstLine : context.stringer
*firstLine : runtime.stringer
healthCheckConfig defines the go-native version of the LB channel health check config. serviceName is the service name to use in the health-checking request.
func (*ClientConn).healthCheckConfig() *healthCheckConfig
healthData holds data related to health state reporting. closeHealthProducer stores function to close the ref counted health
producer. The health producer is automatically closed when the SubConn
state changes. connectivityState stores the most recent connectivity state delivered
to the LB policy. This is stored to avoid sending updates when the
SubConn has already exited connectivity state READY.
func newHealthData(s connectivity.State) *healthData
healthProducerRegisterFn is a type alias for the health producer's function
for registering listeners.
// See initAuthority(). // Always recreated whenever entering idle to simplify Close. // Cancelled on close. // Channelz object. // Set to nil on close. The following provide their own synchronization, and therefore don't
require cc.mu to be held to access them. // Initialized using the background context at dial time. // Default and user specified dial options. firstResolveEvent is used to track whether the name resolver sent us at
least one update. RPCs block on this event. May be accessed without mu
if we know we cannot be asked to enter idle mode while accessing it (e.g.
when the idle manager has already been closed, or if we are already
entering idle mode).idlenessMgr*idle.Manager // May be updated upon receipt of a GoAway.lastConnectionErrorerror // protects lastConnectionErrormetricsRecorderList*stats.MetricsRecorderList mu protects the following fields.
TODO: split mu so the same mutex isn't used for everything. // See initParsedTargetAndResolverBuilder().pickerWrapper*pickerWrapper // See initParsedTargetAndResolverBuilder(). // Always recreated whenever entering idle to simplify Close. // Updated from service config.safeConfigSelectoriresolver.SafeConfigSelector // Latest service config received from the resolver. The following are initialized at dial time, and are read-only after that. // User's dial target.(*idler) EnterIdleMode()(*idler) ExitIdleMode() error
*idler : google.golang.org/grpc/internal/idle.Enforcer
parser reads complete gRPC messages from the underlying reader. bufferPool is the pool of shared receive buffers. The header of a gRPC message. Find more detail at
https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md r is the underlying reader.
See the comment on recvMsg for the permissible
error types. recvMsg reads a complete gRPC message from the stream.
It returns the message and its payload (compression/encoding)
format. The caller owns the returned msg memory.
If there is an error, possible values are:
- io.EOF, when no messages remain
- io.ErrUnexpectedEOF
- of type transport.ConnectionError
- an error from the status package
No other error values or types must be returned, which also means
that the underlying streamReader must not return an incompatible
error.
func recv(p *parser, c baseCodec, s recvCompressor, dc Decompressor, m any, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor, isServer bool) error
func recvAndDecompress(p *parser, s recvCompressor, dc Decompressor, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor, isServer bool) (out mem.BufferSlice, err error)
payload represents an RPC request or response payload. // e.g. a proto.Message // whether this is an outgoing payload( payload) String() string
payload : expvar.Var
payload : fmt.Stringer
payload : context.stringer
payload : runtime.stringer
perTargetDialOption takes a parsed target and returns a dial option to apply.
This gets called after NewClient() parses the target, and allows per target
configuration set through a returned DialOption. The DialOption will not take
effect if specifies a resolver builder, as that Dial Option is factored in
while parsing target. DialOption returns a Dial Option to apply.
// set if a picker call queued for a new picker // the contents of the pick from the LB policy // the selected transport
pickerGeneration stores a picker and a channel used to signal that a picker
newer than this one is available. blockingCh is closed when the picker has been invalidated because there
is a new one available. picker is the picker produced by the LB policy. May be nil if a picker
has never been produced.
pickerWrapper is a wrapper of balancer.Picker. It blocks on certain pick
actions and unblock when there's a picker update. If pickerGen holds a nil pointer, the pickerWrapper is closed.(*pickerWrapper) close() pick returns the transport that will be used for the RPC.
It may block in the following cases:
- there's no picker
- the current picker returns ErrNoSubConnAvailable
- the current picker returns other errors and failfast is false.
- the subConn returned by the current picker is not READY
When one of these situations happens, pick blocks until the picker gets updated. reset clears the pickerWrapper and prepares it for being used again when idle
mode is exited. updatePicker is called by UpdateState calls from the LB policy. It
unblocks all blocked pick.
func newPickerWrapper() *pickerWrapper
maxfloat64musync.Mutexratiofloat64threshfloat64 // TODO(dfawley): replace with atomic and remove lock.(*retryThrottler) successfulRPC() throttle subtracts a retry token from the pool and returns whether a retry
should be throttled (disallowed) based upon the retry throttling policy in
the service config.
retryThrottlingPolicy defines the go-native version of the retry throttling
policy defined by the service config here:
https://github.com/grpc/proposal/blob/master/A6-client-retries.md#integration-with-service-config The number of tokens starts at maxTokens. The token_count will always be
between 0 and maxTokens.
This field is required and must be greater than zero. The amount of tokens to add on each successful RPC. Typically this will
be some number between 0 and 1, e.g., 0.1.
This field is required and must be greater than zero. Up to 3 decimal
places are supported.
traceEventLog mirrors golang.org/x/net/trace.EventLog.
It exists in order to avoid importing x/net/trace on grpcnotrace builds. Errorf is like Printf, but it marks this event as an error. Finish declares that this event log is complete.
The event log should not be used after calling this method. Printf formats its arguments with fmt.Sprintf and adds the
result to the event log.
golang.org/x/net/trace.EventLog(interface)
*golang.org/x/net/trace.eventLog
traceEventLog : golang.org/x/net/trace.EventLog
func newTraceEventLog(family, title string) traceEventLog
traceLog mirrors golang.org/x/net/trace.Trace.
It exists in order to avoid importing x/net/trace on grpcnotrace builds. Finish declares that this trace is complete.
The trace should not be used after calling this method. LazyLog adds x to the event log. It will be evaluated each time the
/debug/requests page is rendered. Any memory referenced by x will be
pinned until the trace is finished and later discarded. LazyPrintf evaluates its arguments with fmt.Sprintf each time the
/debug/requests page is rendered. Any memory referenced by a will be
pinned until the trace is finished and later discarded. SetError declares that this trace resulted in an error. SetMaxEvents sets the maximum number of events that will be stored
in the trace. This has no effect if any events have already been
added to the trace. SetRecycler sets a recycler for the trace.
f will be called for each event passed to LazyLog at a time when
it is no longer required, whether while the trace is still active
and the event is discarded, or when a completed trace is discarded. SetTraceInfo sets the trace info for the trace.
This is currently unused.
golang.org/x/net/trace.Trace(interface)
*golang.org/x/net/trace.trace
traceLog : golang.org/x/net/trace.Trace
func newTrace(family, title string) traceLog
func newTraceContext(ctx context.Context, tr traceLog) context.Context
Package-Level Functions (total 192, in which 113 are exported)
CallAuthority returns a CallOption that sets the HTTP/2 :authority header of
an RPC to the specified value. When using CallAuthority, the credentials in
use must implement the AuthorityValidator interface.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a later
release.
CallContentSubtype returns a CallOption that will set the content-subtype
for a call. For example, if content-subtype is "json", the Content-Type over
the wire will be "application/grpc+json". The content-subtype is converted
to lowercase before being included in Content-Type. See Content-Type on
https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
more details.
If ForceCodec is not also used, the content-subtype will be used to look up
the Codec to use in the registry controlled by RegisterCodec. See the
documentation on RegisterCodec for details on registration. The lookup of
content-subtype is case-insensitive. If no such Codec is found, the call
will result in an error with code codes.Internal.
If ForceCodec is also used, that Codec will be used for all request and
response messages, with the content-subtype set to the given contentSubtype
here for requests.
CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of
an encoding.Codec.
Deprecated: use ForceCodec instead.
ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor
for streaming RPCs. The first interceptor will be the outer most,
while the last interceptor will be the inner most wrapper around the real call.
All stream interceptors added by this method will be chained.
ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor
for unary RPCs. The first interceptor will be the outer most,
while the last interceptor will be the inner most wrapper around the real call.
All unary interceptors added by this method will be chained.
ClientSupportedCompressors returns compressor names advertised by the client
via grpc-accept-encoding header.
The context provided must be the context passed to the server's handler.
# Experimental
Notice: This function is EXPERIMENTAL and may be changed or removed in a
later release.
Code returns the error code for err if it was produced by the rpc system.
Otherwise, it returns codes.Unknown.
Deprecated: use status.Code instead.
ConnectionTimeout returns a ServerOption that sets the timeout for
connection establishment (up to and including HTTP/2 handshaking) for all
new connections. If this is not set, the default is 120 seconds. A zero or
negative value will result in an immediate timeout.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
Creds returns a ServerOption that sets credentials for server connections.
CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
This will override any lookups by content-subtype for Codecs registered with RegisterCodec.
Deprecated: register codecs using encoding.RegisterCodec. The server will
automatically use registered codecs based on the incoming requests' headers.
See also
https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec.
Will be supported throughout 1.x.
Dial calls DialContext(context.Background(), target, opts...).
Deprecated: use NewClient instead. Will be supported throughout 1.x.
DialContext calls NewClient and then exits idle mode. If WithBlock(true) is
used, it calls Connect and WaitForStateChange until either the context
expires or the state of the ClientConn is Ready.
One subtle difference between NewClient and Dial and DialContext is that the
former uses "dns" as the default name resolver, while the latter use
"passthrough" for backward compatibility. This distinction should not matter
to most users, but could matter to legacy users that specify a custom dialer
and expect it to receive the target string directly.
Deprecated: use NewClient instead. Will be supported throughout 1.x.
ErrorDesc returns the error description of err if it was produced by the rpc system.
Otherwise, it returns err.Error() or empty string when err is nil.
Deprecated: use status.Convert and Message method instead.
Errorf returns an error containing an error code and a description;
Errorf returns nil if c is OK.
Deprecated: use status.Errorf instead.
FailFast is the opposite of WaitForReady.
Deprecated: use WaitForReady.
FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on
non-temporary dial errors. If f is true, and dialer returns a non-temporary
error, gRPC will fail the connection to the network address and won't try to
reconnect. The default value of FailOnNonTempDialError is false.
FailOnNonTempDialError only affects the initial dial, and does not do
anything useful unless you are also using WithBlock().
Use of this feature is not recommended. For more information, please see:
https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md
Deprecated: this DialOption is not supported by NewClient.
This API may be changed or removed in a
later release.
ForceCodec returns a CallOption that will set codec to be used for all
request and response messages for a call. The result of calling Name() will
be used as the content-subtype after converting to lowercase, unless
CallContentSubtype is also used.
See Content-Type on
https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
more details. Also see the documentation on RegisterCodec and
CallContentSubtype for more details on the interaction between Codec and
content-subtype.
This function is provided for advanced users; prefer to use only
CallContentSubtype to select a registered codec instead.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
ForceCodecV2 returns a CallOption that will set codec to be used for all
request and response messages for a call. The result of calling Name() will
be used as the content-subtype after converting to lowercase, unless
CallContentSubtype is also used.
See Content-Type on
https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
more details. Also see the documentation on RegisterCodec and
CallContentSubtype for more details on the interaction between Codec and
content-subtype.
This function is provided for advanced users; prefer to use only
CallContentSubtype to select a registered codec instead.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
ForceServerCodec returns a ServerOption that sets a codec for message
marshaling and unmarshaling.
This will override any lookups by content-subtype for Codecs registered
with RegisterCodec.
See Content-Type on
https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
more details. Also see the documentation on RegisterCodec and
CallContentSubtype for more details on the interaction between encoding.Codec
and content-subtype.
This function is provided for advanced users; prefer to register codecs
using encoding.RegisterCodec.
The server will automatically use registered codecs based on the incoming
requests' headers. See also
https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec.
Will be supported throughout 1.x.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
ForceServerCodecV2 is the equivalent of ForceServerCodec, but for the new
CodecV2 interface.
Will be supported throughout 1.x.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
Header returns a CallOptions that retrieves the header metadata
for a unary RPC.
HeaderTableSize returns a ServerOption that sets the size of dynamic
header table for stream.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
InitialConnWindowSize returns a ServerOption that sets window size for a connection.
The lower bound for window size is 64K and any value smaller than that will be ignored.
InitialWindowSize returns a ServerOption that sets window size for stream.
The lower bound for window size is 64K and any value smaller than that will be ignored.
InTapHandle returns a ServerOption that sets the tap handle for all the server
transport to be created. Only one can be installed.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
Invoke sends the RPC request on the wire and returns after response is
received. This is typically called by generated code.
DEPRECATED: Use ClientConn.Invoke instead.
KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server.
KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.
MaxCallRecvMsgSize returns a CallOption which sets the maximum message size
in bytes the client can receive. If this is not set, gRPC uses the default
4MB.
MaxCallSendMsgSize returns a CallOption which sets the maximum message size
in bytes the client can send. If this is not set, gRPC uses the default
`math.MaxInt32`.
MaxConcurrentStreams returns a ServerOption that will apply a limit on the number
of concurrent streams to each ServerTransport.
MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size
of header list that the server is prepared to accept.
MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
If this is not set, gRPC uses the default limit.
Deprecated: use MaxRecvMsgSize instead. Will be supported throughout 1.x.
MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
If this is not set, gRPC uses the default 4MB.
MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory
used for buffering this RPC's requests for retry purposes.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send.
If this is not set, gRPC uses the default `math.MaxInt32`.
Method returns the method string for the server context. The returned
string is in the format of "/service/method".
MethodFromServerStream returns the method string for the input stream.
The returned string is in the format of "/service/method".
NewClient creates a new gRPC "channel" for the target URI provided. No I/O
is performed. Use of the ClientConn for RPCs will automatically cause it to
connect. The Connect method may be called to manually create a connection,
but for most users this should be unnecessary.
The target name syntax is defined in
https://github.com/grpc/grpc/blob/master/doc/naming.md. E.g. to use the dns
name resolver, a "dns:///" prefix may be applied to the target. The default
name resolver will be used if no scheme is detected, or if the parsed scheme
is not a registered name resolver. The default resolver is "dns" but can be
overridden using the resolver package's SetDefaultScheme.
Examples:
- "foo.googleapis.com:8080"
- "dns:///foo.googleapis.com:8080"
- "dns:///foo.googleapis.com"
- "dns:///10.0.0.213:8080"
- "dns:///%5B2001:db8:85a3:8d3:1319:8a2e:370:7348%5D:443"
- "dns://8.8.8.8/foo.googleapis.com:8080"
- "dns://8.8.8.8/foo.googleapis.com"
- "zookeeper://zk.example.com:9900/example_service"
The DialOptions returned by WithBlock, WithTimeout,
WithReturnConnectionError, and FailOnNonTempDialError are ignored by this
function.
NewClientStream is a wrapper for ClientConn.NewStream.
NewContextWithServerTransportStream creates a new context from ctx and
attaches stream to it.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
NewGZIPCompressor creates a Compressor based on GZIP.
Deprecated: use package encoding/gzip.
NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead
of assuming DefaultCompression.
The error returned will be nil if the level is valid.
Deprecated: use package encoding/gzip.
NewGZIPDecompressor creates a Decompressor based on GZIP.
Deprecated: use package encoding/gzip.
NewServer creates a gRPC server which has no service registered and has not
started to accept requests yet.
NumStreamWorkers returns a ServerOption that sets the number of worker
goroutines that should be used to process incoming streams. Setting this to
zero (default) will disable workers and spawn a new goroutine for each
stream.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
OnFinish returns a CallOption that configures a callback to be called when
the call completes. The error passed to the callback is the status of the
RPC, and may be nil. The onFinish callback provided will only be called once
by gRPC. This is mainly used to be used by streaming interceptors, to be
notified when the RPC completes along with information about the status of
the RPC.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
Peer returns a CallOption that retrieves peer information for a unary RPC.
The peer field will be populated *after* the RPC completes.
PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials
for a call.
ReadBufferSize lets you set the size of read buffer, this determines how much
data can be read at most for one read syscall. The default value for this
buffer is 32KB. Zero or negative values will disable read buffer for a
connection so data framer can access the underlying conn directly.
RPCCompressor returns a ServerOption that sets a compressor for outbound
messages. For backward compatibility, all outbound messages will be sent
using this compressor, regardless of incoming message compression. By
default, server messages will be sent using the same compressor with which
request messages were sent.
Deprecated: use encoding.RegisterCompressor instead. Will be supported
throughout 1.x.
RPCDecompressor returns a ServerOption that sets a decompressor for inbound
messages. It has higher priority than decompressors registered via
encoding.RegisterCompressor.
Deprecated: use encoding.RegisterCompressor instead. Will be supported
throughout 1.x.
SendHeader sends header metadata. It may be called at most once, and may not
be called after any event that causes headers to be sent (see SetHeader for
a complete list). The provided md and headers set by SetHeader() will be
sent.
The error returned is compatible with the status package. However, the
status code will often not match the RPC status as seen by the client
application, and therefore, should not be relied upon for this purpose.
ServerTransportStreamFromContext returns the ServerTransportStream saved in
ctx. Returns nil if the given context has no stream associated with it
(which implies it is not an RPC invocation context).
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
SetHeader sets the header metadata to be sent from the server to the client.
The context provided must be the context passed to the server's handler.
Streaming RPCs should prefer the SetHeader method of the ServerStream.
When called multiple times, all the provided metadata will be merged. All
the metadata will be sent out when one of the following happens:
- grpc.SendHeader is called, or for streaming handlers, stream.SendHeader.
- The first response message is sent. For unary handlers, this occurs when
the handler returns; for streaming handlers, this can happen when stream's
SendMsg method is called.
- An RPC status is sent out (error or success). This occurs when the handler
returns.
SetHeader will fail if called after any of the events above.
The error returned is compatible with the status package. However, the
status code will often not match the RPC status as seen by the client
application, and therefore, should not be relied upon for this purpose.
SetSendCompressor sets a compressor for outbound messages from the server.
It must not be called after any event that causes headers to be sent
(see ServerStream.SetHeader for the complete list). Provided compressor is
used when below conditions are met:
- compressor is registered via encoding.RegisterCompressor
- compressor name must exist in the client advertised compressor names
sent in grpc-accept-encoding header. Use ClientSupportedCompressors to
get client supported compressor names.
The context provided must be the context passed to the server's handler.
It must be noted that compressor name encoding.Identity disables the
outbound compression.
By default, server messages will be sent using the same compressor with
which request messages were sent.
It is not safe to call SetSendCompressor concurrently with SendHeader and
SendMsg.
# Experimental
Notice: This function is EXPERIMENTAL and may be changed or removed in a
later release.
SetTrailer sets the trailer metadata that will be sent when an RPC returns.
When called more than once, all the provided metadata will be merged.
The error returned is compatible with the status package. However, the
status code will often not match the RPC status as seen by the client
application, and therefore, should not be relied upon for this purpose.
SharedWriteBuffer allows reusing per-connection transport write buffer.
If this option is set to true every connection will release the buffer after
flushing the data on the wire.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
StaticConnWindowSize returns a ServerOption to set the initial connection
window size to the value provided and disables dynamic flow control.
The lower bound for window size is 64K and any value smaller than that
will be ignored.
StaticMethod returns a CallOption which specifies that a call is being made
to a method that is static, which means the method is known at compile time
and doesn't change at runtime. This can be used as a signal to stats plugins
that this method is safe to include as a key to a measurement.
StaticStreamWindowSize returns a ServerOption to set the initial stream
window size to the value provided and disables dynamic flow control.
The lower bound for window size is 64K and any value smaller than that
will be ignored.
StatsHandler returns a ServerOption that sets the stats handler for the server.
StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the
server. Only one stream interceptor can be installed.
Trailer returns a CallOptions that retrieves the trailer metadata
for a unary RPC.
UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the
server. Only one unary interceptor can be installed. The construction of multiple
interceptors (e.g., chaining) can be implemented at the caller.
UnknownServiceHandler returns a ServerOption that allows for adding a custom
unknown service handler. The provided method is a bidi-streaming RPC service
handler that will be invoked instead of returning the "unimplemented" gRPC
error whenever a request is received for an unregistered service or method.
The handling function and stream interceptor (if set) have full access to
the ServerStream, including its Context.
UseCompressor returns a CallOption which sets the compressor used when
sending the request. If WithCompressor is also set, UseCompressor has
higher priority.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WaitForHandlers cause Stop to wait until all outstanding method handlers have
exited before returning. If false, Stop will return as soon as all
connections have closed, but method handlers may still be running. By
default, Stop does not wait for method handlers to return.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WaitForReady configures the RPC's behavior when the client is in
TRANSIENT_FAILURE, which occurs when all addresses fail to connect. If
waitForReady is false, the RPC will fail immediately. Otherwise, the client
will wait until a connection becomes available or the RPC's deadline is
reached.
By default, RPCs do not "wait for ready".
WithAuthority returns a DialOption that specifies the value to be used as the
:authority pseudo-header and as the server name in authentication handshake.
This overrides all other ways of setting authority on the channel, but can be
overridden per-call by using grpc.CallAuthority.
WithBackoffConfig configures the dialer to use the provided backoff
parameters after connection failures.
Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.
WithBackoffMaxDelay configures the dialer to use the provided maximum delay
when backing off after failed connection attempts.
Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.
WithBlock returns a DialOption which makes callers of Dial block until the
underlying connection is up. Without this, Dial returns immediately and
connecting the server happens in background.
Use of this feature is not recommended. For more information, please see:
https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md
Deprecated: this DialOption is not supported by NewClient.
Will be supported throughout 1.x.
WithChainStreamInterceptor returns a DialOption that specifies the chained
interceptor for streaming RPCs. The first interceptor will be the outer most,
while the last interceptor will be the inner most wrapper around the real call.
All interceptors added by this method will be chained, and the interceptor
defined by WithStreamInterceptor will always be prepended to the chain.
WithChainUnaryInterceptor returns a DialOption that specifies the chained
interceptor for unary RPCs. The first interceptor will be the outer most,
while the last interceptor will be the inner most wrapper around the real call.
All interceptors added by this method will be chained, and the interceptor
defined by WithUnaryInterceptor will always be prepended to the chain.
WithChannelzParentID returns a DialOption that specifies the channelz ID of
current ClientConn's parent. This function is used in nested channel creation
(e.g. grpclb dial).
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WithCodec returns a DialOption which sets a codec for message marshaling and
unmarshaling.
Deprecated: use WithDefaultCallOptions(ForceCodec(_)) instead. Will be
supported throughout 1.x.
WithCompressor returns a DialOption which sets a Compressor to use for
message compression. It has lower priority than the compressor set by the
UseCompressor CallOption.
Deprecated: use UseCompressor instead. Will be supported throughout 1.x.
WithConnectParams configures the ClientConn to use the provided ConnectParams
for creating and maintaining connections to servers.
The backoff configuration specified as part of the ConnectParams overrides
all defaults specified in
https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Consider
using the backoff.DefaultConfig as a base, in cases where you want to
override only a subset of the backoff configuration.
WithContextDialer returns a DialOption that sets a dialer to create
connections. If FailOnNonTempDialError() is set to true, and an error is
returned by f, gRPC checks the error's Temporary() method to decide if it
should try to reconnect to the network address.
Note that gRPC by default performs name resolution on the target passed to
NewClient. To bypass name resolution and cause the target string to be
passed directly to the dialer here instead, use the "passthrough" resolver
by specifying it in the target string, e.g. "passthrough:target".
Note: All supported releases of Go (as of December 2023) override the OS
defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive
with OS defaults for keepalive time and interval, use a net.Dialer that sets
the KeepAlive field to a negative value, and sets the SO_KEEPALIVE socket
option to true from the Control field. For a concrete example of how to do
this, see internal.NetDialerWithTCPKeepalive().
For more information, please see [issue 23459] in the Go GitHub repo.
[issue 23459]: https://github.com/golang/go/issues/23459
WithCredentialsBundle returns a DialOption to set a credentials bundle for
the ClientConn.WithCreds. This should not be used together with
WithTransportCredentials.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WithDecompressor returns a DialOption which sets a Decompressor to use for
incoming message decompression. If incoming response messages are encoded
using the decompressor's Type(), it will be used. Otherwise, the message
encoding will be used to look up the compressor registered via
encoding.RegisterCompressor, which will then be used to decompress the
message. If no compressor is registered for the encoding, an Unimplemented
status error will be returned.
Deprecated: use encoding.RegisterCompressor instead. Will be supported
throughout 1.x.
WithDefaultCallOptions returns a DialOption which sets the default
CallOptions for calls over the connection.
WithDefaultServiceConfig returns a DialOption that configures the default
service config, which will be used in cases where:
1. WithDisableServiceConfig is also used, or
2. The name resolver does not provide a service config or provides an
invalid service config.
The parameter s is the JSON representation of the default service config.
For more information about service configs, see:
https://github.com/grpc/grpc/blob/master/doc/service_config.md
For a simple example of usage, see:
examples/features/load_balancing/client/main.go
WithDialer returns a DialOption that specifies a function to use for dialing
network addresses. If FailOnNonTempDialError() is set to true, and an error
is returned by f, gRPC checks the error's Temporary() method to decide if it
should try to reconnect to the network address.
Deprecated: use WithContextDialer instead. Will be supported throughout
1.x.
WithDisableHealthCheck disables the LB channel health checking for all
SubConns of this ClientConn.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WithDisableRetry returns a DialOption that disables retries, even if the
service config enables them. This does not impact transparent retries, which
will happen automatically if no data is written to the wire or if the RPC is
unprocessed by the remote server.
WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any
service config provided by the resolver and provides a hint to the resolver
to not fetch service configs.
Note that this dial option only disables service config from resolver. If
default service config is provided, gRPC will use the default service config.
WithIdleTimeout returns a DialOption that configures an idle timeout for the
channel. If the channel is idle for the configured timeout, i.e there are no
ongoing RPCs and no new RPCs are initiated, the channel will enter idle mode
and as a result the name resolver and load balancer will be shut down. The
channel will exit idle mode when the Connect() method is called or when an
RPC is initiated.
A default timeout of 30 minutes will be used if this dial option is not set
at dial time and idleness can be disabled by passing a timeout of zero.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WithInitialConnWindowSize returns a DialOption which sets the value for
initial window size on a connection. The lower bound for window size is 64K
and any value smaller than that will be ignored.
WithInitialWindowSize returns a DialOption which sets the value for initial
window size on a stream. The lower bound for window size is 64K and any value
smaller than that will be ignored.
WithInsecure returns a DialOption which disables transport security for this
ClientConn. Under the hood, it uses insecure.NewCredentials().
Note that using this DialOption with per-RPC credentials (through
WithCredentialsBundle or WithPerRPCCredentials) which require transport
security is incompatible and will cause RPCs to fail.
Deprecated: use WithTransportCredentials and insecure.NewCredentials()
instead. Will be supported throughout 1.x.
WithKeepaliveParams returns a DialOption that specifies keepalive parameters
for the client transport.
Keepalive is disabled by default.
WithLocalDNSResolution forces local DNS name resolution even when a proxy is
specified in the environment. By default, the server name is provided
directly to the proxy as part of the CONNECT handshake. This is ignored if
WithNoProxy is used.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WithMaxCallAttempts returns a DialOption that configures the maximum number
of attempts per call (including retries and hedging) using the channel.
Service owners may specify a higher value for these parameters, but higher
values will be treated as equal to the maximum value by the client
implementation. This mitigates security concerns related to the service
config being transferred to the client via DNS.
A value of 5 will be used if this dial option is not set or n < 2.
WithMaxHeaderListSize returns a DialOption that specifies the maximum
(uncompressed) size of header list that the client is prepared to accept.
WithMaxMsgSize returns a DialOption which sets the maximum message size the
client can receive.
Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. Will
be supported throughout 1.x.
WithNoProxy returns a DialOption which disables the use of proxies for this
ClientConn. This is ignored if WithDialer or WithContextDialer are used.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WithPerRPCCredentials returns a DialOption which sets credentials and places
auth state on each outbound RPC.
WithReadBufferSize lets you set the size of read buffer, this determines how
much data can be read at most for each read syscall.
The default value for this buffer is 32KB. Zero or negative values will
disable read buffer for a connection so data framer can access the
underlying conn directly.
WithResolvers allows a list of resolver implementations to be registered
locally with the ClientConn without needing to be globally registered via
resolver.Register. They will be matched against the scheme used for the
current Dial only, and will take precedence over the global registry.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WithReturnConnectionError returns a DialOption which makes the client connection
return a string containing both the last connection error that occurred and
the context.DeadlineExceeded error.
Implies WithBlock()
Use of this feature is not recommended. For more information, please see:
https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md
Deprecated: this DialOption is not supported by NewClient.
Will be supported throughout 1.x.
WithSharedWriteBuffer allows reusing per-connection transport write buffer.
If this option is set to true every connection will release the buffer after
flushing the data on the wire.
# Experimental
Notice: This API is EXPERIMENTAL and may be changed or removed in a
later release.
WithStaticConnWindowSize returns a DialOption which sets the initial
connection window size to the value provided and disables dynamic flow
control.
WithStaticStreamWindowSize returns a DialOption which sets the initial
stream window size to the value provided and disables dynamic flow control.
WithStatsHandler returns a DialOption that specifies the stats handler for
all the RPCs and underlying network connections in this ClientConn.
WithStreamInterceptor returns a DialOption that specifies the interceptor for
streaming RPCs.
WithTimeout returns a DialOption that configures a timeout for dialing a
ClientConn initially. This is valid if and only if WithBlock() is present.
Deprecated: this DialOption is not supported by NewClient.
Will be supported throughout 1.x.
WithTransportCredentials returns a DialOption which configures a connection
level security credentials (e.g., TLS/SSL). This should not be used together
with WithCredentialsBundle.
WithUnaryInterceptor returns a DialOption that specifies the interceptor for
unary RPCs.
WithUserAgent returns a DialOption that specifies a user agent string for all
the RPCs.
WithWriteBufferSize determines how much data can be batched before doing a
write on the wire. The default value for this buffer is 32KB.
Zero or negative values will disable the write buffer such that each write
will be on underlying connection. Note: A Send call may not directly
translate to a write.
WriteBufferSize determines how much data can be batched before doing a write
on the wire. The default value for this buffer is 32KB. Zero or negative
values will disable the write buffer such that each write will be on underlying
connection. Note: A Send call may not directly translate to a write.
compress returns the input bytes compressed by compressor or cp.
If both compressors are nil, or if the message has zero length, returns nil,
indicating no compression was done.
TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
Makes a copy of the input addresses slice. Addresses are passed during
subconn creation and address update operations.
decompress processes the given data by decompressing it using either a custom decompressor or a standard compressor.
If a custom decompressor is provided, it takes precedence. The function validates that the decompressed data
does not exceed the specified maximum size and returns an error if this limit is exceeded.
On success, it returns the decompressed data. Otherwise, it returns an error if decompression fails or the data exceeds the size limit.
doneChannelzWrapper performs the following:
- increments the calls started channelz counter
- wraps the done function in the passed in result to increment the calls
failed or calls succeeded channelz counter before invoking the actual
done function.
encode serializes msg and returns a buffer containing the message, or an
error if it is too large to be transmitted by grpc. If msg is nil, it
generates an empty message.
encodeAuthority escapes the authority string based on valid chars defined in
https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.
equalAddressIgnoringBalAttributes returns true is a and b are considered equal.
This is different from the Equal method on the resolver.Address type which
considers all fields to determine equality. Here, we only consider fields
that are meaningful to the subConn.
equalServiceConfig compares two configs. The rawJSONString field is ignored,
because they may diff in white spaces.
If any of them is NOT *ServiceConfig, return false.
getChainStreamer recursively generate the chained client stream constructor.
getChainUnaryInvoker recursively generate the chained unary invoker.
getCodec returns an encoding.CodecV2 for the codec of the given name (if
registered). Initially checks the V2 registry with encoding.GetCodecV2 and
returns the V2 codec if it is registered. Otherwise, it checks the V1 registry
with encoding.GetCodec and if it is registered wraps it with newCodecV1Bridge
to turn it into an encoding.CodecV2. Returns nil otherwise.
msgHeader returns a 5-byte header for the message being transmitted and the
payload, which is compData if non-nil or data otherwise.
newCCBalancerWrapper creates a new balancer wrapper in idle state. The
underlying balancer is not created until the updateClientConnState() method
is invoked.
newCCResolverWrapper initializes the ccResolverWrapper. It can only be used
after calling start, which builds the resolver.
newNonRetryClientStream creates a ClientStream with the specified transport, on the
given addrConn.
It's expected that the given transport is either the same one in addrConn, or
is already closed. To avoid race, transport is specified separately, instead
of using ac.transport.
Main difference between this and ClientConn.NewStream:
- no retry
- no service config (or wait for service config)
- no tracing or stats
parseTarget uses RFC 3986 semantics to parse the given target into a
resolver.Target struct containing url. Query params are stripped from the
endpoint.
prepareMsg returns the hdr, payload and data using the compressors passed or
using the passed preparedmsg. The returned boolean indicates whether
compression was made and therefore whether the payload needs to be freed in
addition to the returned data. Freeing the payload if the returned boolean is
false can lead to undefined behavior.
For the two compressor parameters, both should not be set, but if they are,
dc takes precedence over compressor.
TODO(dfawley): wrap the old compressor/decompressor using the new API?
recvAndDecompress reads a message from the stream, decompressing it if necessary.
Cancelling the returned cancel function releases the buffer back to the pool. So the caller should cancel as soon as
the buffer is no longer needed.
TODO: Refactor this function to reduce the number of arguments.
See: https://google.github.io/styleguide/go/best-practices.html#function-argument-lists
validateSendCompressor returns an error when given compressor name cannot be
handled by the server or the client based on the advertised compressors.
withBackoff sets the backoff strategy used for connectRetryNum after a failed
connection attempt.
This can be exported if arbitrary backoff strategies are allowed by gRPC.
withBinaryLogger returns a DialOption that specifies the binary logger for
this ClientConn.
withDefaultScheme is used to allow Dial to use "passthrough" as the default
name resolver, while NewClient uses "dns" otherwise.
withMinConnectDeadline specifies the function that clientconn uses to
get minConnectDeadline. This can be used to make connection attempts happen
faster/slower.
For testing purpose only.
Package-Level Variables (total 29, in which 6 are exported)
DefaultBackoffConfig uses values specified for backoff in
https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
Deprecated: use ConnectParams instead. Will be supported throughout 1.x.
EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package.
This should only be set before any RPCs are sent or received by this program.
ErrClientConnClosing indicates that the operation is illegal because
the ClientConn is closing.
Deprecated: this error should not be relied upon by users; use the status
code of Canceled instead.
ErrClientConnTimeout indicates that the ClientConn cannot establish the
underlying connections within the specified timeout.
Deprecated: This error is never returned by grpc and should not be
referenced by users.
ErrServerStopped indicates that the operation is now illegal because of
the server being stopped.
PickFirstBalancerName is the name of the pick_first balancer.
errNoTransportCredsInBundle indicated that the configured creds bundle
returned a transport credentials which was nil.
errNoTransportSecurity indicates that there is no transport security
being set for ClientConn. Users should either set one or explicitly
call WithInsecure DialOption to disable security.
errTransportCredentialsMissing indicates that users want to transmit
security information (e.g., OAuth2 token) which requires secure
connection on an insecure connection.
errTransportCredsAndBundle indicates that creds bundle is used together
with other individual Transport Credentials.
Package-Level Constants (total 26, in which 8 are exported)
The SupportPackageIsVersion variables are referenced from generated protocol
buffer files to ensure compatibility with the gRPC version used. The latest
support package version is 9.
Older versions are kept for compatibility.
These constants should not be referenced from any other code.
The SupportPackageIsVersion variables are referenced from generated protocol
buffer files to ensure compatibility with the gRPC version used. The latest
support package version is 9.
Older versions are kept for compatibility.
These constants should not be referenced from any other code.
The SupportPackageIsVersion variables are referenced from generated protocol
buffer files to ensure compatibility with the gRPC version used. The latest
support package version is 9.
Older versions are kept for compatibility.
These constants should not be referenced from any other code.
The SupportPackageIsVersion variables are referenced from generated protocol
buffer files to ensure compatibility with the gRPC version used. The latest
support package version is 9.
Older versions are kept for compatibility.
These constants should not be referenced from any other code.
The SupportPackageIsVersion variables are referenced from generated protocol
buffer files to ensure compatibility with the gRPC version used. The latest
support package version is 9.
Older versions are kept for compatibility.
These constants should not be referenced from any other code.
The SupportPackageIsVersion variables are referenced from generated protocol
buffer files to ensure compatibility with the gRPC version used. The latest
support package version is 9.
Older versions are kept for compatibility.
These constants should not be referenced from any other code.
The SupportPackageIsVersion variables are referenced from generated protocol
buffer files to ensure compatibility with the gRPC version used. The latest
support package version is 9.
Older versions are kept for compatibility.
These constants should not be referenced from any other code.
Server transports are tracked in a map which is keyed on listener
address. For regular gRPC traffic, connections are accepted in Serve()
through a call to Accept(), and we use the actual listener address as key
when we add it to the map. But for connections received through
ServeHTTP(), we do not have a listener and hence use this dummy value.
serverWorkerResetThreshold defines how often the stack must be reset. Every
N requests, by spawning a new goroutine in its place, a worker can reset its
stack so that large stacks don't live in memory forever. 2^16 should allow
each goroutine stack to live for at least a few seconds in a typical
workload (assuming a QPS of a few thousand requests/sec).