wsrpc

package module
v2.3.5 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2022 License: BlueOak-1.0.0 Imports: 14 Imported by: 33

README

wsrpc

Module github.com/jrick/wsrpc/v2 provides a partial implementation of a JSON-RPC 2.0 websocket client. Inspired by net/rpc, clients call methods by their name with arguments and return values marshaled by encoding/json. The client may be used to create convenience calls with types specific to an application.

Receiving notifications is supported but it is up to the caller to unmarshal the JSON-RPC parameters into meaningful data.

This module currently does not implement JSON-RPC 2.0 request batching or keyed request parameters when performing calls.

CLI

A command line tool is provided to perform individual websocket JSON-RPCs against a server.

A JSON array must be used to pass parameters in a method call.

$ wsrpc -h
usage: wsrpc address [flags] method [arg]
  -c string
        Root certificate PEM file
  -p string
        Password
  -u string
        User
$ wsrpc wss://dcrd0.i.zettaport.com:9109/ws -c dcrd0.pem -u jrick -p sekrit getinfo
{
  "version": 1050000,
  "protocolversion": 6,
  "blocks": 324795,
  "timeoffset": 0,
  "connections": 65,
  "proxy": "",
  "difficulty": 19920803496.64989,
  "testnet": false,
  "relayfee": 0.0001,
  "errors": ""
}
$ wsrpc wss://dcrd0.i.zettaport.com:9109/ws -c dcrd0.pem -u jrick -p sekrit getblockhash '[324795]'
"0000000000000000235b1210221d412c428237175dbb0aef202277d1706b9312"

The wsrpc-agent tool can be optionally used to manage persistent connections. Usage of the agent is similar to ssh-agent. The agent can exec a command, running only so long as the command continues to run, or by daemonizing and using eval to set the environment of the Bourne shell:

$ wsrpc-agent -h
usage (exec):   wsrpc-agent cmd [args...]
usage (daemon): eval $(wsrpc-agent)

Once running, wsrpc will use the WSRPCAGENT_SOCK and WSRPCAGENT_AUTH environment variables to perform IPC with the agent. TLS and RPC authentication flags only apply to the initial connection.

$ eval `wsrpc-agent`
Agent listening on /tmp/wsrpc732266934/agent.19981
$ wsrpc wss://dcrd0.i.zettaport.com:9109/ws -c dcrd0.pem -u jrick -p sekrit getblockhash '[324795]'
"0000000000000000235b1210221d412c428237175dbb0aef202277d1706b9312"
$ wsrpc wss://dcrd0.i.zettaport.com:9109/ws getblockhash '[324795]'
"0000000000000000235b1210221d412c428237175dbb0aef202277d1706b9312"

It is sometimes desirable for wsrpc-agent to run at login and stay running for the duration of the user's X session. This can be accomplished with the following in a .xsession script:

if [ -z "$WSRPCAGENT_PID" -a "$(whence wsrpc-agent)" ]; then
	eval $(wsrpc-agent)
fi

do_exit() {
	if [ "$WSRPCAGENT_PID" ]; then
		kill "$WSRPCAGENT_PID"
		export WSRPCAGENT_SOCK=
		export WSRPCAGENT_AUTH=
		export WSRPCAGENT_PID=
	fi
	exit
}

your_window_manager
do_exit

License

wsrpc is licensed under the permissive Blue Oak Model License 1.0.0.

Documentation

Overview

Package wsrpc provides a partial implementation of a JSON-RPC 2.0 websocket client. Inspired by net/rpc, clients call methods by their name with arguments and return values marshaled by encoding/json. The client may be used to create convenience calls with types specific to an application.

Receiving notifications is supported but it is up to the caller to unmarshal the JSON-RPC parameters into meaningful data.

This package currently does not implement JSON-RPC 2.0 request batching or keyed request parameters when performing calls.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Call added in v2.2.2

type Call interface {
	Result() (interface{}, error)
	Done() chan Call
}

Call represents a JSON-RPC method invocation. Result returns the provided return result and any error occurring during the call.

Result must only be called after the call has completed. Completion is signaled by the call being sent over the channel returned by Done. Implementations are allowed to panic when Result is called before this.

type Client

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

Client implements JSON-RPC calls and notifications over a websocket.

func Dial

func Dial(ctx context.Context, addr string, opts ...Option) (*Client, error)

Dial establishes an RPC client connection to the server described by addr. Addr must be the URL of the websocket, e.g., "wss://[::1]:9109/ws".

func (*Client) Call

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

Call performs the JSON-RPC described by method with positional parameters passed through args. Result should point to an object to unmarshal the result, or equal nil to discard the result.

func (*Client) Close

func (c *Client) Close() error

Close sends a websocket close control message and closes the underlying network connection.

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done returns a channel that is closed after the client's final error is set.

func (*Client) Err

func (c *Client) Err() error

Err blocks until the client has shutdown and returns the final error.

func (*Client) Go added in v2.2.2

func (c *Client) Go(ctx context.Context, method string, result interface{}, done chan Call, args ...interface{}) Call

Go asynchronously calls the JSON-RPC described by method with positional parameters passed through args. Result should point to an object to unmarshal the result, or equal nil to discard the result. The done channel will be written with the returned call after completion or error and must be buffered if non-nil.

func (*Client) String

func (c *Client) String() string

String returns the dialed websocket URL.

type DialFunc

type DialFunc func(ctx context.Context, network, address string) (net.Conn, error)

DialFunc dials a network connection. Custom dialers may utilize a proxy or set connection timeouts.

type Error

type Error struct {
	Code    int64           `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

Error represents a JSON-RPC error object.

func (*Error) Error

func (e *Error) Error() string

type Notifier

type Notifier interface {
	Notify(method string, params json.RawMessage) error
}

Notifier handles JSON-RPC notifications. Method defines the type of notification and params describes the arguments (positional or keyed) if any were included in the Request object.

Notify is never called concurrently and is called with notifications in the order received. Blocking in Notify only blocks other Notify calls and does not prevent the Client from receiving further buffered notifications and processing calls.

If Notify returns an error, the client is closed and no more notifications are processed. If this is the first error observed by the client, it will be returned by Err.

If Notifier implements io.Closer, Close is called following the final notification.

type Option

type Option func(*options)

Option modifies the behavior of Dial.

func WithBasicAuth

func WithBasicAuth(user, pass string) Option

WithBasicAuth enables basic access authentication using the user and password.

func WithDial

func WithDial(dial DialFunc) Option

WithDial specifies a custom dial function.

func WithNotifier

func WithNotifier(n Notifier) Option

WithNotifier specifies a Notifier to handle received JSON-RPC notifications. Notifications may continue to be processed after the client has closed. Notifications are dropped by Client if a Notifier is not configured.

func WithPingPeriod added in v2.1.0

func WithPingPeriod(period time.Duration) Option

WithPingPeriod specifies a duration between pings sent on a timer. A pong message not received within this period (plus a tolerance) causes connection termination. A period of 0 disables the mechanism.

The default value is one minute.

func WithTLSConfig

func WithTLSConfig(tls *tls.Config) Option

WithTLSConfig specifies a TLS config when connecting to a secure websocket (wss) server. If unspecified, the default TLS config will be used.

func WithoutPongDeadline added in v2.2.0

func WithoutPongDeadline() Option

WithoutPongDeadline disables any default or custom pong deadline. Pings will still be written every ping period unless disabled. This option is reset by later WithPingPeriod options.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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