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 sent 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
- Variables
- func CreateIPCListener(endpoint string) (net.Listener, error)
- func NewHTTPServer(cors []string, vhosts []string, allowIP []string, behindreverseproxy bool, ...) *http.Serverdeprecated
- func NewWSServer(allowedOrigins []string, allowedIP []string, reverseproxy bool, srv *Server) *http.Serverdeprecated
- type API
- type BlockNumber
- type CodecOption
- type Error
- type ID
- type JsonError
- type Notifier
- type RPCService
- type Server
- func (s *Server) RegisterName(name string, rcvr interface{}) error
- func (s *Server) ServeCodec(codec ServerCodec, options CodecOption)
- func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (srv *Server) ServeListener(l net.Listener) error
- func (s *Server) ServeSingleRequest(codec ServerCodec, options CodecOption)
- func (s *Server) Stop()
- func (srv *Server) WebsocketHandler(allowedOrigins []string, allowedIP []string, reverseproxy bool) http.Handler
- type ServerCodec
- type Subscription
Constants ¶
const ( JsonrpcVersion = "2.0" ServiceMethodSeparator = "_" SubscribeMethodSuffix = "_subscribe" UnsubscribeMethodSuffix = "_unsubscribe" NotificationMethodSuffix = "_subscription" )
const ( PendingBlockNumber = BlockNumber(-2) LatestBlockNumber = BlockNumber(-1) EarliestBlockNumber = BlockNumber(0) )
const MetadataApi = "rpc"
Variables ¶
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 ErrSubscriptionNotFound = errors.New("subscription not found") )
Functions ¶
func CreateIPCListener ¶
CreateIPCListener creates an listener, on Unix platforms this is a unix socket, on Windows this is a named pipe
Types ¶
type API ¶
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 ¶
type BlockNumber int64
func (BlockNumber) Int64 ¶
func (bn BlockNumber) Int64() int64
func (*BlockNumber) UnmarshalJSON ¶
func (bn *BlockNumber) UnmarshalJSON(data []byte) error
UnmarshalJSON parses the given JSON fragment 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 CodecOption ¶
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 ID ¶
type ID string
ID defines a pseudo random number that is used to identify RPC subscriptions.
type Notifier ¶
type Notifier struct {
// contains filtered or unexported fields
}
Notifier is tight to a RPC connection that supports subscriptions. Server callbacks use the notifier to send notifications.
func NotifierFromContext ¶
NotifierFromContext returns the Notifier value stored in ctx, if any.
func (*Notifier) Closed ¶
func (n *Notifier) Closed() <-chan interface{}
Closed returns a channel that is closed when the RPC connection is closed.
func (*Notifier) CreateSubscription ¶
func (n *Notifier) CreateSubscription() *Subscription
CreateSubscription returns a new subscription that is coupled to the RPC connection. By default subscriptions are inactive and notifications are dropped until the subscription is marked as active. This is done by the RPC server after the subscription ID is send to the client.
type RPCService ¶
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 ¶
func (s *RPCService) Modules() map[string]string
Modules returns the list of RPC services with their version number
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents a RPC server
func NewServer ¶
func NewServer() *Server
NewServer will create a new server instance with no registered handlers.
func (*Server) RegisterName ¶
RegisterName will create a 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 ¶
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) ServeHTTP ¶
func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves JSON-RPC requests over HTTP.
func (*Server) ServeListener ¶
ServeListener accepts connections on l, serving JSON-RPC on them.
func (*Server) ServeSingleRequest ¶
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 ¶
func (s *Server) Stop()
Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish, close all codecs which will cancel pending requests/subscriptions.
func (*Server) WebsocketHandler ¶
func (srv *Server) WebsocketHandler(allowedOrigins []string, allowedIP []string, reverseproxy bool) http.Handler
WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections.
allowedOrigins should be a comma-separated list of allowed origin URLs. To allow connections with any origin, pass "*".
type ServerCodec ¶
type ServerCodec interface { // Read next request ReadRequestHeaders() ([]rpcRequest, bool, Error) // Parse request argument to the given types ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) // Assemble success response, expects response id and payload CreateResponse(id interface{}, reply interface{}) interface{} // Assemble error response, expects response id and error CreateErrorResponse(id interface{}, err Error) interface{} // Assemble error response with extra information about the error through info CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} // Create notification response CreateNotification(id, namespace string, event interface{}) interface{} // Write msg to client. Write(msg 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 NewCodec ¶ added in v1.3.3
func NewCodec(rwc io.ReadWriteCloser, encode, decode func(v interface{}) error) ServerCodec
NewCodec creates a new RPC server codec with support for JSON-RPC 2.0 based on explicitly given encoding and decoding methods.
func NewJSONCodec ¶
func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec
NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0
type Subscription ¶
type Subscription struct { ID ID // contains filtered or unexported fields }
a Subscription is created by a notifier and tight to that notifier. The client can use this subscription to wait for an unsubscribe request for the client, see Err().
func (*Subscription) Err ¶
func (s *Subscription) Err() <-chan error
Err returns a channel that is closed when the client send an unsubscribe request.