github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/network/rpc/client.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"net/url"
    26  	"reflect"
    27  	"strconv"
    28  	"sync/atomic"
    29  	"time"
    30  
    31  	"github.com/neatlab/neatio/chain/log"
    32  )
    33  
    34  var (
    35  	ErrClientQuit                = errors.New("client is closed")
    36  	ErrNoResult                  = errors.New("no result in JSON-RPC response")
    37  	ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow")
    38  	errClientReconnected         = errors.New("client reconnected")
    39  	errDead                      = errors.New("connection lost")
    40  )
    41  
    42  const (
    43  	// Timeouts
    44  	tcpKeepAliveInterval = 30 * time.Second
    45  	defaultDialTimeout   = 10 * time.Second // used if context has no deadline
    46  	subscribeTimeout     = 5 * time.Second  // overall timeout eth_subscribe, rpc_modules calls
    47  )
    48  
    49  const (
    50  	// Subscriptions are removed when the subscriber cannot keep up.
    51  	//
    52  	// This can be worked around by supplying a channel with sufficiently sized buffer,
    53  	// but this can be inconvenient and hard to explain in the docs. Another issue with
    54  	// buffered channels is that the buffer is static even though it might not be needed
    55  	// most of the time.
    56  	//
    57  	// The approach taken here is to maintain a per-subscription linked list buffer
    58  	// shrinks on demand. If the buffer reaches the size below, the subscription is
    59  	// dropped.
    60  	maxClientSubscriptionBuffer = 20000
    61  )
    62  
    63  // BatchElem is an element in a batch request.
    64  type BatchElem struct {
    65  	Method string
    66  	Args   []interface{}
    67  	// The result is unmarshaled into this field. Result must be set to a
    68  	// non-nil pointer value of the desired type, otherwise the response will be
    69  	// discarded.
    70  	Result interface{}
    71  	// Error is set if the server returns an error for this request, or if
    72  	// unmarshaling into Result fails. It is not set for I/O errors.
    73  	Error error
    74  }
    75  
    76  // Client represents a connection to an RPC server.
    77  type Client struct {
    78  	idgen    func() ID // for subscriptions
    79  	isHTTP   bool
    80  	services *serviceRegistry
    81  
    82  	idCounter uint32
    83  
    84  	// This function, if non-nil, is called when the connection is lost.
    85  	reconnectFunc reconnectFunc
    86  
    87  	// writeConn is used for writing to the connection on the caller's goroutine. It should
    88  	// only be accessed outside of dispatch, with the write lock held. The write lock is
    89  	// taken by sending on requestOp and released by sending on sendDone.
    90  	writeConn jsonWriter
    91  
    92  	// for dispatch
    93  	close       chan struct{}
    94  	closing     chan struct{}    // closed when client is quitting
    95  	didClose    chan struct{}    // closed when client quits
    96  	reconnected chan ServerCodec // where write/reconnect sends the new connection
    97  	readOp      chan readOp      // read messages
    98  	readErr     chan error       // errors from read
    99  	reqInit     chan *requestOp  // register response IDs, takes write lock
   100  	reqSent     chan error       // signals write completion, releases write lock
   101  	reqTimeout  chan *requestOp  // removes response IDs when call timeout expires
   102  }
   103  
   104  type reconnectFunc func(ctx context.Context) (ServerCodec, error)
   105  
   106  type clientContextKey struct{}
   107  
   108  type clientConn struct {
   109  	codec   ServerCodec
   110  	handler *handler
   111  }
   112  
   113  func (c *Client) newClientConn(conn ServerCodec) *clientConn {
   114  	ctx := context.WithValue(context.Background(), clientContextKey{}, c)
   115  	handler := newHandler(ctx, conn, c.idgen, c.services)
   116  	return &clientConn{conn, handler}
   117  }
   118  
   119  func (cc *clientConn) close(err error, inflightReq *requestOp) {
   120  	cc.handler.close(err, inflightReq)
   121  	cc.codec.Close()
   122  }
   123  
   124  type readOp struct {
   125  	msgs  []*jsonrpcMessage
   126  	batch bool
   127  }
   128  
   129  type requestOp struct {
   130  	ids  []json.RawMessage
   131  	err  error
   132  	resp chan *jsonrpcMessage // receives up to len(ids) responses
   133  	sub  *ClientSubscription  // only set for EthSubscribe requests
   134  }
   135  
   136  func (op *requestOp) wait(ctx context.Context, c *Client) (*jsonrpcMessage, error) {
   137  	select {
   138  	case <-ctx.Done():
   139  		// Send the timeout to dispatch so it can remove the request IDs.
   140  		select {
   141  		case c.reqTimeout <- op:
   142  		case <-c.closing:
   143  		}
   144  		return nil, ctx.Err()
   145  	case resp := <-op.resp:
   146  		return resp, op.err
   147  	}
   148  }
   149  
   150  // Dial creates a new client for the given URL.
   151  //
   152  // The currently supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a
   153  // file name with no URL scheme, a local socket connection is established using UNIX
   154  // domain sockets on supported platforms and named pipes on Windows. If you want to
   155  // configure transport options, use DialHTTP, DialWebsocket or DialIPC instead.
   156  //
   157  // For websocket connections, the origin is set to the local host name.
   158  //
   159  // The client reconnects automatically if the connection is lost.
   160  func Dial(rawurl string) (*Client, error) {
   161  	return DialContext(context.Background(), rawurl)
   162  }
   163  
   164  // DialContext creates a new RPC client, just like Dial.
   165  //
   166  // The context is used to cancel or time out the initial connection establishment. It does
   167  // not affect subsequent interactions with the client.
   168  func DialContext(ctx context.Context, rawurl string) (*Client, error) {
   169  	u, err := url.Parse(rawurl)
   170  	if err != nil {
   171  		return nil, err
   172  	}
   173  	switch u.Scheme {
   174  	case "http", "https":
   175  		return DialHTTP(rawurl)
   176  	case "ws", "wss":
   177  		return DialWebsocket(ctx, rawurl, "")
   178  	case "stdio":
   179  		return DialStdIO(ctx)
   180  	case "":
   181  		return DialIPC(ctx, rawurl)
   182  	default:
   183  		return nil, fmt.Errorf("no known transport for URL scheme %q", u.Scheme)
   184  	}
   185  }
   186  
   187  // Client retrieves the client from the context, if any. This can be used to perform
   188  // 'reverse calls' in a handler method.
   189  func ClientFromContext(ctx context.Context) (*Client, bool) {
   190  	client, ok := ctx.Value(clientContextKey{}).(*Client)
   191  	return client, ok
   192  }
   193  
   194  func newClient(initctx context.Context, connect reconnectFunc) (*Client, error) {
   195  	conn, err := connect(initctx)
   196  	if err != nil {
   197  		return nil, err
   198  	}
   199  	c := initClient(conn, randomIDGenerator(), new(serviceRegistry))
   200  	c.reconnectFunc = connect
   201  	return c, nil
   202  }
   203  
   204  func initClient(conn ServerCodec, idgen func() ID, services *serviceRegistry) *Client {
   205  	_, isHTTP := conn.(*httpConn)
   206  	c := &Client{
   207  		idgen:       idgen,
   208  		isHTTP:      isHTTP,
   209  		services:    services,
   210  		writeConn:   conn,
   211  		close:       make(chan struct{}),
   212  		closing:     make(chan struct{}),
   213  		didClose:    make(chan struct{}),
   214  		reconnected: make(chan ServerCodec),
   215  		readOp:      make(chan readOp),
   216  		readErr:     make(chan error),
   217  		reqInit:     make(chan *requestOp),
   218  		reqSent:     make(chan error, 1),
   219  		reqTimeout:  make(chan *requestOp),
   220  	}
   221  	if !isHTTP {
   222  		go c.dispatch(conn)
   223  	}
   224  	return c
   225  }
   226  
   227  // RegisterName creates a service for the given receiver type under the given name. When no
   228  // methods on the given receiver match the criteria to be either a RPC method or a
   229  // subscription an error is returned. Otherwise a new service is created and added to the
   230  // service collection this client provides to the server.
   231  func (c *Client) RegisterName(name string, receiver interface{}) error {
   232  	return c.services.registerName(name, receiver)
   233  }
   234  
   235  func (c *Client) nextID() json.RawMessage {
   236  	id := atomic.AddUint32(&c.idCounter, 1)
   237  	return strconv.AppendUint(nil, uint64(id), 10)
   238  }
   239  
   240  // SupportedModules calls the rpc_modules method, retrieving the list of
   241  // APIs that are available on the server.
   242  func (c *Client) SupportedModules() (map[string]string, error) {
   243  	var result map[string]string
   244  	ctx, cancel := context.WithTimeout(context.Background(), subscribeTimeout)
   245  	defer cancel()
   246  	err := c.CallContext(ctx, &result, "rpc_modules")
   247  	return result, err
   248  }
   249  
   250  // Close closes the client, aborting any in-flight requests.
   251  func (c *Client) Close() {
   252  	if c.isHTTP {
   253  		return
   254  	}
   255  	select {
   256  	case c.close <- struct{}{}:
   257  		<-c.didClose
   258  	case <-c.didClose:
   259  	}
   260  }
   261  
   262  // Call performs a JSON-RPC call with the given arguments and unmarshals into
   263  // result if no error occurred.
   264  //
   265  // The result must be a pointer so that package json can unmarshal into it. You
   266  // can also pass nil, in which case the result is ignored.
   267  func (c *Client) Call(result interface{}, method string, args ...interface{}) error {
   268  	ctx := context.Background()
   269  	return c.CallContext(ctx, result, method, args...)
   270  }
   271  
   272  // CallContext performs a JSON-RPC call with the given arguments. If the context is
   273  // canceled before the call has successfully returned, CallContext returns immediately.
   274  //
   275  // The result must be a pointer so that package json can unmarshal into it. You
   276  // can also pass nil, in which case the result is ignored.
   277  func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error {
   278  	msg, err := c.newMessage(method, args...)
   279  	if err != nil {
   280  		return err
   281  	}
   282  	op := &requestOp{ids: []json.RawMessage{msg.ID}, resp: make(chan *jsonrpcMessage, 1)}
   283  
   284  	if c.isHTTP {
   285  		err = c.sendHTTP(ctx, op, msg)
   286  	} else {
   287  		err = c.send(ctx, op, msg)
   288  	}
   289  	if err != nil {
   290  		return err
   291  	}
   292  
   293  	// dispatch has accepted the request and will close the channel when it quits.
   294  	switch resp, err := op.wait(ctx, c); {
   295  	case err != nil:
   296  		return err
   297  	case resp.Error != nil:
   298  		return resp.Error
   299  	case len(resp.Result) == 0:
   300  		return ErrNoResult
   301  	default:
   302  		return json.Unmarshal(resp.Result, &result)
   303  	}
   304  }
   305  
   306  // BatchCall sends all given requests as a single batch and waits for the server
   307  // to return a response for all of them.
   308  //
   309  // In contrast to Call, BatchCall only returns I/O errors. Any error specific to
   310  // a request is reported through the Error field of the corresponding BatchElem.
   311  //
   312  // Note that batch calls may not be executed atomically on the server side.
   313  func (c *Client) BatchCall(b []BatchElem) error {
   314  	ctx := context.Background()
   315  	return c.BatchCallContext(ctx, b)
   316  }
   317  
   318  // BatchCall sends all given requests as a single batch and waits for the server
   319  // to return a response for all of them. The wait duration is bounded by the
   320  // context's deadline.
   321  //
   322  // In contrast to CallContext, BatchCallContext only returns errors that have occurred
   323  // while sending the request. Any error specific to a request is reported through the
   324  // Error field of the corresponding BatchElem.
   325  //
   326  // Note that batch calls may not be executed atomically on the server side.
   327  func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error {
   328  	msgs := make([]*jsonrpcMessage, len(b))
   329  	op := &requestOp{
   330  		ids:  make([]json.RawMessage, len(b)),
   331  		resp: make(chan *jsonrpcMessage, len(b)),
   332  	}
   333  	for i, elem := range b {
   334  		msg, err := c.newMessage(elem.Method, elem.Args...)
   335  		if err != nil {
   336  			return err
   337  		}
   338  		msgs[i] = msg
   339  		op.ids[i] = msg.ID
   340  	}
   341  
   342  	var err error
   343  	if c.isHTTP {
   344  		err = c.sendBatchHTTP(ctx, op, msgs)
   345  	} else {
   346  		err = c.send(ctx, op, msgs)
   347  	}
   348  
   349  	// Wait for all responses to come back.
   350  	for n := 0; n < len(b) && err == nil; n++ {
   351  		var resp *jsonrpcMessage
   352  		resp, err = op.wait(ctx, c)
   353  		if err != nil {
   354  			break
   355  		}
   356  		// Find the element corresponding to this response.
   357  		// The element is guaranteed to be present because dispatch
   358  		// only sends valid IDs to our channel.
   359  		var elem *BatchElem
   360  		for i := range msgs {
   361  			if bytes.Equal(msgs[i].ID, resp.ID) {
   362  				elem = &b[i]
   363  				break
   364  			}
   365  		}
   366  		if resp.Error != nil {
   367  			elem.Error = resp.Error
   368  			continue
   369  		}
   370  		if len(resp.Result) == 0 {
   371  			elem.Error = ErrNoResult
   372  			continue
   373  		}
   374  		elem.Error = json.Unmarshal(resp.Result, elem.Result)
   375  	}
   376  	return err
   377  }
   378  
   379  // Notify sends a notification, i.e. a method call that doesn't expect a response.
   380  func (c *Client) Notify(ctx context.Context, method string, args ...interface{}) error {
   381  	op := new(requestOp)
   382  	msg, err := c.newMessage(method, args...)
   383  	if err != nil {
   384  		return err
   385  	}
   386  	msg.ID = nil
   387  
   388  	if c.isHTTP {
   389  		return c.sendHTTP(ctx, op, msg)
   390  	} else {
   391  		return c.send(ctx, op, msg)
   392  	}
   393  }
   394  
   395  // EthSubscribe registers a subscripion under the "neatptc" namespace.
   396  func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   397  	return c.Subscribe(ctx, "eth", channel, args...)
   398  }
   399  
   400  // ShhSubscribe registers a subscripion under the "shh" namespace.
   401  func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   402  	return c.Subscribe(ctx, "shh", channel, args...)
   403  }
   404  
   405  // Subscribe calls the "<namespace>_subscribe" method with the given arguments,
   406  // registering a subscription. Server notifications for the subscription are
   407  // sent to the given channel. The element type of the channel must match the
   408  // expected type of content returned by the subscription.
   409  //
   410  // The context argument cancels the RPC request that sets up the subscription but has no
   411  // effect on the subscription after Subscribe has returned.
   412  //
   413  // Slow subscribers will be dropped eventually. Client buffers up to 8000 notifications
   414  // before considering the subscriber dead. The subscription Err channel will receive
   415  // ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure
   416  // that the channel usually has at least one reader to prevent this issue.
   417  func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   418  	// Check type of channel first.
   419  	chanVal := reflect.ValueOf(channel)
   420  	if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 {
   421  		panic("first argument to Subscribe must be a writable channel")
   422  	}
   423  	if chanVal.IsNil() {
   424  		panic("channel given to Subscribe must not be nil")
   425  	}
   426  	if c.isHTTP {
   427  		return nil, ErrNotificationsUnsupported
   428  	}
   429  
   430  	msg, err := c.newMessage(namespace+subscribeMethodSuffix, args...)
   431  	if err != nil {
   432  		return nil, err
   433  	}
   434  	op := &requestOp{
   435  		ids:  []json.RawMessage{msg.ID},
   436  		resp: make(chan *jsonrpcMessage),
   437  		sub:  newClientSubscription(c, namespace, chanVal),
   438  	}
   439  
   440  	// Send the subscription request.
   441  	// The arrival and validity of the response is signaled on sub.quit.
   442  	if err := c.send(ctx, op, msg); err != nil {
   443  		return nil, err
   444  	}
   445  	if _, err := op.wait(ctx, c); err != nil {
   446  		return nil, err
   447  	}
   448  	return op.sub, nil
   449  }
   450  
   451  func (c *Client) newMessage(method string, paramsIn ...interface{}) (*jsonrpcMessage, error) {
   452  	msg := &jsonrpcMessage{Version: vsn, ID: c.nextID(), Method: method}
   453  	if paramsIn != nil { // prevent sending "params":null
   454  		var err error
   455  		if msg.Params, err = json.Marshal(paramsIn); err != nil {
   456  			return nil, err
   457  		}
   458  	}
   459  	return msg, nil
   460  }
   461  
   462  // send registers op with the dispatch loop, then sends msg on the connection.
   463  // if sending fails, op is deregistered.
   464  func (c *Client) send(ctx context.Context, op *requestOp, msg interface{}) error {
   465  	select {
   466  	case c.reqInit <- op:
   467  		err := c.write(ctx, msg)
   468  		c.reqSent <- err
   469  		return err
   470  	case <-ctx.Done():
   471  		// This can happen if the client is overloaded or unable to keep up with
   472  		// subscription notifications.
   473  		return ctx.Err()
   474  	case <-c.closing:
   475  		return ErrClientQuit
   476  	}
   477  }
   478  
   479  func (c *Client) write(ctx context.Context, msg interface{}) error {
   480  	// The previous write failed. Try to establish a new connection.
   481  	if c.writeConn == nil {
   482  		if err := c.reconnect(ctx); err != nil {
   483  			return err
   484  		}
   485  	}
   486  	err := c.writeConn.Write(ctx, msg)
   487  	if err != nil {
   488  		c.writeConn = nil
   489  	}
   490  	return err
   491  }
   492  
   493  func (c *Client) reconnect(ctx context.Context) error {
   494  	if c.reconnectFunc == nil {
   495  		return errDead
   496  	}
   497  
   498  	if _, ok := ctx.Deadline(); !ok {
   499  		var cancel func()
   500  		ctx, cancel = context.WithTimeout(ctx, defaultDialTimeout)
   501  		defer cancel()
   502  	}
   503  	newconn, err := c.reconnectFunc(ctx)
   504  	if err != nil {
   505  		log.Trace("RPC client reconnect failed", "err", err)
   506  		return err
   507  	}
   508  	select {
   509  	case c.reconnected <- newconn:
   510  		c.writeConn = newconn
   511  		return nil
   512  	case <-c.didClose:
   513  		newconn.Close()
   514  		return ErrClientQuit
   515  	}
   516  }
   517  
   518  // dispatch is the main loop of the client.
   519  // It sends read messages to waiting calls to Call and BatchCall
   520  // and subscription notifications to registered subscriptions.
   521  func (c *Client) dispatch(codec ServerCodec) {
   522  	var (
   523  		lastOp      *requestOp  // tracks last send operation
   524  		reqInitLock = c.reqInit // nil while the send lock is held
   525  		conn        = c.newClientConn(codec)
   526  		reading     = true
   527  	)
   528  	defer func() {
   529  		close(c.closing)
   530  		if reading {
   531  			conn.close(ErrClientQuit, nil)
   532  			c.drainRead()
   533  		}
   534  		close(c.didClose)
   535  	}()
   536  
   537  	// Spawn the initial read loop.
   538  	go c.read(codec)
   539  
   540  	for {
   541  		select {
   542  		case <-c.close:
   543  			return
   544  
   545  		// Read path:
   546  		case op := <-c.readOp:
   547  			if op.batch {
   548  				conn.handler.handleBatch(op.msgs)
   549  			} else {
   550  				conn.handler.handleMsg(op.msgs[0])
   551  			}
   552  
   553  		case err := <-c.readErr:
   554  			conn.handler.log.Debug("RPC connection read error", "err", err)
   555  			conn.close(err, lastOp)
   556  			reading = false
   557  
   558  		// Reconnect:
   559  		case newcodec := <-c.reconnected:
   560  			log.Debug("RPC client reconnected", "reading", reading, "conn", newcodec.RemoteAddr())
   561  			if reading {
   562  				// Wait for the previous read loop to exit. This is a rare case which
   563  				// happens if this loop isn't notified in time after the connection breaks.
   564  				// In those cases the caller will notice first and reconnect. Closing the
   565  				// handler terminates all waiting requests (closing op.resp) except for
   566  				// lastOp, which will be transferred to the new handler.
   567  				conn.close(errClientReconnected, lastOp)
   568  				c.drainRead()
   569  			}
   570  			go c.read(newcodec)
   571  			reading = true
   572  			conn = c.newClientConn(newcodec)
   573  			// Re-register the in-flight request on the new handler
   574  			// because that's where it will be sent.
   575  			conn.handler.addRequestOp(lastOp)
   576  
   577  		// Send path:
   578  		case op := <-reqInitLock:
   579  			// Stop listening for further requests until the current one has been sent.
   580  			reqInitLock = nil
   581  			lastOp = op
   582  			conn.handler.addRequestOp(op)
   583  
   584  		case err := <-c.reqSent:
   585  			if err != nil {
   586  				// Remove response handlers for the last send. When the read loop
   587  				// goes down, it will signal all other current operations.
   588  				conn.handler.removeRequestOp(lastOp)
   589  			}
   590  			// Let the next request in.
   591  			reqInitLock = c.reqInit
   592  			lastOp = nil
   593  
   594  		case op := <-c.reqTimeout:
   595  			conn.handler.removeRequestOp(op)
   596  		}
   597  	}
   598  }
   599  
   600  // drainRead drops read messages until an error occurs.
   601  func (c *Client) drainRead() {
   602  	for {
   603  		select {
   604  		case <-c.readOp:
   605  		case <-c.readErr:
   606  			return
   607  		}
   608  	}
   609  }
   610  
   611  // read decodes RPC messages from a codec, feeding them into dispatch.
   612  func (c *Client) read(codec ServerCodec) {
   613  	for {
   614  		msgs, batch, err := codec.Read()
   615  		if _, ok := err.(*json.SyntaxError); ok {
   616  			codec.Write(context.Background(), errorMessage(&parseError{err.Error()}))
   617  		}
   618  		if err != nil {
   619  			c.readErr <- err
   620  			return
   621  		}
   622  		c.readOp <- readOp{msgs, batch}
   623  	}
   624  }