types

package
v0.0.0-...-7505a0c Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2019 License: LGPL-3.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	JsonrpcVersion           = "2.0"
	ServiceMethodSeparator   = "_"
	SubscribeMethodSuffix    = "_subscribe"
	UnsubscribeMethodSuffix  = "_unsubscribe"
	NotificationMethodSuffix = "_subscription"
)
View Source
const (
	DefaultHTTPHost = "localhost" // Default host interface for the HTTP RPC server
	DefaultHTTPPort = 15645       // Default TCP port for the HTTP RPC server
	DefaultWSHost   = "localhost" // Default host interface for the websocket RPC server
	DefaultWSPort   = 15646       // Default TCP port for the websocket RPC server
	DefaultRestHost = "localhost" // Default host interface for the REST RPC server
	DefaultRestPort = 55550       // Default TCP port for the REST RPC server
)
View Source
const (
	ContentType = "application/json"
	MetadataApi = "rpc"
)

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
	ErrSubscriptionNotFound = errors.New("subscription not found")
)

Functions

func DefaultHTTPEndpoint

func DefaultHTTPEndpoint() string

DefaultHTTPEndpoint returns the HTTP endpoint used by default.

func DefaultRestEndpoint

func DefaultRestEndpoint() string

DefaultHTTPEndpoint returns the HTTP endpoint used by default.

func DefaultWSEndpoint

func DefaultWSEndpoint() string

DefaultWSEndpoint returns the websocket endpoint used by default.

func IsBatch

func IsBatch(msg json.RawMessage) bool

isBatch returns true when the first non-whitespace characters is '['

Types

type CallbackError

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

logic error, callback returned an error

func (*CallbackError) Error

func (e *CallbackError) Error() string

func (*CallbackError) ErrorCode

func (e *CallbackError) ErrorCode() int

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 Error

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

Error wraps RPC errors, which contain an error code in addition to the message.

type HTTPTimeouts

type HTTPTimeouts struct {
	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body.
	//
	// Because ReadTimeout does not let Handlers make per-request
	// decisions on each request body's acceptable deadline or
	// upload rate, most users will prefer to use
	// ReadHeaderTimeout. It is valid to use them both.
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, ReadHeaderTimeout is used.
	IdleTimeout time.Duration
}

HTTPTimeouts represents the configuration params for the HTTP RPC server.

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 InvalidMessageError

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

received message is invalid

func (*InvalidMessageError) Error

func (e *InvalidMessageError) Error() string

func (*InvalidMessageError) ErrorCode

func (e *InvalidMessageError) ErrorCode() int

type InvalidParamsError

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

unable to decode supplied params, or an invalid number of parameters

func (*InvalidParamsError) Error

func (e *InvalidParamsError) Error() string

func (*InvalidParamsError) ErrorCode

func (e *InvalidParamsError) ErrorCode() int

type InvalidRequestError

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

received message isn't a valid request

func (*InvalidRequestError) Error

func (e *InvalidRequestError) Error() string

func (*InvalidRequestError) ErrorCode

func (e *InvalidRequestError) ErrorCode() int

type JsonrpcMessage

type JsonrpcMessage struct {
	Version string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id,omitempty"`
	Method  string          `json:"method,omitempty"`
	Params  json.RawMessage `json:"params,omitempty"`
	Error   *jsonError      `json:"error,omitempty"`
	Result  json.RawMessage `json:"result,omitempty"`
}

A value of this type can a JSON-RPC request, notification, successful response or error response. Which one it is depends on the fields.

func (*JsonrpcMessage) IsNotification

func (msg *JsonrpcMessage) IsNotification() bool

func (*JsonrpcMessage) IsResponse

func (msg *JsonrpcMessage) IsResponse() bool

func (*JsonrpcMessage) String

func (msg *JsonrpcMessage) String() string

type MethodNotFoundError

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

request is for an unknown service

func (*MethodNotFoundError) Error

func (e *MethodNotFoundError) Error() string

func (*MethodNotFoundError) ErrorCode

func (e *MethodNotFoundError) ErrorCode() int

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
}

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 Request

type Request struct {
	Method string `json:"method"`
	Params string `json:"params"`
}

type Response

type Response struct {
	Success  bool        `json:"success"`
	ErrorMsg string      `json:"errMsg"`
	Data     interface{} `json:"body"`
}

type RestDescription

type RestDescription struct {
	Api reflect.Value
}

type RpcConfig

type RpcConfig struct {

	// IPCEnabled
	IPCEnabled bool `json:"IPCEnabled"`

	// IPCPath is the requested location to place the IPC endpoint. If the path is
	// a simple file name, it is placed inside the data directory (or on the root
	// pipe path on Windows), whereas if it's a resolvable path name (absolute or
	// relative), then that specific path is enforced. An empty path disables IPC.
	IPCPath string `json:"IPCPath,omitempty"`

	// HTTPEnabled
	HTTPEnabled bool `json:"HTTPEnabled"`
	// HTTPHost is the host interface on which to start the HTTP RPC server. If this
	// field is empty, no HTTP API endpoint will be started.
	HTTPHost string `json:"HTTPHost,omitempty"`

	// HTTPPort is the TCP port number on which to start the HTTP RPC server. The
	// default zero value is/ valid and will pick a port number randomly (useful
	// for ephemeral nodes).
	HTTPPort int `json:"HTTPPort"`

	// HTTPCors is the Cross-Origin Resource Sharing header to send to requesting
	// clients. Please be aware that CORS is a browser enforced security, it's fully
	// useless for custom HTTP clients.
	HTTPCors []string `json:"HTTPCors,omitempty"`

	// HTTPVirtualHosts is the list of virtual hostnames which are allowed on incoming requests.
	// This is by default {'localhost'}. Using this prevents attacks like
	// DNS rebinding, which bypasses SOP by simply masquerading as being within the same
	// origin. These attacks do not utilize CORS, since they are not cross-domain.
	// By explicitly checking the Host-header, the server will not allow requests
	// made against the server with a malicious host domain.
	// Requests using ip address directly are not affected
	HTTPVirtualHosts []string `json:"HTTPVirtualHosts,omitempty"`

	// HTTPModules is a list of API modules to expose via the HTTP RPC interface.
	// If the module list is empty, all RPC API endpoints designated public will be
	// exposed.
	HTTPModules []string `json:"HTTPModules,omitempty"`

	// HTTPTimeouts allows for customization of the timeout values used by the HTTP RPC
	// interface.
	HTTPTimeouts HTTPTimeouts `json:"HTTPTimeouts"`

	// WSEnabled
	WSEnabled bool `json:"WSEnabled"`
	// WSHost is the host interface on which to start the websocket RPC server. If
	// this field is empty, no websocket API endpoint will be started.
	WSHost string `json:"WSHost,omitempty"`

	// WSPort is the TCP port number on which to start the websocket RPC server. The
	// default zero value is/ valid and will pick a port number randomly (useful for
	// ephemeral nodes).
	WSPort int `json:"WSPort"`

	// WSOrigins is the list of domain to accept websocket requests from. Please be
	// aware that the server can only act upon the HTTP request the client sends and
	// cannot verify the validity of the request header.
	WSOrigins []string `json:"WSOrigins,omitempty"`

	// WSModules is a list of API modules to expose via the websocket RPC interface.
	// If the module list is empty, all RPC API endpoints designated public will be
	// exposed.
	WSModules []string `json:"WSModules,omitempty"`

	// WSExposeAll exposes all API modules via the WebSocket RPC interface rather
	// than just the public ones.
	//
	// *WARNING* Only set this if the node is running in a trusted network, exposing
	// private APIs to untrusted users is a major security risk.
	WSExposeAll bool `json:"WSExposeAll"`

	// RESTEnabled
	RESTEnabled bool `json:"RESTEnabled"`
	// HTTPHost is the host interface on which to start the HTTP RPC server. If this
	// field is empty, no HTTP API endpoint will be started.
	RESTHost string `json:"RESTHost,omitempty"`

	// HTTPPort is the TCP port number on which to start the HTTP RPC server. The
	// default zero value is/ valid and will pick a port number randomly (useful
	// for ephemeral nodes).
	RESTPort int `json:"RESTPort"`

	// HTTPCors is the Cross-Origin Resource Sharing header to send to requesting
	// clients. Please be aware that CORS is a browser enforced security, it's fully
	// useless for custom HTTP clients.
	RESTCors []string `json:"RESTCors,omitempty"`
}

func (*RpcConfig) HTTPEndpoint

func (c *RpcConfig) HTTPEndpoint() string

HTTPEndpoint resolves an HTTP endpoint based on the configured host interface and port parameters.

func (*RpcConfig) IPCEndpoint

func (c *RpcConfig) IPCEndpoint() string

IPCEndpoint resolves an IPC endpoint based on a configured value, taking into account the set data folders as well as the designated platform we're currently running on.

func (*RpcConfig) RestEndpoint

func (c *RpcConfig) RestEndpoint() string

HTTPEndpoint resolves an HTTP endpoint based on the configured host interface and port parameters.

func (*RpcConfig) WSEndpoint

func (c *RpcConfig) WSEndpoint() string

WSEndpoint resolves a websocket endpoint based on the configured host interface and port parameters.

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

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

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

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(ctx context.Context, 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) 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

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 ShutdownError

type ShutdownError struct{}

issued when a request is received after the server is issued to stop.

func (*ShutdownError) Error

func (e *ShutdownError) Error() string

func (*ShutdownError) ErrorCode

func (e *ShutdownError) ErrorCode() int

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