Documentation ¶
Overview ¶
Package grpcx is a generated protocol buffer package.
It is generated from these files:
packet.proto
It has these top-level messages:
PackHeader NetPack
Index ¶
- Constants
- Variables
- func GetMetaFromContext(ctx context.Context) map[int32][]byte
- func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, ...) error
- func RegistNotifyHandler(serviceName string, handler interface{}, withMeta ...bool) error
- func RegistNotifyStruct(serviceName string, struc interface{}) error
- type Address
- type Balancer
- type BalancerConfig
- type BalancerGetOptions
- type CallContext
- type CallOption
- type ClientConn
- func (cc *ClientConn) BackCall(ctx context.Context, method string, args, reply interface{}, ...) (*CallContext, error)
- func (cc *ClientConn) Call(ctx context.Context, method string, args, reply interface{}, ...) error
- func (cc *ClientConn) Close() error
- func (cc *ClientConn) GetMethodConfig(method string) MethodConfig
- func (cc *ClientConn) GetState() ConnectivityState
- func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, ...) error
- func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
- func (cc *ClientConn) Send(ctx context.Context, method string, args interface{}, opts ...CallOption) error
- func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState ConnectivityState) bool
- type ClientStream
- type CompType
- type Conn
- type ConnectivityState
- type ConnectivityStateEvaluator
- type ConnectivityStateManager
- type DialOption
- func WithBalancer(b Balancer) DialOption
- func WithBlock() DialOption
- func WithCodec(c codec.Codec) DialOption
- func WithCompressor(cp compresser.Compressor) DialOption
- func WithCreds(c credentials.TransportCredentials) DialOption
- func WithDecompressor(dc compresser.Decompressor) DialOption
- func WithDefaultCallOptions(cos ...CallOption) DialOption
- func WithDialTimeout(d time.Duration) DialOption
- func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption
- func WithKeepAlive(d time.Duration) DialOption
- func WithMaxMsgSize(s int) DialOption
- func WithPlugin(plugin IConnPlugin) DialOption
- func WithReadTimeout(t time.Duration) DialOption
- func WithReaderWindowSize(s int32) DialOption
- func WithServiceConfig(c <-chan ServiceConfig) DialOption
- func WithWriteTimeout(t time.Duration) DialOption
- type EmptyCallOption
- type IConnPlugin
- type MethodConfig
- type MethodDesc
- type MethodInfo
- type NetPack
- func (*NetPack) Descriptor() ([]byte, []int)
- func (m *NetPack) GetBody() []byte
- func (m *NetPack) GetHeader() *PackHeader
- func (m *NetPack) Marshal() (dAtA []byte, err error)
- func (m *NetPack) MarshalTo(dAtA []byte) (int, error)
- func (*NetPack) ProtoMessage()
- func (m *NetPack) Reset()
- func (m *NetPack) Size() (n int)
- func (m *NetPack) String() string
- func (m *NetPack) Unmarshal(dAtA []byte) error
- type PackHeader
- func (*PackHeader) Descriptor() ([]byte, []int)
- func (m *PackHeader) GetMetadata() map[int32][]byte
- func (m *PackHeader) GetMethord() string
- func (m *PackHeader) GetPtype() PackType
- func (m *PackHeader) GetSessionid() int64
- func (m *PackHeader) Marshal() (dAtA []byte, err error)
- func (m *PackHeader) MarshalTo(dAtA []byte) (int, error)
- func (*PackHeader) ProtoMessage()
- func (m *PackHeader) Reset()
- func (m *PackHeader) Size() (n int)
- func (m *PackHeader) String() string
- func (m *PackHeader) Unmarshal(dAtA []byte) error
- type PackType
- type Server
- func (s *Server) GracefulStop(ctx context.Context)
- func (s *Server) RegistHandler(serviceName string, handler interface{}, withMeta ...bool) error
- func (s *Server) RegistStruct(serviceName string, struc interface{}) error
- func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})
- func (s *Server) SendTo(ctx context.Context, method string, m interface{}, keys ...metaKeyType) (err error)
- func (s *Server) Serve(ln net.Listener) error
- func (s *Server) Stop()
- type ServerOption
- func Creds(c credentials.TransportCredentials) ServerOption
- func CustomCodec(codec codec.Codec) ServerOption
- func KeepalivePeriod(kp time.Duration) ServerOption
- func MaxConcurrentRequest(n uint32) ServerOption
- func MaxConcurrentRoutine(n uint32) ServerOption
- func MaxMsgSize(m int) ServerOption
- func MaxRecvMsgSize(m int) ServerOption
- func MaxSendMsgSize(m int) ServerOption
- func Plugin(plugin IConnPlugin) ServerOption
- func RPCCompressor(cp compresser.Compressor) ServerOption
- func RPCDecompressor(dc compresser.Decompressor) ServerOption
- func ReadTimeout(t time.Duration) ServerOption
- func ReaderWindowSize(s int32) ServerOption
- func WriteTimeout(t time.Duration) ServerOption
- type ServerStream
- type ServiceConfig
- type ServiceDesc
- type ServiceInfo
- type Stream
- type StreamClientInterceptor
- type StreamDesc
- type StreamHandler
- type StreamServerInfo
- type StreamServerInterceptor
- type Streamer
- type UnaryClientInterceptor
- type UnaryHandler
- type UnaryInvoker
- type UnaryServerInfo
- type UnaryServerInterceptor
Constants ¶
const SupportPackageIsVersion3 = true
SupportPackageIsVersion3 is referenced from generated protocol buffer files. The latest support package version is 4. SupportPackageIsVersion3 is kept for compability. It will be removed in the next support package version update.
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.
const Version = "1.6.0-dev"
Version is the current grpc version.
Variables ¶
var ( ErrInvalidLengthPacket = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowPacket = fmt.Errorf("proto: integer overflow") )
var ( // ErrServerStopped indicates that the operation is now illegal because of // the server being stopped. ErrServerStopped = errors.New("grpcx: the server has been stopped") // ErrInvalidConnid indicates the connection is not exist index by the connid ErrInvalidConnid = errors.New("grpcx: connection id invalid, connection not exist") )
var CompType_name = map[int32]string{
0: "None",
1: "GZip",
}
var CompType_value = map[string]int32{
"None": 0,
"GZip": 1,
}
var ( // ErrClientConnClosing indicates that the operation is illegal because // the ClientConn is closing. ErrClientConnClosing = errors.New("grpc: the client connection is closing") )
var PackType_name = map[int32]string{
0: "UNKNOW",
1: "SINI",
2: "SREQ",
3: "SRSP",
4: "REQ",
5: "RSP",
6: "Notify",
7: "PING",
8: "PONG",
9: "EOF",
10: "ERROR",
11: "GoAway",
}
var PackType_value = map[string]int32{
"UNKNOW": 0,
"SINI": 1,
"SREQ": 2,
"SRSP": 3,
"REQ": 4,
"RSP": 5,
"Notify": 6,
"PING": 7,
"PONG": 8,
"EOF": 9,
"ERROR": 10,
"GoAway": 11,
}
Functions ¶
func GetMetaFromContext ¶
GetMetaFromContext used to get metadata from context
func Invoke ¶
func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error
Invoke sends the RPC request on the wire and returns after response is received. Invoke is called by generated code. Also users can call Invoke directly when it is really needed in their use cases.
func RegistNotifyHandler ¶
RegistNotifyHandler used to regist a notify handler serviceName: must in the format "/{service}/{methord}" withMeta: if business layer need to get the metadata, set this and metadata will taken be context not goroutine safe: should be call before serving, otherwise may cause crash
func RegistNotifyStruct ¶
RegistNotifyStruct used to regist group notify handler group by struct erviceName: only taken the name of the service but no method and slash" struc is the value of the struct, must be pointer not goroutine safe: should be call before serving, otherwise may cause crash
Types ¶
type Address ¶
type Address struct { // Addr is the server address on which a connection will be established. Addr string // Metadata is the information associated with Addr, which may be used // to make load balancing decision. Metadata interface{} }
Address represents a server the client connects to. This is the EXPERIMENTAL API and may be changed or extended in the future.
type Balancer ¶
type Balancer interface { // Start does the initialization work to bootstrap a Balancer. For example, // this function may start the name resolution and watch the updates. It will // be called when dialing. Start(target string, config BalancerConfig) error // Up informs the Balancer that gRPC has a connection to the server at // addr. It returns down which is called once the connection to addr gets // lost or closed. // TODO: It is not clear how to construct and take advantage of the meaningful error // parameter for down. Need realistic demands to guide. Up(addr string) (down func(error)) // Get gets the address of a server for the RPC corresponding to ctx. // i) If it returns a connected address, gRPC internals issues the RPC on the // connection to this address; // ii) If it returns an address on which the connection is under construction // (initiated by Notify(...)) but not connected, gRPC internals // * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or // Shutdown state; // or // * issues RPC on the connection otherwise. // iii) If it returns an address on which the connection does not exist, gRPC // internals treats it as an error and will fail the corresponding RPC. // // Therefore, the following is the recommended rule when writing a custom Balancer. // If opts.BlockingWait is true, it should return a connected address or // block if there is no connected address. It should respect the timeout or // cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast // RPCs), it should return an address it has notified via Notify(...) immediately // instead of blocking. // // The function returns put which is called once the rpc has completed or failed. // put can collect and report RPC stats to a remote load balancer. // // This function should only return the errors Balancer cannot recover by itself. // gRPC internals will fail the RPC if an error is returned. Get(ctx context.Context, opts BalancerGetOptions) (addr string, put func(), err error) // Notify returns a channel that is used by gRPC internals to watch the addresses // gRPC needs to connect. The addresses might be from a name resolver or remote // load balancer. gRPC internals will compare it with the existing connected // addresses. If the address Balancer notified is not in the existing connected // addresses, gRPC starts to connect the address. If an address in the existing // connected addresses is not in the notification list, the corresponding connection // is shutdown gracefully. Otherwise, there are no operations to take. Note that // the string slice must be the full list of the Addresses which should be connected. // It is NOT delta. Notify() <-chan []string // Close shuts down the balancer. Close() error }
Balancer chooses network addresses for RPCs. This is the EXPERIMENTAL API and may be changed or extended in the future.
type BalancerConfig ¶
type BalancerConfig struct { // DialCreds is the transport credential the Balancer implementation can // use to dial to a remote load balancer server. The Balancer implementations // can ignore this if it does not need to talk to another party securely. DialCreds credentials.TransportCredentials // Dialer is the custom dialer the Balancer implementation can use to dial // to a remote load balancer server. The Balancer implementations // can ignore this if it doesn't need to talk to remote balancer. Dialer func(context.Context, string) (net.Conn, error) }
BalancerConfig specifies the configurations for Balancer.
type BalancerGetOptions ¶
type BalancerGetOptions struct { // BlockingWait specifies whether Get should block when there is no // connected address. BlockingWait bool // HashKey only work in hash balancer which specifies the key for hash op HashKey uint32 }
BalancerGetOptions configures a Get call. This is the EXPERIMENTAL API and may be changed or extended in the future.
type CallContext ¶
type CallContext struct {
// contains filtered or unexported fields
}
CallContext is the async rpc request info
func (*CallContext) Done ¶
func (cc *CallContext) Done() <-chan struct{}
Done indicate the request is finish
func (*CallContext) TimePass ¶
func (cc *CallContext) TimePass() time.Duration
TimePass is the time cost for the request
type 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.
func 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/wait-for-ready.md. Note: failFast is default to true.
func MaxCallRecvMsgSize ¶
func MaxCallRecvMsgSize(s int) CallOption
MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive.
func MaxCallSendMsgSize ¶
func MaxCallSendMsgSize(s int) CallOption
MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send.
func WithHBalancerKey ¶
func WithHBalancerKey(key int64) CallOption
WithHBalancerKey return a CallOption which set the consistent integer hash key the key will be used to cal a crc32 val
func WithHBalancerStrKey ¶
func WithHBalancerStrKey(key string) CallOption
WithHBalancerStrKey return a CallOption which set the consistent string hash key
func WithToken ¶
func WithToken(token int64) CallOption
WithToken return a CallOption which set the service channel hash token set the option if and only if the request must be serve in the same channel in the server
type ClientConn ¶
type ClientConn struct {
// contains filtered or unexported fields
}
ClientConn represents a client connection to an RPC server.
func Dial ¶
func Dial(target string, opts ...DialOption) (*ClientConn, error)
Dial creates a client connection to the given target.
func DialContext ¶
func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error)
DialContext creates a client connection to the given target. ctx can be used to cancel or expire the pending connection. Once this function returns, the cancellation and expiration of ctx will be noop. Users should call ClientConn.Close to terminate all the pending operations after this function returns.
func (*ClientConn) BackCall ¶
func (cc *ClientConn) BackCall(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) (*CallContext, error)
BackCall request async
func (*ClientConn) Call ¶
func (cc *ClientConn) Call(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error
Call same as Invoke
func (*ClientConn) Close ¶
func (cc *ClientConn) Close() error
Close tears down the ClientConn and all underlying connections.
func (*ClientConn) GetMethodConfig ¶
func (cc *ClientConn) GetMethodConfig(method string) MethodConfig
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 default config under the service (i.e /service/). If there is a default MethodConfig for the serivce, we return it. Otherwise, we return an empty MethodConfig.
func (*ClientConn) GetState ¶
func (cc *ClientConn) GetState() ConnectivityState
GetState returns the ConnectivityState of ClientConn.
func (*ClientConn) Invoke ¶
func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error
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.
func (*ClientConn) NewStream ¶
func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
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:
- Call Close on the ClientConn.
- Cancel the context provided.
- 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).
- 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.
func (*ClientConn) Send ¶
func (cc *ClientConn) Send(ctx context.Context, method string, args interface{}, opts ...CallOption) error
Send oneway request
func (*ClientConn) WaitForStateChange ¶
func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState ConnectivityState) bool
WaitForStateChange waits until the ConnectivityState of ClientConn changes from sourceState or ctx expires. A true value is returned in former case and false in latter.
type ClientStream ¶
type ClientStream interface { // CloseSend closes the send direction of the stream. It closes the stream // when non-nil error is met. CloseSend() error // Stream.SendMsg() may return a non-nil error when something wrong happens sending // the request. The returned error indicates the status of this sending, not the final // status of the RPC. // Always call Stream.RecvMsg() to get the final status if you care about the status of // the RPC. Stream }
ClientStream defines the interface a client stream has to satisfy.
func NewClientStream ¶
func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error)
NewClientStream creates a new Stream for the client side. This is called
type Conn ¶
type Conn interface {
// contains filtered or unexported methods
}
Conn is a network connection to a given address.
type ConnectivityState ¶
type ConnectivityState int
ConnectivityState indicates the state of a client connection.
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 //Draining indicates graceful close, unaccept new request but wait unfinish request Draining // Shutdown indicates the ClientConn has started shutting down. Shutdown // Goaway indicates server is on closing Goaway )
func (ConnectivityState) String ¶
func (s ConnectivityState) String() string
type ConnectivityStateEvaluator ¶
type ConnectivityStateEvaluator struct { CsMgr *ConnectivityStateManager // contains filtered or unexported fields }
ConnectivityStateEvaluator gets updated by addrConns when their states transition, based on which it evaluates the state of ClientConn. Note: This code will eventually sit in the balancer in the new design.
type ConnectivityStateManager ¶
type ConnectivityStateManager struct {
// contains filtered or unexported fields
}
ConnectivityStateManager keeps the ConnectivityState of ClientConn. This struct will eventually be exported so the balancers can access it.
func (*ConnectivityStateManager) GetNotifyChan ¶
func (csm *ConnectivityStateManager) GetNotifyChan() <-chan struct{}
func (*ConnectivityStateManager) GetState ¶
func (csm *ConnectivityStateManager) GetState() ConnectivityState
func (*ConnectivityStateManager) UpdateState ¶
func (csm *ConnectivityStateManager) UpdateState(state ConnectivityState) bool
UpdateState updates the ConnectivityState of ClientConn. If there's a change it notifies goroutines waiting on state change to happen.
type DialOption ¶
type DialOption func(*dialOptions)
DialOption configures how we set up the connection.
func WithBalancer ¶
func WithBalancer(b Balancer) DialOption
WithBalancer returns a DialOption which sets a load balancer.
func WithBlock ¶
func WithBlock() DialOption
WithBlock returns a DialOption which makes caller of Dial blocks until the underlying connection is up. Without this, Dial returns immediately and connecting the server happens in background.
func WithCodec ¶
func WithCodec(c codec.Codec) DialOption
WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.
func WithCompressor ¶
func WithCompressor(cp compresser.Compressor) DialOption
WithCompressor returns a DialOption which sets a CompressorGenerator for generating message compressor.
func WithCreds ¶
func WithCreds(c credentials.TransportCredentials) DialOption
WithCreds returns a DialOption that sets credentials for server connections.
func WithDecompressor ¶
func WithDecompressor(dc compresser.Decompressor) DialOption
WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating message decompressor.
func WithDefaultCallOptions ¶
func WithDefaultCallOptions(cos ...CallOption) DialOption
WithDefaultCallOptions returns a DialOption which sets the default CallOptions for calls over the connection.
func WithDialTimeout ¶
func WithDialTimeout(d time.Duration) DialOption
WithDialTimeout returns a DialOption that configures a timeout for net.DialTimeout's parameter default value is three seconds
func WithDialer ¶
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.
func WithKeepAlive ¶
func WithKeepAlive(d time.Duration) DialOption
WithKeepAlive return DialOption that set the connection keep alive period
func WithMaxMsgSize ¶
func WithMaxMsgSize(s int) DialOption
WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive. Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead.
func WithPlugin ¶
func WithPlugin(plugin IConnPlugin) DialOption
WithPlugin return DialOption that handle connection event plugin
func WithReadTimeout ¶
func WithReadTimeout(t time.Duration) DialOption
WithReadTimeout return a DialOption which sets the conn's read timeout
func WithReaderWindowSize ¶
func WithReaderWindowSize(s int32) DialOption
WithReaderWindowSize returns a DialOption which sets the value for reader window size for most data read once.
func WithServiceConfig ¶
func WithServiceConfig(c <-chan ServiceConfig) DialOption
WithServiceConfig returns a DialOption which has a channel to read the service configuration.
func WithWriteTimeout ¶
func WithWriteTimeout(t time.Duration) DialOption
WithWriteTimeout return a DialOption which sets the conn's write timeout
type EmptyCallOption ¶
type EmptyCallOption struct{}
EmptyCallOption does not alter the Call configuration. It can be embedded in another structure to carry satellite data for use by interceptors.
type IConnPlugin ¶
type IConnPlugin interface { // OnPreConnect call before dial a service // only client side can trigger this event OnPreConnect(addr string) error // OnPostCOnnect call when a connection happen(dial or accept) OnPostConnect(Conn) interface{} // OnPreDisconnect call when try to close a connection OnPreDisconnect(Conn) // OnPostDisconnect call when a connection closed OnPostDisconnect(Conn) }
IConnPlugin define the connection event interface
type 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 // payload after per-message compression (but before stream compression) 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. MaxReqSize *int // MaxRespSize is the maximum allowed payload size for an individual response in a // stream (server->client) in bytes. MaxRespSize *int }
MethodConfig defines the configuration recommended by the service providers for a particular method. This is EXPERIMENTAL and subject to change.
type MethodDesc ¶
type MethodDesc struct { MethodName string Handler interface{} }
MethodDesc represents an RPC service's method specification.
type 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.
type NetPack ¶
type NetPack struct { Header *PackHeader `protobuf:"bytes,1,opt,name=header" json:"header,omitempty"` Body []byte `protobuf:"bytes,2,opt,name=body,proto3" json:"body,omitempty"` }
func (*NetPack) Descriptor ¶
func (*NetPack) GetHeader ¶
func (m *NetPack) GetHeader() *PackHeader
func (*NetPack) ProtoMessage ¶
func (*NetPack) ProtoMessage()
type PackHeader ¶
type PackHeader struct { Ptype PackType `protobuf:"varint,1,opt,name=ptype,proto3,enum=grpcx.PackType" json:"ptype,omitempty"` Methord string `protobuf:"bytes,2,opt,name=methord,proto3" json:"methord,omitempty"` Sessionid int64 `protobuf:"varint,3,opt,name=sessionid,proto3" json:"sessionid,omitempty"` Metadata map[int32][]byte `` /* 151-byte string literal not displayed */ }
func (*PackHeader) Descriptor ¶
func (*PackHeader) Descriptor() ([]byte, []int)
func (*PackHeader) GetMetadata ¶
func (m *PackHeader) GetMetadata() map[int32][]byte
func (*PackHeader) GetMethord ¶
func (m *PackHeader) GetMethord() string
func (*PackHeader) GetPtype ¶
func (m *PackHeader) GetPtype() PackType
func (*PackHeader) GetSessionid ¶
func (m *PackHeader) GetSessionid() int64
func (*PackHeader) Marshal ¶
func (m *PackHeader) Marshal() (dAtA []byte, err error)
func (*PackHeader) ProtoMessage ¶
func (*PackHeader) ProtoMessage()
func (*PackHeader) Reset ¶
func (m *PackHeader) Reset()
func (*PackHeader) Size ¶
func (m *PackHeader) Size() (n int)
func (*PackHeader) String ¶
func (m *PackHeader) String() string
func (*PackHeader) Unmarshal ¶
func (m *PackHeader) Unmarshal(dAtA []byte) error
type PackType ¶
type PackType int32
const ( PackType_UNKNOW PackType = 0 PackType_SINI PackType = 1 PackType_SREQ PackType = 2 PackType_SRSP PackType = 3 PackType_REQ PackType = 4 PackType_RSP PackType = 5 PackType_Notify PackType = 6 PackType_PING PackType = 7 PackType_PONG PackType = 8 PackType_EOF PackType = 9 PackType_ERROR PackType = 10 PackType_GoAway PackType = 11 )
func (PackType) EnumDescriptor ¶
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a gRPC server to serve RPC requests.
func NewServer ¶
func NewServer(opt ...ServerOption) *Server
NewServer creates a gRPC server which has no service registered and has not started to accept requests yet.
func (*Server) GracefulStop ¶
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.
func (*Server) RegistHandler ¶
RegistHandler used to regist a handler serviceName: must in the format "/{service}/{methord}" withMeta: if business layer need to get the metadata, set this and metadata will taken be context
func (*Server) RegistStruct ¶
RegistStruct used to regist group handler group by struct erviceName: only taken the name of the service but no method and slash" struc is the value of the struct, must be pointer
func (*Server) RegisterService ¶
func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})
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.
func (*Server) SendTo ¶
func (s *Server) SendTo(ctx context.Context, method string, m interface{}, keys ...metaKeyType) (err error)
SendTo used to send data to client connection directly ctx must be the context get from the connection wich contain the connid
func (*Server) Serve ¶
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.
type ServerOption ¶
type ServerOption func(*options)
A ServerOption sets options such as credentials, codec and keepalive parameters, etc.
func Creds ¶
func Creds(c credentials.TransportCredentials) ServerOption
Creds returns a ServerOption that sets credentials for server connections.
func CustomCodec ¶
func CustomCodec(codec codec.Codec) ServerOption
CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
func KeepalivePeriod ¶
func KeepalivePeriod(kp time.Duration) ServerOption
KeepalivePeriod returns a ServerOption that sets keepalive and max-age parameters for the server.
func MaxConcurrentRequest ¶
func MaxConcurrentRequest(n uint32) ServerOption
MaxConcurrentRequest returns a ServerOption that will apply a limit on the number of concurrent request.
func MaxConcurrentRoutine ¶
func MaxConcurrentRoutine(n uint32) ServerOption
MaxConcurrentRoutine returns a ServerOption that will apply a limit on the number of concurrent routine.
func MaxMsgSize ¶
func MaxMsgSize(m int) ServerOption
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.
func MaxRecvMsgSize ¶
func MaxRecvMsgSize(m int) ServerOption
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.
func MaxSendMsgSize ¶
func MaxSendMsgSize(m int) ServerOption
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 4MB.
func Plugin ¶
func Plugin(plugin IConnPlugin) ServerOption
Plugin return ServerOption that handle connection event plugin
func RPCCompressor ¶
func RPCCompressor(cp compresser.Compressor) ServerOption
RPCCompressor returns a ServerOption that sets a compressor for outbound messages.
func RPCDecompressor ¶
func RPCDecompressor(dc compresser.Decompressor) ServerOption
RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages.
func ReadTimeout ¶
func ReadTimeout(t time.Duration) ServerOption
ReadTimeout return a ServerOption which sets the conn's read timeout
func ReaderWindowSize ¶
func ReaderWindowSize(s int32) ServerOption
ReaderWindowSize returns a ServerOption which sets the value for reader window size for most data read once.
func WriteTimeout ¶
func WriteTimeout(t time.Duration) ServerOption
WriteTimeout return a ServerOption which sets the conn's write timeout
type ServerStream ¶
type ServerStream interface { Stream }
ServerStream defines the interface a server stream has to satisfy.
type ServiceConfig ¶
type ServiceConfig struct { // LB is the load balancer the service providers recommends. The balancer specified // via grpc.WithBalancer will override this. LB Balancer // 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. 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.
type 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.
type 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 method info and metadata for a service.
type 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. // It's 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. 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. // It's 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. RecvMsg(m interface{}) error // contains filtered or unexported methods }
Stream defines the common interface a client or server stream has to satisfy.
type 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 handler to create a ClientStream and it is the responsibility of the interceptor to call it. This is an EXPERIMENTAL API.
type 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.
type 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.
type 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.
type 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.
type 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.
type UnaryClientInterceptor ¶
type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error
UnaryClientInterceptor intercepts the execution of a unary RPC on the client. invoker is the handler to complete the RPC and it is the responsibility of the interceptor to call it. This is an EXPERIMENTAL API.
type UnaryHandler ¶
UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal execution of a unary RPC.
type UnaryInvoker ¶
type UnaryInvoker func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error
UnaryInvoker is called by UnaryClientInterceptor to complete RPCs.
type 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.
type 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.
Source Files ¶
- call.go
- conn_accept.go
- conn_dial.go
- dispatcher.go
- error.go
- go17.go
- grpc_balancer.go
- grpc_client_conn.go
- grpc_dial.go
- grpc_state_manager.go
- grpc_stream_api.go
- interceptor.go
- meta_util.go
- notify_regist.go
- option.go
- option_call.go
- option_dial.go
- packet.pb.go
- parser.go
- plugin.go
- pool.go
- put_buf.go
- recv_buf.go
- rpc_util.go
- server.go
- service_regist.go
- session_oneway.go
- session_stream_client.go
- session_stream_server.go
- session_unary.go
Directories ¶
Path | Synopsis |
---|---|
Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks.
|
Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks. |
benchresult
To format the benchmark result: go run benchmark/benchresult/main.go resultfile To see the performance change based on a old result: go run benchmark/benchresult/main.go resultfile_old resultfile It will print the comparison result of intersection benchmarks between two files.
|
To format the benchmark result: go run benchmark/benchresult/main.go resultfile To see the performance change based on a old result: go run benchmark/benchresult/main.go resultfile_old resultfile It will print the comparison result of intersection benchmarks between two files. |
latency
Package latency provides wrappers for net.Conn, net.Listener, and net.Dialers, designed to interoperate to inject real-world latency into network connections.
|
Package latency provides wrappers for net.Conn, net.Listener, and net.Dialers, designed to interoperate to inject real-world latency into network connections. |
Package credentials implements various credentials supported by gRPC library, which encapsulate all the state needed by a client to authenticate with a server and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call.
|
Package credentials implements various credentials supported by gRPC library, which encapsulate all the state needed by a client to authenticate with a server and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call. |
oauth
Package oauth implements gRPC credentials using OAuth.
|
Package oauth implements gRPC credentials using OAuth. |
examples
|
|
helloworld/helloworld
Package helloworld is a generated protocol buffer package.
|
Package helloworld is a generated protocol buffer package. |
route_guide/client
Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries to perform unary, client streaming, server streaming and full duplex RPCs.
|
Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries to perform unary, client streaming, server streaming and full duplex RPCs. |
route_guide/routeguide
Package routeguide is a generated protocol buffer package.
|
Package routeguide is a generated protocol buffer package. |
route_guide/server
Package main implements a simple gRPC server that demonstrates how to use gRPC-Go libraries to perform unary, client streaming, server streaming and full duplex RPCs.
|
Package main implements a simple gRPC server that demonstrates how to use gRPC-Go libraries to perform unary, client streaming, server streaming and full duplex RPCs. |
Package grpclog defines logging for grpc.
|
Package grpclog defines logging for grpc. |
glogger
Package glogger defines glog-based logging for grpc.
|
Package glogger defines glog-based logging for grpc. |
Package internal contains gRPC-internal code, to avoid polluting the godoc of the top-level grpc package.
|
Package internal contains gRPC-internal code, to avoid polluting the godoc of the top-level grpc package. |
backoff
Package backoff implement the backoff strategy for gRPC.
|
Package backoff implement the backoff strategy for gRPC. |
envconfig
Package envconfig contains grpc settings configured by environment variables.
|
Package envconfig contains grpc settings configured by environment variables. |
grpcrand
Package grpcrand implements math/rand functions in a concurrent-safe way with a global random source, independent of math/rand's global source.
|
Package grpcrand implements math/rand functions in a concurrent-safe way with a global random source, independent of math/rand's global source. |
grpcsync
Package grpcsync implements additional synchronization primitives built upon the sync package.
|
Package grpcsync implements additional synchronization primitives built upon the sync package. |
leakcheck
Package leakcheck contains functions to check leaked goroutines.
|
Package leakcheck contains functions to check leaked goroutines. |
syscall
Package syscall provides functionalities that grpc uses to get low-level operating system stats/info.
|
Package syscall provides functionalities that grpc uses to get low-level operating system stats/info. |