grpc
v0.0.0-20170609214715-11d0a25b4919
Documentation
pkg.go.dev ↗Package grpc implements an RPC system called gRPC.
See www.grpc.io for more information about gRPC.
WARNING: this is an EXPERIMENTAL and unsupported version of the official gRPC-Go package. For the official version, see https://github.com/grpc/grpc-go. For information about this experimental version, see https://github.com/go4org/grpc
Constants
SupportPackageIsVersion4
const SupportPackageIsVersion4 = true
SupportPackageIsVersion4 is referenced from generated protocol buffer files to assert that that code is compatible with this version of the grpc package.
This constant may be renamed in the future if a change in the generated code requires a synchronised update of grpc-go and protoc-gen-go. This constant should not be referenced from any other code.
Variables
ErrClientConnClosing (2 declarations)
var (
// ErrClientConnClosing indicates that the operation is illegal because
// the ClientConn is closing.
ErrClientConnClosing = errors.New("grpc: the client connection is closing")
// ErrClientConnTimeout indicates that the ClientConn cannot establish the
// underlying connections within the specified timeout.
// DEPRECATED: Please use context.DeadlineExceeded instead. This error will be
// removed in Q1 2017.
ErrClientConnTimeout = errors.New("grpc: timed out when dialing")
)
DefaultBackoffConfig
var (
DefaultBackoffConfig = BackoffConfig{
MaxDelay: 120 * time.Second,
// contains filtered or unexported fields
}
)
DefaultBackoffConfig uses values specified for backoff in https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
EnableTracing
var EnableTracing = true
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.
ErrServerStopped
var (
// ErrServerStopped indicates that the operation is now illegal because of
// the server being stopped.
ErrServerStopped = errors.New("grpc: the server has been stopped")
)
Functions
Code
func Code(err error) codes.Code
Code returns the error code for err if it was produced by the rpc system. Otherwise, it returns codes.Unknown.
ErrorDesc
func ErrorDesc(err error) string
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.
Errorf
func Errorf(c codes.Code, format string, a ...interface{}) error
Errorf returns an error containing an error code and a description; Errorf returns nil if c is OK.
Invoke
func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error
Invoke sends a non-streaming RPC request on the wire and returns after a response is received.
Invoke is generally only called by generated code.
SendHeader
func SendHeader(ctx context.Context, md metadata.MD) error
SendHeader sends header metadata. It may be called at most once. The provided md and headers set by SetHeader() will be sent.
SetHeader
func SetHeader(ctx context.Context, md metadata.MD) error
SetHeader sets the header metadata. 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;
- The first response is sent out;
- An RPC status is sent out (error or success).
SetTrailer
func SetTrailer(ctx context.Context, md metadata.MD) error
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.
Types
BackoffConfig
type BackoffConfig struct {
// MaxDelay is the upper bound of backoff delay.
MaxDelay time.Duration
// contains filtered or unexported fields
}
BackoffConfig defines the parameters for the default gRPC backoff strategy.
Balancer
type Balancer struct{}
Deprecated: don't use for now.
RoundRobin
func RoundRobin(r naming.Resolver) Balancer
Deprecated: don't use for now.
CallOption
type CallOption interface {
// contains filtered or unexported methods
}
CallOption configures a Call before it starts or extracts information from a Call after it completes.
FailFast
func FailFast(failFast bool) CallOption
FailFast configures the action to take when an RPC is attempted on broken connections or unreachable servers. If failfast is true, the RPC will fail immediately. Otherwise, the RPC client will block the call until a connection is available (or the call is canceled or times out) and will retry the call if it fails due to a transient error. Please refer to https://github.com/grpc/grpc/blob/master/doc/fail_fast.md
Header
func Header(md *metadata.MD) CallOption
Header returns a CallOptions that retrieves the header metadata for a unary RPC.
Trailer
func Trailer(md *metadata.MD) CallOption
Trailer returns a CallOptions that retrieves the trailer metadata for a unary RPC.
ClientConn
type ClientConn struct {
// contains filtered or unexported fields
}
ClientConn is a gRPC client.
Despite its name, it is not necessarily a single connection. Depending on its underlying transport, it could be using zero or multiple TCP or other connections, and changing over time.
Dial
func Dial(target string, opts ...DialOption) (*ClientConn, error)
Dial is the old way to create a gRPC client.
Deprecated: use NewClient instead. This only exists to let existing code in the wild work.
DialContext
func DialContext(ctx context.Context, target string, opts ...DialOption) (*ClientConn, error)
DialContext is the old way to create a gRPC client.
Deprecated: use NewClient instead.
NewClient
func NewClient(hc *http.Client, target string, opts ...DialOption) (*ClientConn, error)
NewClient returns a new gRPC client for the provided target server. If the provided HTTP client is nil, http.DefaultClient is used. The target should be a URL scheme and authority, without a path. For example, "https://api.example.com" for TLS or "http://10.0.5.3:5000" for unencrypted HTTP/2.
The returned type is named "ClientConn" for legacy reasons. It does not necessarily represent one actual connection. (It might be zero or multiple.)
ClientConn.Close
func (cc *ClientConn) Close() error
Close tears down the ClientConn and all underlying connections.
ClientStream
type ClientStream interface {
// Header returns the header metadata received from the server if there
// is any. It blocks if the metadata is not ready to read.
Header() (metadata.MD, error)
// 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).
Trailer() metadata.MD
// CloseSend closes the send direction of the stream. It closes the stream
// when non-nil error is met.
CloseSend() error
Stream
}
ClientStream defines the interface a client stream has to satisfy.
NewClientStream
func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)
NewClientStream creates a new Stream for the client side. This is called by generated code.
Codec
type Codec interface {
// Marshal returns the wire format of v.
Marshal(v interface{}) ([]byte, error)
// Unmarshal parses the wire format into v.
Unmarshal(data []byte, v interface{}) error
// String returns the name of the Codec implementation. The returned
// string will be used as part of content type in transmission.
String() string
}
Codec defines the interface gRPC uses to encode and decode messages.
Compressor
type Compressor interface {
// Do compresses p into w.
Do(w io.Writer, p []byte) error
// Type returns the compression algorithm the Compressor uses.
Type() string
}
Compressor defines the interface gRPC uses to compress a message.
NewGZIPCompressor
func NewGZIPCompressor() Compressor
NewGZIPCompressor creates a Compressor based on GZIP.
ConnectivityState
type ConnectivityState int
ConnectivityState indicates the state of a client connection.
Idle (5 declarations)
const ( // Idle indicates the ClientConn is idle. Idle ConnectivityState = iota // Connecting indicates the ClienConn is connecting. Connecting // Ready indicates the ClientConn is ready for work. Ready // TransientFailure indicates the ClientConn has seen a failure but expects to recover. TransientFailure // Shutdown indicates the ClientConn has started shutting down. Shutdown )
ConnectivityState.String
func (s ConnectivityState) String() string
Decompressor
type Decompressor interface {
// Do reads the data from r and uncompress them.
Do(r io.Reader) ([]byte, error)
// Type returns the compression algorithm the Decompressor uses.
Type() string
}
Decompressor defines the interface gRPC uses to decompress a message.
NewGZIPDecompressor
func NewGZIPDecompressor() Decompressor
NewGZIPDecompressor creates a Decompressor based on GZIP.
DialOption
type DialOption func(*clientOptions)
DialOption is a client option.
Despite its name, it does not necessarily have anything to do with dialing.
TODO: rename this.
WithBalancer
func WithBalancer(b Balancer) DialOption
Deprecated: don't use for now.
WithCodec
func WithCodec(c Codec) DialOption
WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.
WithCompressor
func WithCompressor(cp Compressor) DialOption
WithCompressor returns a DialOption which sets a CompressorGenerator for generating message compressor.
WithDecompressor
func WithDecompressor(dc Decompressor) DialOption
WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating message decompressor.
WithInsecure
func WithInsecure() DialOption
WithInsecure returns a DialOption which disables transport security for this ClientConn. WithInsecure is mutually exclusive with use of WithTransportCredentials or https endpoints.
WithPerRPCCredentials
func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption
WithPerRPCCredentials returns an option which sets credentials which will place auth state on each outbound RPC.
WithStatsHandler
func WithStatsHandler(h stats.Handler) DialOption
WithStatsHandler returns a DialOption that specifies the stats handler for all the RPCs and underlying network connections in this ClientConn.
WithTransportCredentials
func WithTransportCredentials(creds credentials.TransportCredentials) DialOption
WithTransportCredentials is controls whether to use TLS or not for connections.
Deprecated: this is only respected in a minimal form to let existing code in the wild work. Uew NewClient instead.
WithUserAgent
func WithUserAgent(s string) DialOption
WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.
MethodConfig
type MethodConfig struct {
// WaitForReady indicates whether RPCs sent to this method should wait until
// the connection is ready by default (!failfast). The value specified via the
// gRPC client API will override the value set here.
WaitForReady bool
// Timeout is the default timeout for RPCs sent to this method. The actual
// deadline used will be the minimum of the value specified here and the value
// set by the application via the gRPC client API. If either one is not set,
// then the other will be used. If neither is set, then the RPC has no deadline.
Timeout time.Duration
// MaxReqSize is the maximum allowed payload size for an individual request in a
// stream (client->server) in bytes. The size which is measured is the serialized,
// uncompressed payload in bytes. The actual value used is the minumum of the value
// specified here and the value set by the application via the gRPC client API. If
// either one is not set, then the other will be used. If neither is set, then the
// built-in default is used.
// TODO: support this.
MaxReqSize uint64
// MaxRespSize is the maximum allowed payload size for an individual response in a
// stream (server->client) in bytes.
// TODO: support this.
MaxRespSize uint64
}
MethodConfig defines the configuration recommended by the service providers for a particular method. This is EXPERIMENTAL and subject to change.
MethodDesc
type MethodDesc struct {
MethodName string
Handler methodHandler
}
MethodDesc represents an RPC service's method specification.
MethodInfo
type MethodInfo struct {
// Name is the method name only, without the service name or package name.
Name string
// IsClientStream indicates whether the RPC is a client streaming RPC.
IsClientStream bool
// IsServerStream indicates whether the RPC is a server streaming RPC.
IsServerStream bool
}
MethodInfo contains the information of an RPC including its method name and type.
Server
type Server struct {
// contains filtered or unexported fields
}
Server is a gRPC server to serve RPC requests.
NewServer
func NewServer(opt ...ServerOption) *Server
NewServer creates a gRPC server which has no service registered and has not started to accept requests yet.
Server.GetServiceInfo
func (s *Server) GetServiceInfo() map[string]ServiceInfo
GetServiceInfo returns a map from service names to ServiceInfo. Service names include the package names, in the form of <package>.<service>.
Server.GracefulStop
func (s *Server) GracefulStop()
GracefulStop stops the gRPC server gracefully. It stops the server to accept new connections and RPCs and blocks until all the pending RPCs are finished.
Server.RegisterService
func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})
RegisterService register a service and its implementation to the gRPC server. Called from the IDL generated code. This must be called before invoking Serve.
Server.Serve
func (s *Server) Serve(lis net.Listener) error
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 always returns non-nil error.
Server.ServeHTTP
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
Server.Stop
func (s *Server) Stop()
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.
ServerOption
type ServerOption func(*options)
A ServerOption sets options.
Creds
func Creds(c credentials.TransportCredentials) ServerOption
Creds returns a ServerOption that sets credentials for server connections.
CustomCodec
func CustomCodec(codec Codec) ServerOption
CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
InTapHandle
func InTapHandle(h tap.ServerInHandle) ServerOption
InTapHandle returns a ServerOption that sets the tap handle for all the server transport to be created. Only one can be installed.
MaxConcurrentStreams
func MaxConcurrentStreams(n uint32) ServerOption
MaxConcurrentStreams returns a ServerOption that will apply a limit on the number of concurrent streams to each ServerTransport.
MaxMsgSize
func MaxMsgSize(m int) ServerOption
MaxMsgSize returns a ServerOption to set the max message size in bytes for inbound mesages. If this is not set, gRPC uses the default 4MB.
RPCCompressor
func RPCCompressor(cp Compressor) ServerOption
RPCCompressor returns a ServerOption that sets a compressor for outbound messages.
RPCDecompressor
func RPCDecompressor(dc Decompressor) ServerOption
RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages.
StatsHandler
func StatsHandler(h stats.Handler) ServerOption
StatsHandler returns a ServerOption that sets the stats handler for the server.
ServerStream
type ServerStream interface {
// 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).
SetHeader(metadata.MD) error
// SendHeader sends the header metadata.
// The provided md and headers set by SetHeader() will be sent.
// It fails if called multiple times.
SendHeader(metadata.MD) error
// 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.
SetTrailer(metadata.MD)
Stream
}
ServerStream defines the interface a server stream has to satisfy.
ServiceConfig
type ServiceConfig struct {
// Methods contains a map for the methods in this service.
Methods map[string]MethodConfig
}
ServiceConfig is provided by the service provider and contains parameters for how clients that connect to the service should behave. This is EXPERIMENTAL and subject to change.
ServiceDesc
type ServiceDesc struct {
ServiceName string
// The pointer to the service interface. Used to check whether the user
// provided implementation satisfies the interface requirements.
HandlerType interface{}
Methods []MethodDesc
Streams []StreamDesc
Metadata interface{}
}
ServiceDesc represents an RPC service's specification.
ServiceInfo
type ServiceInfo struct {
Methods []MethodInfo
// Metadata is the metadata specified in ServiceDesc when registering service.
Metadata interface{}
}
ServiceInfo contains unary RPC method info, streaming RPC methid info and metadata for a service.
Stream
type Stream interface {
// Context returns the context for this stream.
Context() context.Context
// SendMsg blocks until it sends m, the stream is done or the stream
// breaks.
// On error, it aborts the stream and returns an RPC status on client
// side. On server side, it simply returns the error to the caller.
// SendMsg is called by generated code. Also Users can call SendMsg
// directly when it is really needed in their use cases.
SendMsg(m interface{}) error
// RecvMsg blocks until it receives a message or the stream is
// done. On client side, it returns io.EOF when the stream is done. On
// any other error, it aborts the stream and returns an RPC status. On
// server side, it simply returns the error to the caller.
RecvMsg(m interface{}) error
}
Stream defines the common interface a client or server stream has to satisfy.
StreamClientInterceptor
type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error)
StreamClientInterceptor intercepts the creation of ClientStream. It may return a custom ClientStream to intercept all I/O operations. streamer is the handlder to create a ClientStream and it is the responsibility of the interceptor to call it. This is the EXPERIMENTAL API.
StreamDesc
type StreamDesc struct {
StreamName string
Handler StreamHandler
// At least one of these is true.
ServerStreams bool
ClientStreams bool
}
StreamDesc represents a streaming RPC service's method specification.
StreamHandler
type StreamHandler func(srv interface{}, stream ServerStream) error
StreamHandler defines the handler called by gRPC server to complete the execution of a streaming RPC.
StreamServerInfo
type StreamServerInfo struct {
// FullMethod is the full RPC method string, i.e., /package.service/method.
FullMethod string
// IsClientStream indicates whether the RPC is a client streaming RPC.
IsClientStream bool
// IsServerStream indicates whether the RPC is a server streaming RPC.
IsServerStream bool
}
StreamServerInfo consists of various information about a streaming RPC on server side. All per-rpc information may be mutated by the interceptor.
StreamServerInterceptor
type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error
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.
Streamer
type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)
Streamer is called by StreamClientInterceptor to create a ClientStream.
UnaryHandler
type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error)
UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal execution of a unary RPC.
UnaryServerInfo
type UnaryServerInfo struct {
// Server is the service implementation the user provides. This is read-only.
Server interface{}
// FullMethod is the full RPC method string, i.e., /package.service/method.
FullMethod string
}
UnaryServerInfo consists of various information about a unary RPC on server side. All per-rpc information may be mutated by the interceptor.
UnaryServerInterceptor
type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error)
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.