github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/rpc/client.go (about)

     1  // Copyright 2016 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"bytes"
    21  	"container/list"
    22  	"context"
    23  	"encoding/json"
    24  	"errors"
    25  	"fmt"
    26  	"net"
    27  	"net/url"
    28  	"reflect"
    29  	"strconv"
    30  	"strings"
    31  	"sync"
    32  	"sync/atomic"
    33  	"time"
    34  
    35  	"github.com/SmartMeshFoundation/Spectrum/log"
    36  )
    37  
    38  var (
    39  	ErrClientQuit                = errors.New("client is closed")
    40  	ErrNoResult                  = errors.New("no result in JSON-RPC response")
    41  	ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow")
    42  )
    43  
    44  const (
    45  	// Timeouts
    46  	tcpKeepAliveInterval = 30 * time.Second
    47  	defaultDialTimeout   = 10 * time.Second // used when dialing if the context has no deadline
    48  	defaultWriteTimeout  = 10 * time.Second // used for calls if the context has no deadline
    49  	subscribeTimeout     = 5 * time.Second  // overall timeout eth_subscribe, rpc_modules calls
    50  )
    51  
    52  const (
    53  	// Subscriptions are removed when the subscriber cannot keep up.
    54  	//
    55  	// This can be worked around by supplying a channel with sufficiently sized buffer,
    56  	// but this can be inconvenient and hard to explain in the docs. Another issue with
    57  	// buffered channels is that the buffer is static even though it might not be needed
    58  	// most of the time.
    59  	//
    60  	// The approach taken here is to maintain a per-subscription linked list buffer
    61  	// shrinks on demand. If the buffer reaches the size below, the subscription is
    62  	// dropped.
    63  	maxClientSubscriptionBuffer = 8000
    64  )
    65  
    66  // BatchElem is an element in a batch request.
    67  type BatchElem struct {
    68  	Method string
    69  	Args   []interface{}
    70  	// The result is unmarshaled into this field. Result must be set to a
    71  	// non-nil pointer value of the desired type, otherwise the response will be
    72  	// discarded.
    73  	Result interface{}
    74  	// Error is set if the server returns an error for this request, or if
    75  	// unmarshaling into Result fails. It is not set for I/O errors.
    76  	Error error
    77  }
    78  
    79  // A value of this type can a JSON-RPC request, notification, successful response or
    80  // error response. Which one it is depends on the fields.
    81  type jsonrpcMessage struct {
    82  	Version string          `json:"jsonrpc"`
    83  	ID      json.RawMessage `json:"id,omitempty"`
    84  	Method  string          `json:"method,omitempty"`
    85  	Params  json.RawMessage `json:"params,omitempty"`
    86  	Error   *jsonError      `json:"error,omitempty"`
    87  	Result  json.RawMessage `json:"result,omitempty"`
    88  }
    89  
    90  func (msg *jsonrpcMessage) isNotification() bool {
    91  	return msg.ID == nil && msg.Method != ""
    92  }
    93  
    94  func (msg *jsonrpcMessage) isResponse() bool {
    95  	return msg.hasValidID() && msg.Method == "" && len(msg.Params) == 0
    96  }
    97  
    98  func (msg *jsonrpcMessage) hasValidID() bool {
    99  	return len(msg.ID) > 0 && msg.ID[0] != '{' && msg.ID[0] != '['
   100  }
   101  
   102  func (msg *jsonrpcMessage) String() string {
   103  	b, _ := json.Marshal(msg)
   104  	return string(b)
   105  }
   106  
   107  // Client represents a connection to an RPC server.
   108  type Client struct {
   109  	idCounter   uint32
   110  	connectFunc func(ctx context.Context) (net.Conn, error)
   111  	isHTTP      bool
   112  
   113  	// writeConn is only safe to access outside dispatch, with the
   114  	// write lock held. The write lock is taken by sending on
   115  	// requestOp and released by sending on sendDone.
   116  	writeConn net.Conn
   117  
   118  	// for dispatch
   119  	close       chan struct{}
   120  	didQuit     chan struct{}                  // closed when client quits
   121  	reconnected chan net.Conn                  // where write/reconnect sends the new connection
   122  	readErr     chan error                     // errors from read
   123  	readResp    chan []*jsonrpcMessage         // valid messages from read
   124  	requestOp   chan *requestOp                // for registering response IDs
   125  	sendDone    chan error                     // signals write completion, releases write lock
   126  	respWait    map[string]*requestOp          // active requests
   127  	subs        map[string]*ClientSubscription // active subscriptions
   128  }
   129  
   130  type requestOp struct {
   131  	ids  []json.RawMessage
   132  	err  error
   133  	resp chan *jsonrpcMessage // receives up to len(ids) responses
   134  	sub  *ClientSubscription  // only set for EthSubscribe requests
   135  }
   136  
   137  func (op *requestOp) wait(ctx context.Context) (*jsonrpcMessage, error) {
   138  	select {
   139  	case <-ctx.Done():
   140  		return nil, ctx.Err()
   141  	case resp := <-op.resp:
   142  		return resp, op.err
   143  	}
   144  }
   145  
   146  // Dial creates a new client for the given URL.
   147  //
   148  // The currently supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a
   149  // file name with no URL scheme, a local socket connection is established using UNIX
   150  // domain sockets on supported platforms and named pipes on Windows. If you want to
   151  // configure transport options, use DialHTTP, DialWebsocket or DialIPC instead.
   152  //
   153  // For websocket connections, the origin is set to the local host name.
   154  //
   155  // The client reconnects automatically if the connection is lost.
   156  func Dial(rawurl string) (*Client, error) {
   157  	return DialContext(context.Background(), rawurl)
   158  }
   159  
   160  // DialContext creates a new RPC client, just like Dial.
   161  //
   162  // The context is used to cancel or time out the initial connection establishment. It does
   163  // not affect subsequent interactions with the client.
   164  func DialContext(ctx context.Context, rawurl string) (*Client, error) {
   165  	u, err := url.Parse(rawurl)
   166  	if err != nil {
   167  		return nil, err
   168  	}
   169  	switch u.Scheme {
   170  	case "http", "https":
   171  		return DialHTTP(rawurl)
   172  	case "ws", "wss":
   173  		return DialWebsocket(ctx, rawurl, "")
   174  	case "":
   175  		return DialIPC(ctx, rawurl)
   176  	default:
   177  		return nil, fmt.Errorf("no known transport for URL scheme %q", u.Scheme)
   178  	}
   179  }
   180  
   181  func newClient(initctx context.Context, connectFunc func(context.Context) (net.Conn, error)) (*Client, error) {
   182  	conn, err := connectFunc(initctx)
   183  	if err != nil {
   184  		return nil, err
   185  	}
   186  	_, isHTTP := conn.(*httpConn)
   187  
   188  	c := &Client{
   189  		writeConn:   conn,
   190  		isHTTP:      isHTTP,
   191  		connectFunc: connectFunc,
   192  		close:       make(chan struct{}),
   193  		didQuit:     make(chan struct{}),
   194  		reconnected: make(chan net.Conn),
   195  		readErr:     make(chan error),
   196  		readResp:    make(chan []*jsonrpcMessage),
   197  		requestOp:   make(chan *requestOp),
   198  		sendDone:    make(chan error, 1),
   199  		respWait:    make(map[string]*requestOp),
   200  		subs:        make(map[string]*ClientSubscription),
   201  	}
   202  	if !isHTTP {
   203  		go c.dispatch(conn)
   204  	}
   205  	return c, nil
   206  }
   207  
   208  func (c *Client) nextID() json.RawMessage {
   209  	id := atomic.AddUint32(&c.idCounter, 1)
   210  	return []byte(strconv.FormatUint(uint64(id), 10))
   211  }
   212  
   213  // SupportedModules calls the rpc_modules method, retrieving the list of
   214  // APIs that are available on the server.
   215  func (c *Client) SupportedModules() (map[string]string, error) {
   216  	var result map[string]string
   217  	ctx, cancel := context.WithTimeout(context.Background(), subscribeTimeout)
   218  	defer cancel()
   219  	err := c.CallContext(ctx, &result, "rpc_modules")
   220  	return result, err
   221  }
   222  
   223  // Close closes the client, aborting any in-flight requests.
   224  func (c *Client) Close() {
   225  	if c.isHTTP {
   226  		return
   227  	}
   228  	select {
   229  	case c.close <- struct{}{}:
   230  		<-c.didQuit
   231  	case <-c.didQuit:
   232  	}
   233  }
   234  
   235  // Call performs a JSON-RPC call with the given arguments and unmarshals into
   236  // result if no error occurred.
   237  //
   238  // The result must be a pointer so that package json can unmarshal into it. You
   239  // can also pass nil, in which case the result is ignored.
   240  func (c *Client) Call(result interface{}, method string, args ...interface{}) error {
   241  	ctx := context.Background()
   242  	return c.CallContext(ctx, result, method, args...)
   243  }
   244  
   245  // CallContext performs a JSON-RPC call with the given arguments. If the context is
   246  // canceled before the call has successfully returned, CallContext returns immediately.
   247  //
   248  // The result must be a pointer so that package json can unmarshal into it. You
   249  // can also pass nil, in which case the result is ignored.
   250  func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error {
   251  	msg, err := c.newMessage(method, args...)
   252  	if err != nil {
   253  		return err
   254  	}
   255  	op := &requestOp{ids: []json.RawMessage{msg.ID}, resp: make(chan *jsonrpcMessage, 1)}
   256  
   257  	if c.isHTTP {
   258  		err = c.sendHTTP(ctx, op, msg)
   259  	} else {
   260  		err = c.send(ctx, op, msg)
   261  	}
   262  	if err != nil {
   263  		return err
   264  	}
   265  
   266  	// dispatch has accepted the request and will close the channel it when it quits.
   267  	switch resp, err := op.wait(ctx); {
   268  	case err != nil:
   269  		return err
   270  	case resp.Error != nil:
   271  		return resp.Error
   272  	case len(resp.Result) == 0:
   273  		return ErrNoResult
   274  	default:
   275  		return json.Unmarshal(resp.Result, &result)
   276  	}
   277  }
   278  
   279  // BatchCall sends all given requests as a single batch and waits for the server
   280  // to return a response for all of them.
   281  //
   282  // In contrast to Call, BatchCall only returns I/O errors. Any error specific to
   283  // a request is reported through the Error field of the corresponding BatchElem.
   284  //
   285  // Note that batch calls may not be executed atomically on the server side.
   286  func (c *Client) BatchCall(b []BatchElem) error {
   287  	ctx := context.Background()
   288  	return c.BatchCallContext(ctx, b)
   289  }
   290  
   291  // BatchCall sends all given requests as a single batch and waits for the server
   292  // to return a response for all of them. The wait duration is bounded by the
   293  // context's deadline.
   294  //
   295  // In contrast to CallContext, BatchCallContext only returns errors that have occurred
   296  // while sending the request. Any error specific to a request is reported through the
   297  // Error field of the corresponding BatchElem.
   298  //
   299  // Note that batch calls may not be executed atomically on the server side.
   300  func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error {
   301  	msgs := make([]*jsonrpcMessage, len(b))
   302  	op := &requestOp{
   303  		ids:  make([]json.RawMessage, len(b)),
   304  		resp: make(chan *jsonrpcMessage, len(b)),
   305  	}
   306  	for i, elem := range b {
   307  		msg, err := c.newMessage(elem.Method, elem.Args...)
   308  		if err != nil {
   309  			return err
   310  		}
   311  		msgs[i] = msg
   312  		op.ids[i] = msg.ID
   313  	}
   314  
   315  	var err error
   316  	if c.isHTTP {
   317  		err = c.sendBatchHTTP(ctx, op, msgs)
   318  	} else {
   319  		err = c.send(ctx, op, msgs)
   320  	}
   321  
   322  	// Wait for all responses to come back.
   323  	for n := 0; n < len(b) && err == nil; n++ {
   324  		var resp *jsonrpcMessage
   325  		resp, err = op.wait(ctx)
   326  		if err != nil {
   327  			break
   328  		}
   329  		// Find the element corresponding to this response.
   330  		// The element is guaranteed to be present because dispatch
   331  		// only sends valid IDs to our channel.
   332  		var elem *BatchElem
   333  		for i := range msgs {
   334  			if bytes.Equal(msgs[i].ID, resp.ID) {
   335  				elem = &b[i]
   336  				break
   337  			}
   338  		}
   339  		if resp.Error != nil {
   340  			elem.Error = resp.Error
   341  			continue
   342  		}
   343  		if len(resp.Result) == 0 {
   344  			elem.Error = ErrNoResult
   345  			continue
   346  		}
   347  		elem.Error = json.Unmarshal(resp.Result, elem.Result)
   348  	}
   349  	return err
   350  }
   351  
   352  // EthSubscribe registers a subscripion under the "eth" namespace.
   353  func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   354  	return c.Subscribe(ctx, "eth", channel, args...)
   355  }
   356  
   357  // ShhSubscribe registers a subscripion under the "shh" namespace.
   358  func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   359  	return c.Subscribe(ctx, "shh", channel, args...)
   360  }
   361  
   362  // Subscribe calls the "<namespace>_subscribe" method with the given arguments,
   363  // registering a subscription. Server notifications for the subscription are
   364  // sent to the given channel. The element type of the channel must match the
   365  // expected type of content returned by the subscription.
   366  //
   367  // The context argument cancels the RPC request that sets up the subscription but has no
   368  // effect on the subscription after Subscribe has returned.
   369  //
   370  // Slow subscribers will be dropped eventually. Client buffers up to 8000 notifications
   371  // before considering the subscriber dead. The subscription Err channel will receive
   372  // ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure
   373  // that the channel usually has at least one reader to prevent this issue.
   374  func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   375  	// Check type of channel first.
   376  	chanVal := reflect.ValueOf(channel)
   377  	if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 {
   378  		panic("first argument to Subscribe must be a writable channel")
   379  	}
   380  	if chanVal.IsNil() {
   381  		panic("channel given to Subscribe must not be nil")
   382  	}
   383  	if c.isHTTP {
   384  		return nil, ErrNotificationsUnsupported
   385  	}
   386  
   387  	msg, err := c.newMessage(namespace+subscribeMethodSuffix, args...)
   388  	if err != nil {
   389  		return nil, err
   390  	}
   391  	op := &requestOp{
   392  		ids:  []json.RawMessage{msg.ID},
   393  		resp: make(chan *jsonrpcMessage),
   394  		sub:  newClientSubscription(c, namespace, chanVal),
   395  	}
   396  
   397  	// Send the subscription request.
   398  	// The arrival and validity of the response is signaled on sub.quit.
   399  	if err := c.send(ctx, op, msg); err != nil {
   400  		return nil, err
   401  	}
   402  	if _, err := op.wait(ctx); err != nil {
   403  		return nil, err
   404  	}
   405  	return op.sub, nil
   406  }
   407  
   408  func (c *Client) newMessage(method string, paramsIn ...interface{}) (*jsonrpcMessage, error) {
   409  	params, err := json.Marshal(paramsIn)
   410  	if err != nil {
   411  		return nil, err
   412  	}
   413  	return &jsonrpcMessage{Version: "2.0", ID: c.nextID(), Method: method, Params: params}, nil
   414  }
   415  
   416  // send registers op with the dispatch loop, then sends msg on the connection.
   417  // if sending fails, op is deregistered.
   418  func (c *Client) send(ctx context.Context, op *requestOp, msg interface{}) error {
   419  	select {
   420  	case c.requestOp <- op:
   421  		log.Trace("", "msg", log.Lazy{Fn: func() string {
   422  			return fmt.Sprint("sending ", msg)
   423  		}})
   424  		err := c.write(ctx, msg)
   425  		c.sendDone <- err
   426  		return err
   427  	case <-ctx.Done():
   428  		// This can happen if the client is overloaded or unable to keep up with
   429  		// subscription notifications.
   430  		return ctx.Err()
   431  	case <-c.didQuit:
   432  		return ErrClientQuit
   433  	}
   434  }
   435  
   436  func (c *Client) write(ctx context.Context, msg interface{}) error {
   437  	deadline, ok := ctx.Deadline()
   438  	if !ok {
   439  		deadline = time.Now().Add(defaultWriteTimeout)
   440  	}
   441  	// The previous write failed. Try to establish a new connection.
   442  	if c.writeConn == nil {
   443  		if err := c.reconnect(ctx); err != nil {
   444  			return err
   445  		}
   446  	}
   447  	c.writeConn.SetWriteDeadline(deadline)
   448  	err := json.NewEncoder(c.writeConn).Encode(msg)
   449  	if err != nil {
   450  		c.writeConn = nil
   451  	}
   452  	return err
   453  }
   454  
   455  func (c *Client) reconnect(ctx context.Context) error {
   456  	newconn, err := c.connectFunc(ctx)
   457  	if err != nil {
   458  		log.Trace(fmt.Sprintf("reconnect failed: %v", err))
   459  		return err
   460  	}
   461  	select {
   462  	case c.reconnected <- newconn:
   463  		c.writeConn = newconn
   464  		return nil
   465  	case <-c.didQuit:
   466  		newconn.Close()
   467  		return ErrClientQuit
   468  	}
   469  }
   470  
   471  // dispatch is the main loop of the client.
   472  // It sends read messages to waiting calls to Call and BatchCall
   473  // and subscription notifications to registered subscriptions.
   474  func (c *Client) dispatch(conn net.Conn) {
   475  	// Spawn the initial read loop.
   476  	go c.read(conn)
   477  
   478  	var (
   479  		lastOp        *requestOp    // tracks last send operation
   480  		requestOpLock = c.requestOp // nil while the send lock is held
   481  		reading       = true        // if true, a read loop is running
   482  	)
   483  	defer close(c.didQuit)
   484  	defer func() {
   485  		c.closeRequestOps(ErrClientQuit)
   486  		conn.Close()
   487  		if reading {
   488  			// Empty read channels until read is dead.
   489  			for {
   490  				select {
   491  				case <-c.readResp:
   492  				case <-c.readErr:
   493  					return
   494  				}
   495  			}
   496  		}
   497  	}()
   498  
   499  	for {
   500  		select {
   501  		case <-c.close:
   502  			return
   503  
   504  		// Read path.
   505  		case batch := <-c.readResp:
   506  			for _, msg := range batch {
   507  				switch {
   508  				case msg.isNotification():
   509  					log.Trace("", "msg", log.Lazy{Fn: func() string {
   510  						return fmt.Sprint("<-readResp: notification ", msg)
   511  					}})
   512  					c.handleNotification(msg)
   513  				case msg.isResponse():
   514  					log.Trace("", "msg", log.Lazy{Fn: func() string {
   515  						return fmt.Sprint("<-readResp: response ", msg)
   516  					}})
   517  					c.handleResponse(msg)
   518  				default:
   519  					log.Debug("", "msg", log.Lazy{Fn: func() string {
   520  						return fmt.Sprint("<-readResp: dropping weird message", msg)
   521  					}})
   522  					// TODO: maybe close
   523  				}
   524  			}
   525  
   526  		case err := <-c.readErr:
   527  			log.Debug(fmt.Sprintf("<-readErr: %v", err))
   528  			c.closeRequestOps(err)
   529  			conn.Close()
   530  			reading = false
   531  
   532  		case newconn := <-c.reconnected:
   533  			log.Debug(fmt.Sprintf("<-reconnected: (reading=%t) %v", reading, conn.RemoteAddr()))
   534  			if reading {
   535  				// Wait for the previous read loop to exit. This is a rare case.
   536  				conn.Close()
   537  				<-c.readErr
   538  			}
   539  			go c.read(newconn)
   540  			reading = true
   541  			conn = newconn
   542  
   543  		// Send path.
   544  		case op := <-requestOpLock:
   545  			// Stop listening for further send ops until the current one is done.
   546  			requestOpLock = nil
   547  			lastOp = op
   548  			for _, id := range op.ids {
   549  				c.respWait[string(id)] = op
   550  			}
   551  
   552  		case err := <-c.sendDone:
   553  			if err != nil {
   554  				// Remove response handlers for the last send. We remove those here
   555  				// because the error is already handled in Call or BatchCall. When the
   556  				// read loop goes down, it will signal all other current operations.
   557  				for _, id := range lastOp.ids {
   558  					delete(c.respWait, string(id))
   559  				}
   560  			}
   561  			// Listen for send ops again.
   562  			requestOpLock = c.requestOp
   563  			lastOp = nil
   564  		}
   565  	}
   566  }
   567  
   568  // closeRequestOps unblocks pending send ops and active subscriptions.
   569  func (c *Client) closeRequestOps(err error) {
   570  	didClose := make(map[*requestOp]bool)
   571  
   572  	for id, op := range c.respWait {
   573  		// Remove the op so that later calls will not close op.resp again.
   574  		delete(c.respWait, id)
   575  
   576  		if !didClose[op] {
   577  			op.err = err
   578  			close(op.resp)
   579  			didClose[op] = true
   580  		}
   581  	}
   582  	for id, sub := range c.subs {
   583  		delete(c.subs, id)
   584  		sub.quitWithError(err, false)
   585  	}
   586  }
   587  
   588  func (c *Client) handleNotification(msg *jsonrpcMessage) {
   589  	if !strings.HasSuffix(msg.Method, notificationMethodSuffix) {
   590  		log.Debug(fmt.Sprint("dropping non-subscription message: ", msg))
   591  		return
   592  	}
   593  	var subResult struct {
   594  		ID     string          `json:"subscription"`
   595  		Result json.RawMessage `json:"result"`
   596  	}
   597  	if err := json.Unmarshal(msg.Params, &subResult); err != nil {
   598  		log.Debug(fmt.Sprint("dropping invalid subscription message: ", msg))
   599  		return
   600  	}
   601  	if c.subs[subResult.ID] != nil {
   602  		c.subs[subResult.ID].deliver(subResult.Result)
   603  	}
   604  }
   605  
   606  func (c *Client) handleResponse(msg *jsonrpcMessage) {
   607  	op := c.respWait[string(msg.ID)]
   608  	if op == nil {
   609  		log.Debug(fmt.Sprintf("unsolicited response %v", msg))
   610  		return
   611  	}
   612  	delete(c.respWait, string(msg.ID))
   613  	// For normal responses, just forward the reply to Call/BatchCall.
   614  	if op.sub == nil {
   615  		op.resp <- msg
   616  		return
   617  	}
   618  	// For subscription responses, start the subscription if the server
   619  	// indicates success. EthSubscribe gets unblocked in either case through
   620  	// the op.resp channel.
   621  	defer close(op.resp)
   622  	if msg.Error != nil {
   623  		op.err = msg.Error
   624  		return
   625  	}
   626  	if op.err = json.Unmarshal(msg.Result, &op.sub.subid); op.err == nil {
   627  		go op.sub.start()
   628  		c.subs[op.sub.subid] = op.sub
   629  	}
   630  }
   631  
   632  // Reading happens on a dedicated goroutine.
   633  
   634  func (c *Client) read(conn net.Conn) error {
   635  	var (
   636  		buf json.RawMessage
   637  		dec = json.NewDecoder(conn)
   638  	)
   639  	readMessage := func() (rs []*jsonrpcMessage, err error) {
   640  		buf = buf[:0]
   641  		if err = dec.Decode(&buf); err != nil {
   642  			return nil, err
   643  		}
   644  		if isBatch(buf) {
   645  			err = json.Unmarshal(buf, &rs)
   646  		} else {
   647  			rs = make([]*jsonrpcMessage, 1)
   648  			err = json.Unmarshal(buf, &rs[0])
   649  		}
   650  		return rs, err
   651  	}
   652  
   653  	for {
   654  		resp, err := readMessage()
   655  		if err != nil {
   656  			c.readErr <- err
   657  			return err
   658  		}
   659  		c.readResp <- resp
   660  	}
   661  }
   662  
   663  // Subscriptions.
   664  
   665  // A ClientSubscription represents a subscription established through EthSubscribe.
   666  type ClientSubscription struct {
   667  	client    *Client
   668  	etype     reflect.Type
   669  	channel   reflect.Value
   670  	namespace string
   671  	subid     string
   672  	in        chan json.RawMessage
   673  
   674  	quitOnce sync.Once     // ensures quit is closed once
   675  	quit     chan struct{} // quit is closed when the subscription exits
   676  	errOnce  sync.Once     // ensures err is closed once
   677  	err      chan error
   678  }
   679  
   680  func newClientSubscription(c *Client, namespace string, channel reflect.Value) *ClientSubscription {
   681  	sub := &ClientSubscription{
   682  		client:    c,
   683  		namespace: namespace,
   684  		etype:     channel.Type().Elem(),
   685  		channel:   channel,
   686  		quit:      make(chan struct{}),
   687  		err:       make(chan error, 1),
   688  		in:        make(chan json.RawMessage),
   689  	}
   690  	return sub
   691  }
   692  
   693  // Err returns the subscription error channel. The intended use of Err is to schedule
   694  // resubscription when the client connection is closed unexpectedly.
   695  //
   696  // The error channel receives a value when the subscription has ended due
   697  // to an error. The received error is nil if Close has been called
   698  // on the underlying client and no other error has occurred.
   699  //
   700  // The error channel is closed when Unsubscribe is called on the subscription.
   701  func (sub *ClientSubscription) Err() <-chan error {
   702  	return sub.err
   703  }
   704  
   705  // Unsubscribe unsubscribes the notification and closes the error channel.
   706  // It can safely be called more than once.
   707  func (sub *ClientSubscription) Unsubscribe() {
   708  	sub.quitWithError(nil, true)
   709  	sub.errOnce.Do(func() { close(sub.err) })
   710  }
   711  
   712  func (sub *ClientSubscription) quitWithError(err error, unsubscribeServer bool) {
   713  	sub.quitOnce.Do(func() {
   714  		// The dispatch loop won't be able to execute the unsubscribe call
   715  		// if it is blocked on deliver. Close sub.quit first because it
   716  		// unblocks deliver.
   717  		close(sub.quit)
   718  		if unsubscribeServer {
   719  			sub.requestUnsubscribe()
   720  		}
   721  		if err != nil {
   722  			if err == ErrClientQuit {
   723  				err = nil // Adhere to subscription semantics.
   724  			}
   725  			sub.err <- err
   726  		}
   727  	})
   728  }
   729  
   730  func (sub *ClientSubscription) deliver(result json.RawMessage) (ok bool) {
   731  	select {
   732  	case sub.in <- result:
   733  		return true
   734  	case <-sub.quit:
   735  		return false
   736  	}
   737  }
   738  
   739  func (sub *ClientSubscription) start() {
   740  	sub.quitWithError(sub.forward())
   741  }
   742  
   743  func (sub *ClientSubscription) forward() (err error, unsubscribeServer bool) {
   744  	cases := []reflect.SelectCase{
   745  		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.quit)},
   746  		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.in)},
   747  		{Dir: reflect.SelectSend, Chan: sub.channel},
   748  	}
   749  	buffer := list.New()
   750  	defer buffer.Init()
   751  	for {
   752  		var chosen int
   753  		var recv reflect.Value
   754  		if buffer.Len() == 0 {
   755  			// Idle, omit send case.
   756  			chosen, recv, _ = reflect.Select(cases[:2])
   757  		} else {
   758  			// Non-empty buffer, send the first queued item.
   759  			cases[2].Send = reflect.ValueOf(buffer.Front().Value)
   760  			chosen, recv, _ = reflect.Select(cases)
   761  		}
   762  
   763  		switch chosen {
   764  		case 0: // <-sub.quit
   765  			return nil, false
   766  		case 1: // <-sub.in
   767  			val, err := sub.unmarshal(recv.Interface().(json.RawMessage))
   768  			if err != nil {
   769  				return err, true
   770  			}
   771  			if buffer.Len() == maxClientSubscriptionBuffer {
   772  				return ErrSubscriptionQueueOverflow, true
   773  			}
   774  			buffer.PushBack(val)
   775  		case 2: // sub.channel<-
   776  			cases[2].Send = reflect.Value{} // Don't hold onto the value.
   777  			buffer.Remove(buffer.Front())
   778  		}
   779  	}
   780  }
   781  
   782  func (sub *ClientSubscription) unmarshal(result json.RawMessage) (interface{}, error) {
   783  	val := reflect.New(sub.etype)
   784  	err := json.Unmarshal(result, val.Interface())
   785  	return val.Elem().Interface(), err
   786  }
   787  
   788  func (sub *ClientSubscription) requestUnsubscribe() error {
   789  	var result interface{}
   790  	return sub.client.Call(&result, sub.namespace+unsubscribeMethodSuffix, sub.subid)
   791  }