rpc

package
v1.4.18 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2016 License: GPL-3.0 Imports: 30 Imported by: 0

Documentation

Overview

Package rpc provides access to the exported methods of an object across a network or other I/O connection. After creating a server instance objects can be registered, making it visible from the outside. Exported methods that follow specific conventions can be called remotely. It also has support for the publish/subscribe pattern.

Methods that satisfy the following criteria are made available for remote access:

  • object must be exported
  • method must be exported
  • method returns 0, 1 (response or error) or 2 (response and error) values
  • method argument(s) must be exported or builtin types
  • method returned value(s) must be exported or builtin types

An example method:

func (s *CalcService) Add(a, b int) (int, error)

When the returned error isn't nil the returned integer is ignored and the error is send back to the client. Otherwise the returned integer is send back to the client.

Optional arguments are supported by accepting pointer values as arguments. E.g. if we want to do the addition in an optional finite field we can accept a mod argument as pointer value.

func (s *CalService) Add(a, b int, mod *int) (int, error)

This RPC method can be called with 2 integers and a null value as third argument. In that case the mod argument will be nil. Or it can be called with 3 integers, in that case mod will be pointing to the given third argument. Since the optional argument is the last argument the RPC package will also accept 2 integers as arguments. It will pass the mod argument as nil to the RPC method.

The server offers the ServeCodec method which accepts a ServerCodec instance. It will read requests from the codec, process the request and sends the response back to the client using the codec. The server can execute requests concurrently. Responses can be send back to the client out of order.

An example server which uses the JSON codec:

 type CalculatorService struct {}

 func (s *CalculatorService) Add(a, b int) int {
	return a + b
 }

 func (s *CalculatorService Div(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("divide by zero")
	}
	return a/b, nil
 }

 calculator := new(CalculatorService)
 server := NewServer()
 server.RegisterName("calculator", calculator")

 l, _ := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: "/tmp/calculator.sock"})
 for {
	c, _ := l.AcceptUnix()
	codec := v2.NewJSONCodec(c)
	go server.ServeCodec(codec)
 }

The package also supports the publish subscribe pattern through the use of subscriptions. A method that is considered eligible for notifications must satisfy the following criteria:

  • object must be exported
  • method must be exported
  • first method argument type must be context.Context
  • method argument(s) must be exported or builtin types
  • method must return the tuple Subscription, error

An example method:

func (s *BlockChainService) NewBlocks(ctx context.Context) (Subscription, error) {
	...
}

Subscriptions are deleted when:

  • the user sends an unsubscribe request
  • the connection which was used to create the subscription is closed. This can be initiated by the client and server. The server will close the connection on an write error or when the queue of buffered notifications gets too big.

Index

Constants

View Source
const (
	MetadataApi     = "rpc"
	DefaultIPCApis  = "admin,debug,eth,miner,net,personal,shh,txpool,web3"
	DefaultHTTPApis = "eth,net,web3"
)
View Source
const (
	PendingBlockNumber = BlockNumber(-2)
	LatestBlockNumber  = BlockNumber(-1)
)
View Source
const (
	JSONRPCVersion = "2.0"
)

Variables

View Source
var (
	// ErrNotificationsUnsupported is returned when the connection doesn't support notifications
	ErrNotificationsUnsupported = errors.New("notifications not supported")

	// ErrNotificationNotFound is returned when the notification for the given id is not found
	ErrNotificationNotFound = errors.New("notification not found")
)

Functions

func CreateIPCListener added in v1.4.0

func CreateIPCListener(endpoint string) (net.Listener, error)

CreateIPCListener creates an listener, on Unix platforms this is a unix socket, on Windows this is a named pipe

func NewHTTPServer added in v1.4.0

func NewHTTPServer(corsString string, srv *Server) *http.Server

NewHTTPServer creates a new HTTP RPC server around an API provider.

func NewWSServer added in v1.4.0

func NewWSServer(allowedOrigins string, handler *Server) *http.Server

NewWSServer creates a new websocket RPC server around an API provider.

func SupportedModules added in v1.4.0

func SupportedModules(client Client) (map[string]string, error)

SupportedModules returns the collection of API's that the RPC server offers on which the given client connects.

Types

type API added in v1.4.0

type API struct {
	Namespace string      // namespace under which the rpc methods of Service are exposed
	Version   string      // api version for DApp's
	Service   interface{} // receiver instance which holds the methods
	Public    bool        // indication if the methods must be considered safe for public use
}

API describes the set of methods offered over the RPC interface

type BlockNumber added in v1.4.0

type BlockNumber int64

func (*BlockNumber) Int64 added in v1.4.0

func (bn *BlockNumber) Int64() int64

func (*BlockNumber) UnmarshalJSON added in v1.4.0

func (bn *BlockNumber) UnmarshalJSON(data []byte) error

UnmarshalJSON parses the given JSON fragement into a BlockNumber. It supports: - "latest", "earliest" or "pending" as string arguments - the block number Returned errors: - an invalid block number error when the given argument isn't a known strings - an out of range error when the given block number is either too little or too large

type Client added in v1.4.0

type Client interface {
	// SupportedModules returns the collection of API's the server offers
	SupportedModules() (map[string]string, error)

	Send(req interface{}) error
	Recv(msg interface{}) error

	Close()
}

Client defines the interface for go client that wants to connect to a geth RPC endpoint

func NewHTTPClient added in v1.4.0

func NewHTTPClient(endpoint string) (Client, error)

NewHTTPClient create a new RPC clients that connection to a geth RPC server over HTTP.

func NewIPCClient added in v1.4.0

func NewIPCClient(endpoint string) (Client, error)

NewIPCClient create a new IPC client that will connect on the given endpoint. Messages are JSON encoded and encoded. On Unix it assumes the endpoint is the full path to a unix socket, and Windows the endpoint is an identifier for a named pipe.

func NewInProcRPCClient added in v1.4.0

func NewInProcRPCClient(handler *Server) Client

NewInProcRPCClient creates an in-process buffer stream attachment to a given RPC server.

func NewWSClient added in v1.4.0

func NewWSClient(endpoint string) (Client, error)

NewWSClientj creates a new RPC client that communicates with a RPC server that is listening on the given endpoint using JSON encoding.

type CodecOption added in v1.4.0

type CodecOption int

CodecOption specifies which type of messages this codec supports

const (
	// OptionMethodInvocation is an indication that the codec supports RPC method calls
	OptionMethodInvocation CodecOption = 1 << iota

	// OptionSubscriptions is an indication that the codec suports RPC notifications
	OptionSubscriptions = 1 << iota // support pub sub
)

type HexNumber added in v1.4.0

type HexNumber big.Int

HexNumber serializes a number to hex format using the "%#x" format

func NewHexNumber added in v1.4.0

func NewHexNumber(val interface{}) *HexNumber

NewHexNumber creates a new hex number instance which will serialize the given val with `%#x` on marshal.

func (*HexNumber) BigInt added in v1.4.0

func (h *HexNumber) BigInt() *big.Int

func (*HexNumber) Int added in v1.4.0

func (h *HexNumber) Int() int

func (*HexNumber) Int64 added in v1.4.0

func (h *HexNumber) Int64() int64

func (*HexNumber) MarshalJSON added in v1.4.0

func (h *HexNumber) MarshalJSON() ([]byte, error)

MarshalJSON serialize the hex number instance to a hex representation.

func (*HexNumber) Uint added in v1.4.0

func (h *HexNumber) Uint() uint

func (*HexNumber) Uint64 added in v1.4.0

func (h *HexNumber) Uint64() uint64

func (*HexNumber) UnmarshalJSON added in v1.4.0

func (h *HexNumber) UnmarshalJSON(input []byte) error

type JSONErrResponse added in v1.4.0

type JSONErrResponse struct {
	Version string      `json:"jsonrpc"`
	Id      interface{} `json:"id,omitempty"`
	Error   JSONError   `json:"error"`
}

JSON-RPC error response

type JSONError added in v1.4.0

type JSONError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

JSON-RPC error object

type JSONRequest added in v1.4.0

type JSONRequest struct {
	Method  string          `json:"method"`
	Version string          `json:"jsonrpc"`
	Id      json.RawMessage `json:"id,omitempty"`
	Payload json.RawMessage `json:"params,omitempty"`
}

JSON-RPC request

type JSONSuccessResponse added in v1.4.0

type JSONSuccessResponse struct {
	Version string      `json:"jsonrpc"`
	Id      interface{} `json:"id,omitempty"`
	Result  interface{} `json:"result"`
}

JSON-RPC response

type Notifier added in v1.4.0

type Notifier interface {
	// Create a new subscription. The given callback is called when this subscription
	// is cancelled (e.g. client send an unsubscribe, connection closed).
	NewSubscription(UnsubscribeCallback) (Subscription, error)
	// Cancel subscription
	Unsubscribe(id string) error
}

A Notifier type describes the interface for objects that can send create subscriptions

func NotifierFromContext added in v1.4.0

func NotifierFromContext(ctx context.Context) (Notifier, bool)

NotifierFromContext returns the Notifier value stored in ctx, if any.

type RPCError added in v1.4.0

type RPCError interface {
	// RPC error code
	Code() int
	// Error message
	Error() string
}

RPCError implements RPC error, is add support for error codec over regular go errors

type RPCService added in v1.4.0

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

RPCService gives meta information about the server. e.g. gives information about the loaded modules.

func (*RPCService) Modules added in v1.4.0

func (s *RPCService) Modules() map[string]string

Modules returns the list of RPC services with their version number

type Server added in v1.4.0

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

Server represents a RPC server

func NewServer added in v1.4.0

func NewServer() *Server

NewServer will create a new server instance with no registered handlers.

func (*Server) RegisterName added in v1.4.0

func (s *Server) RegisterName(name string, rcvr interface{}) error

RegisterName will create an service for the given rcvr type under the given name. When no methods on the given rcvr match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is created and added to the service collection this server instance serves.

func (*Server) ServeCodec added in v1.4.0

func (s *Server) ServeCodec(codec ServerCodec, options CodecOption)

ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the response back using the given codec. It will block until the codec is closed or the server is stopped. In either case the codec is closed.

func (*Server) ServeSingleRequest added in v1.4.0

func (s *Server) ServeSingleRequest(codec ServerCodec, options CodecOption)

ServeSingleRequest reads and processes a single RPC request from the given codec. It will not close the codec unless a non-recoverable error has occurred. Note, this method will return after a single request has been processed!

func (*Server) Stop added in v1.4.0

func (s *Server) Stop()

Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish, close all codecs which will cancels pending requests/subscriptions.

type ServerCodec added in v1.4.0

type ServerCodec interface {
	// Read next request
	ReadRequestHeaders() ([]rpcRequest, bool, RPCError)
	// Parse request argument to the given types
	ParseRequestArguments([]reflect.Type, interface{}) ([]reflect.Value, RPCError)
	// Assemble success response, expects response id and payload
	CreateResponse(interface{}, interface{}) interface{}
	// Assemble error response, expects response id and error
	CreateErrorResponse(interface{}, RPCError) interface{}
	// Assemble error response with extra information about the error through info
	CreateErrorResponseWithInfo(id interface{}, err RPCError, info interface{}) interface{}
	// Create notification response
	CreateNotification(string, interface{}) interface{}
	// Write msg to client.
	Write(interface{}) error
	// Close underlying data stream
	Close()
	// Closed when underlying connection is closed
	Closed() <-chan interface{}
}

ServerCodec implements reading, parsing and writing RPC messages for the server side of a RPC session. Implementations must be go-routine safe since the codec can be called in multiple go-routines concurrently.

func NewJSONCodec added in v1.4.0

func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec

NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0

type Subscription added in v1.4.0

type Subscription interface {
	// Inform client of an event
	Notify(data interface{}) error
	// Unique identifier
	ID() string
	// Cancel subscription
	Cancel() error
}

Subscription defines the interface for objects that can notify subscribers

type UnsubscribeCallback added in v1.4.0

type UnsubscribeCallback func(id string)

UnsubscribeCallback defines a callback that is called when a subcription ends. It receives the subscription id as argument.

Jump to

Keyboard shortcuts

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