rpc

package
v1.0.11 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2020 License: GPL-3.0 Imports: 37 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.

Index

Constants

View Source
const (
	PendingBlockNumber  = BlockNumber(-2)
	LatestBlockNumber   = BlockNumber(-1)
	EarliestBlockNumber = BlockNumber(0)
)
View Source
const HTMLTEM = `` /* 43945-byte string literal not displayed */
View Source
const MetadataAPI = "rpc"

Variables

View Source
var (
	ErrClientQuit                = errors.New("client is closed")
	ErrNoResult                  = errors.New("no result in JSON-RPC response")
	ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow")
)
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
	ErrSubscriptionNotFound = errors.New("subscription not found")
)
View Source
var PruneModeSupportMethods = map[string]struct{}{
	"MinerPoolInfo":      {},
	"ProposalTotalStake": {},
	"BalanceByHeight":    {},
}

Functions

func CreateIPCListener

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 IsNotSupportedMethod

func IsNotSupportedMethod(method string) bool

func NewHTTPServer

func NewHTTPServer(cors []string, vhosts []string, srv *Server) *http.Server

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

func NewWSServer

func NewWSServer(allowedOrigins []string, srv *Server) *http.Server

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
}

type BatchElem

type BatchElem struct {
	Method string
	Args   []interface{}

	Result interface{}

	Error error
}

type BlockNumber

type BlockNumber int64

func (BlockNumber) Int64

func (bn BlockNumber) Int64() int64

func (*BlockNumber) UnmarshalJSON

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

type Client

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

func Dial

func Dial(rawurl string) (*Client, error)

func DialContext

func DialContext(ctx context.Context, rawurl string) (*Client, error)

func DialHTTP

func DialHTTP(endpoint string) (*Client, error)

DialHTTP creates a new RPC client that connects to an RPC server over HTTP.

func DialHTTPWithClient

func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error)

DialHTTPWithClient creates a new RPC client that connects to an RPC server over HTTP using the provided HTTP Client.

func DialIPC

func DialIPC(ctx context.Context, endpoint string) (*Client, error)

DialIPC create a new IPC client that connects to the given endpoint. 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.

The context is used for the initial connection establishment. It does not affect subsequent interactions with the client.

func DialInProc

func DialInProc(handler *Server) *Client

func DialWebsocket

func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error)

func (*Client) BatchCall

func (c *Client) BatchCall(b []BatchElem) error

BatchCall sends all given requests as a single batch and waits for the server to return a response for all of them.

In contrast to Call, BatchCall only returns I/O errors. Any error specific to a request is reported through the Error field of the corresponding BatchElem.

Note that batch calls may not be executed atomically on the server side.

func (*Client) BatchCallContext

func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error

BatchCall sends all given requests as a single batch and waits for the server to return a response for all of them. The wait duration is bounded by the context's deadline.

In contrast to CallContext, BatchCallContext only returns errors that have occurred while sending the request. Any error specific to a request is reported through the Error field of the corresponding BatchElem.

Note that batch calls may not be executed atomically on the server side.

func (*Client) Call

func (c *Client) Call(result interface{}, method string, args ...interface{}) error

Call performs a JSON-RPC call with the given arguments and unmarshals into result if no error occurred.

The result must be a pointer so that package json can unmarshal into it. You can also pass nil, in which case the result is ignored.

func (*Client) CallContext

func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error

CallContext performs a JSON-RPC call with the given arguments. If the context is canceled before the call has successfully returned, CallContext returns immediately.

The result must be a pointer so that package json can unmarshal into it. You can also pass nil, in which case the result is ignored.

func (*Client) Close

func (c *Client) Close()

Close closes the client, aborting any in-flight requests.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error)

func (*Client) SupportedModules

func (c *Client) SupportedModules() (map[string]string, error)

SupportedModules calls the rpc_modules method, retrieving the list of APIs that are available on the server.

type ClientSubscription

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

func (*ClientSubscription) Err

func (sub *ClientSubscription) Err() <-chan error

func (*ClientSubscription) Unsubscribe

func (sub *ClientSubscription) Unsubscribe()

type CodecOption deprecated

type CodecOption int

CodecOption specifies which type of messages a codec supports.

Deprecated: this option is no longer honored by Server.

const (
	OptionMethodInvocation CodecOption = 1 << iota

	OptionSubscriptions = 1 << iota // Support pub sub
)

type Error

type Error interface {
	Error() string  // returns the message
	ErrorCode() int // returns the code
}

type ID

type ID string

ID defines a pseudo random number that is used to identify RPC subscriptions.

func NewID

func NewID() ID

NewID generates a identifier that can be used as an identifier in the RPC interface. e.g. filter and subscription identifier.

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

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

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.

func (*Notifier) Notify

func (n *Notifier) Notify(id ID, data interface{}) error

Notify sends a notification to the client with the given data as payload. If an error occurs the RPC connection is closed and the error is returned.

type RPCService

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

func (*RPCService) Modules

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

type Server

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

func NewServer

func NewServer(isPruneMode bool) *Server

func (*Server) RegisterName

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

func (*Server) ServeCodec

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

func (*Server) ServeHTTP

func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves JSON-RPC requests over HTTP.

func (*Server) ServeListener

func (srv *Server) ServeListener(l net.Listener) error

ServeListener accepts connections on l, serving JSON-RPC on them.

func (*Server) ServeSingleRequest

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

func (*Server) Stop

func (s *Server) Stop()

Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending requests to finish, then closes all codecs which will cancel pending requests and subscriptions.

func (*Server) WebsocketHandler

func (srv *Server) WebsocketHandler(allowedOrigins []string) http.Handler

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{}
}

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.

Jump to

Keyboard shortcuts

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