Documentation
¶
Overview ¶
Package gorpc provides a small Go-to-Go RPC transport for internal services.
It is intentionally not a protobuf, gRPC, Connect, or IDL replacement. Both sides share normal Go request and response types, and the wire protocol uses length-prefixed MessagePack frames over a single full-duplex connection. Once connected, either side can send unary requests and receive responses.
Index ¶
- Constants
- Variables
- func Call[Req, Resp any](ctx context.Context, client *Client, function string, req Req) (Resp, error)
- func MustRegister[Req, Resp any](target any, function string, fn HandlerFunc[Req, Resp])
- func Register[Req, Resp any](target any, function string, fn HandlerFunc[Req, Resp]) error
- type Auth
- type Client
- func Dial(ctx context.Context, network, address string, opts ClientOptions) (*Client, error)
- func NewClient(network, address string, opts ClientOptions) *Client
- func NewTCPClient(address, clientName string, opts ...ClientOptions) *Client
- func NewUnixClient(path, clientName string, opts ...ClientOptions) *Client
- func NewUnixPacketClient(path, clientName string, opts ...ClientOptions) *Client
- func TCPDial(address, clientName string, opts ...ClientOptions) (*Client, error)
- func UnixDial(path, clientName string, opts ...ClientOptions) (*Client, error)
- func UnixPacketDial(path, clientName string, opts ...ClientOptions) (*Client, error)
- func (c *Client) AsyncCall(function string, req any, handler any, correlationID string) error
- func (c *Client) AsyncCallContext(ctx context.Context, function string, req any, handler any, ...) error
- func (c *Client) AsyncCallWithTimeout(function string, req any, handler any, correlationID string, ...) error
- func (c *Client) Call(function string, req any, resp any) error
- func (c *Client) CallContext(ctx context.Context, function string, req any, resp any) error
- func (c *Client) CallWithTimeout(function string, req any, resp any, timeout time.Duration) error
- func (c *Client) Close() error
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) WaitReady(ctx context.Context) error
- type ClientContext
- type ClientFunc
- type ClientOptions
- type Codec
- type Conn
- func (c *Conn) AsyncCall(function string, req any, handler any, correlationID string) error
- func (c *Conn) AsyncCallContext(ctx context.Context, function string, req any, handler any, ...) error
- func (c *Conn) AsyncCallWithTimeout(function string, req any, handler any, correlationID string, ...) error
- func (c *Conn) Call(function string, req any, resp any) error
- func (c *Conn) CallContext(ctx context.Context, function string, req any, resp any) error
- func (c *Conn) CallWithTimeout(function string, req any, resp any, timeout time.Duration) error
- func (c *Conn) ClientName() string
- func (c *Conn) Close() error
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) RemoteAddr() net.Addr
- type Context
- func (c *Context) Call(function string, req any, resp any) error
- func (c *Context) CallContext(ctx context.Context, function string, req any, resp any) error
- func (c *Context) CallWithTimeout(function string, req any, resp any, timeout time.Duration) error
- func (c *Context) ClientName() string
- func (c *Context) Conn() *Conn
- func (c *Context) Function() string
- func (c *Context) LocalAddr() net.Addr
- func (c *Context) RemoteAddr() net.Addr
- func (c *Context) RequestID() uint64
- type Frame
- type FrameType
- type HandlerFunc
- type MessagePackCodec
- type RemoteError
- type Server
- type ServerOptions
Constants ¶
const ( DefaultDialTimeout = 5 * time.Second DefaultWriteTimeout = 10 * time.Second DefaultReconnectMinDelay = 100 * time.Millisecond DefaultReconnectMaxDelay = 5 * time.Second DefaultReconnectJitter = 0.2 DefaultPingInterval = 10 * time.Second DefaultPingTimeout = 3 * time.Second )
Reconnect defaults used by Client when options are unset.
const ( ErrorCodeCanceled = "canceled" ErrorCodeDeadlineExceeded = "deadline_exceeded" ErrorCodeInternal = "internal" ErrorCodeInvalidRequest = "invalid_request" ErrorCodeNotFound = "not_found" )
Remote error codes used by the built-in server and helpers.
const CodecMessagePack = "msgpack"
CodecMessagePack is the v1 MessagePack codec name used during handshake.
const DefaultHandshakeTimeout = 5 * time.Second
DefaultHandshakeTimeout is the default timeout for the initial protocol handshake.
const DefaultMaxFrameSize int64 = 64 * 1024 * 1024
DefaultMaxFrameSize is the default maximum encoded frame size.
const ProtocolVersion uint16 = 1
ProtocolVersion is the current GoRPC wire protocol version.
Variables ¶
var ( ErrClosed = errors.New("gorpc: closed") ErrAuthentication = errors.New("gorpc: authentication failed") ErrDuplicateFunction = errors.New("gorpc: duplicate function") ErrInvalidFunction = errors.New("gorpc: invalid function") ErrInvalidHandler = errors.New("gorpc: invalid handler") ErrInvalidResponse = errors.New("gorpc: invalid response") )
Common GoRPC errors.
var ( ErrFrameTooLarge = errors.New("gorpc: frame too large") ErrProtocol = errors.New("gorpc: protocol error") )
Frame read/write errors.
Functions ¶
func Call ¶
func Call[Req, Resp any](ctx context.Context, client *Client, function string, req Req) (Resp, error)
Call performs a typed unary request/response call.
func MustRegister ¶
func MustRegister[Req, Resp any](target any, function string, fn HandlerFunc[Req, Resp])
MustRegister is Register that panics on error.
func Register ¶
func Register[Req, Resp any](target any, function string, fn HandlerFunc[Req, Resp]) error
Register binds a typed unary handler to a function name. The target can be a *Server, for functions the accepted side handles, or a *Client, for functions the dialing side handles after the connection is established.
Types ¶
type Auth ¶ added in v0.2.0
type Auth struct {
// contains filtered or unexported fields
}
Auth configures optional connection authentication.
func SharedSecret ¶ added in v0.2.0
SharedSecret enables HMAC-SHA256 challenge/response authentication.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the dialing side of a long-lived full-duplex GoRPC connection. It can send requests, register functions for the accepted side to call, and reconnects automatically after connection loss until Close is called.
func Dial ¶
Dial connects to a GoRPC server, completes the protocol handshake, and starts background reconnect monitoring.
func NewClient ¶ added in v0.3.0
func NewClient(network, address string, opts ClientOptions) *Client
NewClient creates a client without connecting it. Use this when the dialing side needs to register functions before the accepted side can call them.
func NewTCPClient ¶ added in v0.3.0
func NewTCPClient(address, clientName string, opts ...ClientOptions) *Client
NewTCPClient creates a TCP client without connecting it.
func NewUnixClient ¶ added in v0.3.0
func NewUnixClient(path, clientName string, opts ...ClientOptions) *Client
NewUnixClient creates a Unix socket client without connecting it.
func NewUnixPacketClient ¶ added in v0.3.0
func NewUnixPacketClient(path, clientName string, opts ...ClientOptions) *Client
NewUnixPacketClient creates a Unix packet socket client without connecting it.
func TCPDial ¶ added in v0.2.0
func TCPDial(address, clientName string, opts ...ClientOptions) (*Client, error)
TCPDial connects to address using TCP and reconnects automatically until Close is called.
func UnixDial ¶ added in v0.2.0
func UnixDial(path, clientName string, opts ...ClientOptions) (*Client, error)
UnixDial connects to path using a Unix socket and reconnects automatically until Close is called.
func UnixPacketDial ¶ added in v0.2.0
func UnixPacketDial(path, clientName string, opts ...ClientOptions) (*Client, error)
UnixPacketDial connects to path using a Unix packet socket and reconnects automatically until Close is called.
func (*Client) AsyncCall ¶ added in v0.2.0
AsyncCall sends a unary request and invokes handler when the response arrives.
func (*Client) AsyncCallContext ¶ added in v0.2.0
func (c *Client) AsyncCallContext(ctx context.Context, function string, req any, handler any, correlationID string) error
AsyncCallContext sends a unary request and invokes handler when the response arrives. The context only controls waiting for a connection and writing the request frame.
func (*Client) AsyncCallWithTimeout ¶ added in v0.2.0
func (c *Client) AsyncCallWithTimeout(function string, req any, handler any, correlationID string, timeout time.Duration) error
AsyncCallWithTimeout sends a unary request using a timeout while waiting for a connection and writing the request frame. The response handler runs later.
func (*Client) Call ¶ added in v0.2.0
Call performs a unary request/response call using context.Background.
func (*Client) CallContext ¶ added in v0.2.0
CallContext performs a unary request/response call. If the client is reconnecting, CallContext waits for the next connection until ctx is canceled.
func (*Client) CallWithTimeout ¶ added in v0.2.0
CallWithTimeout performs a unary request/response call with a timeout.
type ClientContext ¶ added in v0.2.0
type ClientContext interface {
CorrelationID() string
RequestID() uint64
Function() string
Error() error
}
ClientContext is passed to asynchronous response handlers for requests made by either a Client or an accepted Conn.
type ClientFunc ¶ added in v0.2.0
ClientFunc is the typed function shape returned by Function.
type ClientOptions ¶
type ClientOptions struct {
ClientName string
Codec Codec
MaxFrameSize int64
HandshakeTimeout time.Duration
Auth Auth
DialTimeout time.Duration
WriteTimeout time.Duration
Logger *slog.Logger
Dialer *net.Dialer
ReconnectMinDelay time.Duration
ReconnectMaxDelay time.Duration
ReconnectJitter float64
PingInterval time.Duration
PingTimeout time.Duration
}
ClientOptions configures Dial and the network-specific dial helpers.
type Codec ¶
type Codec interface {
Name() string
Marshal(v any) ([]byte, error)
Unmarshal(data []byte, v any) error
}
Codec marshals frame envelopes and function payloads.
type Conn ¶ added in v0.3.0
type Conn struct {
// contains filtered or unexported fields
}
Conn is one accepted GoRPC connection. A Conn can receive requests through server-registered functions and can also initiate requests back to the client over the same full-duplex connection.
func (*Conn) AsyncCall ¶ added in v0.3.0
AsyncCall sends a unary request to the connected client and invokes handler when the response arrives.
func (*Conn) AsyncCallContext ¶ added in v0.3.0
func (c *Conn) AsyncCallContext(ctx context.Context, function string, req any, handler any, correlationID string) error
AsyncCallContext sends a unary request to the connected client and invokes handler when the response arrives.
func (*Conn) AsyncCallWithTimeout ¶ added in v0.3.0
func (c *Conn) AsyncCallWithTimeout(function string, req any, handler any, correlationID string, timeout time.Duration) error
AsyncCallWithTimeout sends a unary request to the connected client using a timeout while writing the request frame. The response handler runs later.
func (*Conn) Call ¶ added in v0.3.0
Call performs a unary request/response call to the connected client.
func (*Conn) CallContext ¶ added in v0.3.0
CallContext performs a unary request/response call to the connected client.
func (*Conn) CallWithTimeout ¶ added in v0.3.0
CallWithTimeout performs a unary request/response call to the connected client with a timeout.
func (*Conn) ClientName ¶ added in v0.3.0
ClientName returns the self-reported client name from the connection handshake. It is useful for logs and metrics, but is not authenticated.
func (*Conn) Close ¶ added in v0.3.0
Close closes the accepted connection, cancels active inbound handlers, and fails pending outbound calls.
func (*Conn) RemoteAddr ¶ added in v0.3.0
RemoteAddr returns the peer address for the connection.
type Context ¶ added in v0.2.0
Context is the request-scoped context passed to server handlers.
func (*Context) Call ¶ added in v0.3.0
Call performs a unary request/response call back over the same accepted connection that delivered this request.
func (*Context) CallContext ¶ added in v0.3.0
CallContext performs a unary request/response call back over the same accepted connection.
func (*Context) CallWithTimeout ¶ added in v0.3.0
CallWithTimeout performs a unary request/response call back over the same accepted connection with a timeout.
func (*Context) ClientName ¶ added in v0.2.0
ClientName returns the self-reported client name from the connection handshake. It is useful for logs and metrics, but is not authenticated.
func (*Context) Conn ¶ added in v0.3.0
Conn returns the accepted connection that delivered this request when the handler is running on a Server. Client-side handlers return nil here because they can already call back through their Client.
func (*Context) Function ¶ added in v0.2.0
Function returns the remote function name for the request.
func (*Context) RemoteAddr ¶ added in v0.2.0
RemoteAddr returns the peer address for the connection.
type Frame ¶
type Frame struct {
Version uint16 `msgpack:"version"`
Type FrameType `msgpack:"type"`
RequestID uint64 `msgpack:"request_id,omitempty"`
Function string `msgpack:"function,omitempty"`
DeadlineUnixNano int64 `msgpack:"deadline_unix_nano,omitempty"`
Payload []byte `msgpack:"payload,omitempty"`
}
Frame is the v1 wire envelope. It is MessagePack-encoded and written with a 4-byte big-endian length prefix.
type FrameType ¶
type FrameType uint8
FrameType identifies the kind of message carried by a frame.
type HandlerFunc ¶
HandlerFunc is the typed function shape used by registered unary functions.
type MessagePackCodec ¶
type MessagePackCodec struct{}
MessagePackCodec is the default v1 codec.
func (MessagePackCodec) Marshal ¶
func (MessagePackCodec) Marshal(v any) ([]byte, error)
Marshal encodes v as MessagePack.
func (MessagePackCodec) Name ¶
func (MessagePackCodec) Name() string
Name returns the handshake name for MessagePackCodec.
type RemoteError ¶
type RemoteError struct {
Code string `msgpack:"code" json:"code"`
Message string `msgpack:"message" json:"message"`
Details map[string]any `msgpack:"details,omitempty" json:"details,omitempty"`
}
RemoteError is sent in FrameError payloads and returned by callers when the server handled the request but rejected or failed it.
func NewRemoteError ¶
func NewRemoteError(code, message string, details map[string]any) *RemoteError
NewRemoteError creates a structured error suitable for returning from a handler.
func (*RemoteError) Error ¶
func (e *RemoteError) Error() string
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server accepts GoRPC connections, dispatches registered functions, and exposes accepted connections that can initiate requests back to the dialing side.
func NewServer ¶
func NewServer(opts ServerOptions) *Server
NewServer creates a Server with default codec and limits where options are unset.
func (*Server) Connections ¶ added in v0.3.0
Connections returns a snapshot of currently accepted connections.
func (*Server) ServeListener ¶ added in v0.2.0
ServeListener accepts GoRPC connections from ln until Shutdown is called or the listener returns an unrecoverable error.
func (*Server) ServeTCP ¶ added in v0.2.0
ServeTCP listens on address with the "tcp" network and serves GoRPC connections.
func (*Server) ServeUnix ¶ added in v0.2.0
ServeUnix listens on path with the "unix" network and serves GoRPC connections.
func (*Server) ServeUnixPacket ¶ added in v0.2.0
ServeUnixPacket listens on path with the "unixpacket" network and serves GoRPC connections.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
inventory/client
command
Package main runs the GoRPC Inventory example client.
|
Package main runs the GoRPC Inventory example client. |
|
inventory/server
command
Package main runs the GoRPC Inventory example server.
|
Package main runs the GoRPC Inventory example server. |