Documentation ¶
Index ¶
- Constants
- Variables
- func NewHTTPServer(cors []string, vhosts []string, srv *Server) *http.Serverdeprecated
- func NewWSServer(allowedOrigins []string, srv *Server) *http.Serverdeprecated
- type API
- type BatchElem
- type BlockNumber
- type Client
- func Dial(rawurl string) (*Client, error)
- func DialContext(ctx context.Context, rawurl string) (*Client, error)
- func DialHTTP(endpoint string) (*Client, error)
- func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error)
- func DialIPC(ctx context.Context, endpoint string) (*Client, error)
- func DialStdIO(ctx context.Context) (*Client, error)
- func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error)
- func (c *Client) BatchCall(b []BatchElem) error
- func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error
- func (c *Client) Call(result interface{}, method string, args ...interface{}) error
- func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error
- func (c *Client) Close()
- func (c *Client) FtSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
- func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, ...) (*ClientSubscription, error)
- func (c *Client) SupportedModules() (map[string]string, error)
- type ClientSubscription
- type CodecOption
- type Error
- type ID
- type Notifier
- type RPCService
- type Server
- func NewServer() *Server
- func StartHTTPEndpoint(endpoint string, apis []API, modules []string, cors []string, vhosts []string) (net.Listener, *Server, error)
- func StartIPCEndpoint(ipcEndpoint string, apis []API) (net.Listener, *Server, error)
- func StartWSEndpoint(endpoint string, apis []API, modules []string, wsOrigins []string, ...) (net.Listener, *Server, error)
- 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(ctx context.Context, codec ServerCodec, options CodecOption)
- func (s *Server) Stop()
- func (srv *Server) WebsocketHandler(allowedOrigins []string) http.Handler
- type ServerCodec
- type StdIOConn
- func (io StdIOConn) Close() error
- func (io StdIOConn) LocalAddr() net.Addr
- func (io StdIOConn) Read(b []byte) (n int, err error)
- func (io StdIOConn) RemoteAddr() net.Addr
- func (io StdIOConn) SetDeadline(t time.Time) error
- func (io StdIOConn) SetReadDeadline(t time.Time) error
- func (io StdIOConn) SetWriteDeadline(t time.Time) error
- func (io StdIOConn) Write(b []byte) (n int, err error)
- type Subscription
Examples ¶
Constants ¶
const ( LatestBlockNumber = BlockNumber(-1) EarliestBlockNumber = BlockNumber(0) )
const MetadataApi = "rpc"
Variables ¶
var ( ErrClientQuit = errors.New("client is closed") ErrNoResult = errors.New("no result in JSON-RPC response") ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow") )
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 NewWSServer
deprecated
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 BatchElem ¶
type BatchElem struct { Method string Args []interface{} // The result is unmarshaled into this field. Result must be set to a // non-nil pointer value of the desired type, otherwise the response will be // discarded. Result interface{} // Error is set if the server returns an error for this request, or if // unmarshaling into Result fails. It is not set for I/O errors. Error error }
BatchElem is an element in a batch request.
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" 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 ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a connection to an RPC server.
func Dial ¶
Dial creates a new client for the given URL.
The currently supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a file name with no URL scheme, a local socket connection is established using UNIX domain sockets on supported platforms and named pipes on Windows. If you want to configure transport options, use DialHTTP, DialWebsocket or DialIPC instead.
For websocket connections, the origin is set to the local host name.
The client reconnects automatically if the connection is lost.
func DialContext ¶
DialContext creates a new RPC client, just like Dial.
The context is used to cancel or time out the initial connection establishment. It does not affect subsequent interactions with the client.
func DialHTTPWithClient ¶
DialHTTPWithClient creates a new RPC client that connects to an RPC server over HTTP using the provided HTTP Client.
func DialIPC ¶
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 DialWebsocket ¶
DialWebsocket creates a new RPC client that communicates with a JSON-RPC server that is listening on the given endpoint.
The context is used for the initial connection establishment. It does not affect subsequent interactions with the client.
func (*Client) BatchCall ¶
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 ¶
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 ¶
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) FtSubscribe ¶ added in v0.0.13
func (c *Client) FtSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
FtSubscribe registers a subscripion under the "ft" namespace.
func (*Client) Subscribe ¶
func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error)
Subscribe calls the "<namespace>_subscribe" method with the given arguments, registering a subscription. Server notifications for the subscription are sent to the given channel. The element type of the channel must match the expected type of content returned by the subscription.
The context argument cancels the RPC request that sets up the subscription but has no effect on the subscription after Subscribe has returned.
Slow subscribers will be dropped eventually. Client buffers up to 8000 notifications before considering the subscriber dead. The subscription Err channel will receive ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure that the channel usually has at least one reader to prevent this issue.
type ClientSubscription ¶
type ClientSubscription struct {
// contains filtered or unexported fields
}
A ClientSubscription represents a subscription established through EthSubscribe.
Example ¶
package main import ( "context" "fmt" "math/big" "time" "github.com/fractalplatform/fractal/rpc" ) // In this example, our client whishes to track the latest 'block number' // known to the server. The server supports two methods: // // ft_getBlockByNumber("latest", {}) // returns the latest block object. // // ft_subscribe("newBlocks") // creates a subscription which fires block objects when new blocks arrive. type Block struct { Number *big.Int } func main() { // Connect the client. client, _ := rpc.Dial("ws://127.0.0.1:8485") subch := make(chan Block) // Ensure that subch receives the latest block. go func() { for i := 0; ; i++ { if i > 0 { time.Sleep(2 * time.Second) } subscribeBlocks(client, subch) } }() // Print events from the subscription as they arrive. for block := range subch { fmt.Println("latest block:", block.Number) } } // subscribeBlocks runs in its own goroutine and maintains // a subscription for new blocks. func subscribeBlocks(client *rpc.Client, subch chan Block) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // Subscribe to new blocks. sub, err := client.FtSubscribe(ctx, subch, "newBlocks") if err != nil { fmt.Println("subscribe error:", err) return } // The connection is established now. // Update the channel with the current block. var lastBlock Block if err := client.CallContext(ctx, &lastBlock, "ft_getBlockByNumber", "latest"); err != nil { fmt.Println("can't get latest block:", err) return } subch <- lastBlock // The subscription will deliver events to the channel. Wait for the // subscription to end for any reason, then loop around to re-establish // the connection. fmt.Println("connection lost: ", <-sub.Err()) }
Output:
func (*ClientSubscription) Err ¶
func (sub *ClientSubscription) Err() <-chan error
Err returns the subscription error channel. The intended use of Err is to schedule resubscription when the client connection is closed unexpectedly.
The error channel receives a value when the subscription has ended due to an error. The received error is nil if Close has been called on the underlying client and no other error has occurred.
The error channel is closed when Unsubscribe is called on the subscription.
func (*ClientSubscription) Unsubscribe ¶
func (sub *ClientSubscription) Unsubscribe()
Unsubscribe unsubscribes the notification and closes the error channel. It can safely be called more than once.
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 StartHTTPEndpoint ¶
func StartHTTPEndpoint(endpoint string, apis []API, modules []string, cors []string, vhosts []string) (net.Listener, *Server, error)
StartHTTPEndpoint starts the HTTP RPC endpoint, configured with cors/vhosts/modules
func StartIPCEndpoint ¶
StartIPCEndpoint starts an IPC endpoint.
func StartWSEndpoint ¶
func StartWSEndpoint(endpoint string, apis []API, modules []string, wsOrigins []string, exposeAll bool) (net.Listener, *Server, error)
StartWSEndpoint starts a websocket endpoint
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(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 ¶
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 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.