rpc

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2026 License: BSD-3-Clause Imports: 18 Imported by: 35

Documentation

Overview

Package rpc provides protocol-agnostic RPC client/server abstractions. Applications use these interfaces without caring about the underlying transport (ZAP, gRPC, JSON-RPC, etc.).

ZAP is the default transport. Use build tags to enable alternatives:

go build -tags grpc  # Enable gRPC transport
go build -tags json  # Enable JSON-RPC transport

Package rpc provides protocol-agnostic RPC abstractions for the Lux ecosystem.

Transport Selection

ZAP is the default transport, optimized for high-frequency trading and VM communication. Use build tags to enable alternative transports:

go build              # ZAP only (default, fastest)
go build -tags grpc   # Enable gRPC transport
go build -tags json   # Enable JSON-RPC transport

Usage

Client usage:

client, err := rpc.Dial(ctx, "localhost:9000")
if err != nil {
    log.Fatal(err)
}
defer client.Close()

// Structured call (auto JSON encoding)
var result MyResponse
err = client.Call(ctx, "Service.Method", &MyRequest{...}, &result)

// Raw call (zero-copy, for HFT)
resp, err := client.CallRaw(ctx, "trade", orderBytes)

Server usage:

server, err := rpc.Listen(":9000")
if err != nil {
    log.Fatal(err)
}

// Register raw handler for low-latency
server.RegisterRaw("trade", func(ctx context.Context, payload []byte) ([]byte, error) {
    // Process order with zero-copy
    return processOrder(payload)
})

server.Serve(ctx)

Performance

ZAP transport benchmarks (Apple M1 Max):

BenchmarkRoundTrip/1KB    46ns encode, 19ns decode, 0 allocs
BenchmarkRoundTrip/100KB  1.6μs encode, 19ns decode, 0 allocs
BenchmarkRoundTrip/1MB    20μs encode, 19ns decode, 0 allocs

ZAP vs Protobuf comparison:

1KB:   7.9x faster encode, 19.8x faster decode
100KB: 8.5x faster encode, 658x faster decode
1MB:   7x faster encode, 2866x faster decode

Architecture

The package separates concerns:

  • client.go: Protocol-agnostic Client and Server interfaces
  • codec.go: Codec interface for message encoding
  • transport.go: Transport registry for build-tag extensibility
  • dial.go: Dial and Listen factory functions
  • zap.go: ZAP transport implementation (default)
  • dial_grpc.go: gRPC transport (requires -tags grpc)

Application code should only depend on the Client/Server interfaces, making transport selection a deployment decision rather than a code change.

Index

Constants

View Source
const (
	TransportZAP  = "zap"  // Zero-copy, default
	TransportGRPC = "grpc" // Google RPC, requires build tag
	TransportJSON = "json" // JSON-RPC over HTTP
)

Transport types

View Source
const DefaultTransport = TransportZAP

DefaultTransport is the default transport type (ZAP)

Variables

View Source
var (
	ErrZAPClosed      = errors.New("zap: connection closed")
	ErrZAPTimeout     = errors.New("zap: request timeout")
	ErrZAPInvalidResp = errors.New("zap: invalid response")
)

Functions

func AvailableTransports

func AvailableTransports() []string

AvailableTransports returns list of available transport types

func CleanlyCloseBody

func CleanlyCloseBody(body io.ReadCloser) error

CleanlyCloseBody drains and closes an HTTP response body to prevent HTTP/2 GOAWAY errors caused by closing bodies with unread data. See: https://github.com/golang/go/issues/46071

func HasTransport

func HasTransport(name string) bool

HasTransport checks if a transport is available

func SendJSONRequest

func SendJSONRequest(
	ctx context.Context,
	uri *url.URL,
	method string,
	params interface{},
	reply interface{},
	options ...Option,
) error

Types

type BinaryCodec

type BinaryCodec struct{}

BinaryCodec passes bytes through unchanged (for pre-encoded data)

func (BinaryCodec) Decode

func (BinaryCodec) Decode(data []byte, v interface{}) error

func (BinaryCodec) Encode

func (BinaryCodec) Encode(v interface{}) ([]byte, error)

type Client

type Client interface {
	// Call makes a synchronous RPC call
	Call(ctx context.Context, method string, args, reply interface{}) error

	// CallRaw makes a call with raw bytes (for zero-copy scenarios)
	CallRaw(ctx context.Context, method string, payload []byte) ([]byte, error)

	// Notify sends a one-way message (no response expected)
	Notify(ctx context.Context, method string, args interface{}) error

	// Close closes the connection
	Close() error
}

Client is the protocol-agnostic RPC client interface. All application code should use this interface.

func Dial

func Dial(ctx context.Context, addr string, opts ...DialOption) (Client, error)

Dial connects to an RPC server using the default transport (ZAP). Use DialWithOptions for transport selection.

type Codec

type Codec interface {
	Encode(v interface{}) ([]byte, error)
	Decode(data []byte, v interface{}) error
}

Codec encodes/decodes RPC messages

var Binary Codec = BinaryCodec{}

Binary is a codec that passes bytes through unchanged

type DialOption

type DialOption func(*dialOptions)

DialOption configures client connections

func WithCodec

func WithCodec(c Codec) DialOption

WithCodec sets a custom codec

func WithTransport

func WithTransport(t string) DialOption

WithTransport explicitly sets the transport type

type EndpointRequester

type EndpointRequester interface {
	SendRequest(ctx context.Context, method string, params interface{}, reply interface{}, options ...Option) error
}

func NewEndpointRequester

func NewEndpointRequester(uri string) EndpointRequester

type JSONCodec

type JSONCodec struct{}

JSONCodec is a JSON-based codec

func (JSONCodec) Decode

func (JSONCodec) Decode(data []byte, v interface{}) error

func (JSONCodec) Encode

func (JSONCodec) Encode(v interface{}) ([]byte, error)

type MessageType

type MessageType uint8

MessageType identifies ZAP message types

const (
	MsgRequest  MessageType = 0x01
	MsgResponse MessageType = 0x02
	MsgError    MessageType = 0x03
	MsgNotify   MessageType = 0x04
)

type Option

type Option func(*Options)

func WithHeader

func WithHeader(key, val string) Option

func WithQueryParam

func WithQueryParam(key, val string) Option

type Options

type Options struct {
	// contains filtered or unexported fields
}

func NewOptions

func NewOptions(ops []Option) *Options

func (*Options) Headers

func (o *Options) Headers() http.Header

func (*Options) QueryParams

func (o *Options) QueryParams() url.Values

type RawHandler

type RawHandler func(ctx context.Context, payload []byte) ([]byte, error)

RawHandler handles raw byte RPC calls (for zero-copy)

type Server

type Server interface {
	// Register registers a service handler
	Register(name string, handler interface{}) error

	// RegisterRaw registers a raw byte handler
	RegisterRaw(method string, handler RawHandler) error

	// Serve starts serving requests (blocks until context cancelled)
	Serve(ctx context.Context) error

	// Close stops the server
	Close() error

	// Addr returns the server's listen address
	Addr() string
}

Server is the protocol-agnostic RPC server interface.

func Listen

func Listen(addr string, opts ...ServerOption) (Server, error)

Listen creates an RPC server listener using the default transport (ZAP).

type ServerOption

type ServerOption func(*serverOptions)

ServerOption configures servers

func WithServerCodec

func WithServerCodec(c Codec) ServerOption

WithServerCodec sets a custom codec for the server

func WithServerTransport

func WithServerTransport(t string) ServerOption

WithServerTransport explicitly sets the transport type for the server

type Transport

type Transport interface {
	io.Closer
	Send(ctx context.Context, data []byte) error
	Recv(ctx context.Context) ([]byte, error)
}

Transport represents the underlying transport mechanism

type ZAPConn

type ZAPConn struct {
	// contains filtered or unexported fields
}

ZAPConn represents a ZAP connection for RPC

func ZAPDial

func ZAPDial(ctx context.Context, addr string) (*ZAPConn, error)

ZAPDial connects to a ZAP server

func (*ZAPConn) Call

func (z *ZAPConn) Call(ctx context.Context, method string, payload []byte) ([]byte, error)

Call makes a ZAP RPC call

func (*ZAPConn) Close

func (z *ZAPConn) Close() error

Close closes the connection

func (*ZAPConn) Notify

func (z *ZAPConn) Notify(ctx context.Context, method string, payload []byte) error

Notify sends a one-way notification (no response expected)

type ZAPHandler

type ZAPHandler interface {
	HandleZAP(ctx context.Context, method string, payload []byte) ([]byte, error)
}

ZAPHandler handles ZAP requests

type ZAPHandlerFunc

type ZAPHandlerFunc func(ctx context.Context, method string, payload []byte) ([]byte, error)

ZAPHandlerFunc is a function adapter for ZAPHandler

func (ZAPHandlerFunc) HandleZAP

func (f ZAPHandlerFunc) HandleZAP(ctx context.Context, method string, payload []byte) ([]byte, error)

type ZAPResponse

type ZAPResponse struct {
	Data []byte
	Err  error
}

ZAPResponse holds a response from a ZAP call

type ZAPServer

type ZAPServer struct {
	// contains filtered or unexported fields
}

ZAPServer handles incoming ZAP RPC requests

func NewZAPServer

func NewZAPServer(listener net.Listener, handler ZAPHandler) *ZAPServer

NewZAPServer creates a new ZAP server

func (*ZAPServer) Addr

func (s *ZAPServer) Addr() net.Addr

Addr returns the listener address

func (*ZAPServer) Close

func (s *ZAPServer) Close() error

Close closes the server

func (*ZAPServer) Serve

func (s *ZAPServer) Serve(ctx context.Context) error

Serve starts serving requests

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL