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