github.com/aquanetwork/aquachain@v1.7.8/rpc/client.go (about)

     1  // Copyright 2016 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain 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  	"gitlab.com/aquachain/aquachain/common/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 aqua_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 AquaSubscribe 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  // AquaSubscribe registers a subscripion under the "aqua" namespace.
   353  func (c *Client) AquaSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   354  	return c.Subscribe(ctx, "aqua", 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  	c.writeConn.SetWriteDeadline(time.Time{})
   450  	if err != nil {
   451  		c.writeConn = nil
   452  	}
   453  	return err
   454  }
   455  
   456  func (c *Client) reconnect(ctx context.Context) error {
   457  	newconn, err := c.connectFunc(ctx)
   458  	if err != nil {
   459  		log.Trace(fmt.Sprintf("reconnect failed: %v", err))
   460  		return err
   461  	}
   462  	select {
   463  	case c.reconnected <- newconn:
   464  		c.writeConn = newconn
   465  		return nil
   466  	case <-c.didQuit:
   467  		newconn.Close()
   468  		return ErrClientQuit
   469  	}
   470  }
   471  
   472  // dispatch is the main loop of the client.
   473  // It sends read messages to waiting calls to Call and BatchCall
   474  // and subscription notifications to registered subscriptions.
   475  func (c *Client) dispatch(conn net.Conn) {
   476  	// Spawn the initial read loop.
   477  	go c.read(conn)
   478  
   479  	var (
   480  		lastOp        *requestOp    // tracks last send operation
   481  		requestOpLock = c.requestOp // nil while the send lock is held
   482  		reading       = true        // if true, a read loop is running
   483  	)
   484  	defer close(c.didQuit)
   485  	defer func() {
   486  		c.closeRequestOps(ErrClientQuit)
   487  		conn.Close()
   488  		if reading {
   489  			// Empty read channels until read is dead.
   490  			for {
   491  				select {
   492  				case <-c.readResp:
   493  				case <-c.readErr:
   494  					return
   495  				}
   496  			}
   497  		}
   498  	}()
   499  
   500  	for {
   501  		select {
   502  		case <-c.close:
   503  			return
   504  
   505  		// Read path.
   506  		case batch := <-c.readResp:
   507  			for _, msg := range batch {
   508  				switch {
   509  				case msg.isNotification():
   510  					log.Trace("", "msg", log.Lazy{Fn: func() string {
   511  						return fmt.Sprint("<-readResp: notification ", msg)
   512  					}})
   513  					c.handleNotification(msg)
   514  				case msg.isResponse():
   515  					log.Trace("", "msg", log.Lazy{Fn: func() string {
   516  						return fmt.Sprint("<-readResp: response ", msg)
   517  					}})
   518  					c.handleResponse(msg)
   519  				default:
   520  					log.Debug("", "msg", log.Lazy{Fn: func() string {
   521  						return fmt.Sprint("<-readResp: dropping weird message", msg)
   522  					}})
   523  					// TODO: maybe close
   524  				}
   525  			}
   526  
   527  		case err := <-c.readErr:
   528  			log.Debug(fmt.Sprintf("<-readErr: %v", err))
   529  			c.closeRequestOps(err)
   530  			conn.Close()
   531  			reading = false
   532  
   533  		case newconn := <-c.reconnected:
   534  			log.Debug(fmt.Sprintf("<-reconnected: (reading=%t) %v", reading, conn.RemoteAddr()))
   535  			if reading {
   536  				// Wait for the previous read loop to exit. This is a rare case.
   537  				conn.Close()
   538  				<-c.readErr
   539  			}
   540  			go c.read(newconn)
   541  			reading = true
   542  			conn = newconn
   543  
   544  		// Send path.
   545  		case op := <-requestOpLock:
   546  			// Stop listening for further send ops until the current one is done.
   547  			requestOpLock = nil
   548  			lastOp = op
   549  			for _, id := range op.ids {
   550  				c.respWait[string(id)] = op
   551  			}
   552  
   553  		case err := <-c.sendDone:
   554  			if err != nil {
   555  				// Remove response handlers for the last send. We remove those here
   556  				// because the error is already handled in Call or BatchCall. When the
   557  				// read loop goes down, it will signal all other current operations.
   558  				for _, id := range lastOp.ids {
   559  					delete(c.respWait, string(id))
   560  				}
   561  			}
   562  			// Listen for send ops again.
   563  			requestOpLock = c.requestOp
   564  			lastOp = nil
   565  		}
   566  	}
   567  }
   568  
   569  // closeRequestOps unblocks pending send ops and active subscriptions.
   570  func (c *Client) closeRequestOps(err error) {
   571  	didClose := make(map[*requestOp]bool)
   572  
   573  	for id, op := range c.respWait {
   574  		// Remove the op so that later calls will not close op.resp again.
   575  		delete(c.respWait, id)
   576  
   577  		if !didClose[op] {
   578  			op.err = err
   579  			close(op.resp)
   580  			didClose[op] = true
   581  		}
   582  	}
   583  	for id, sub := range c.subs {
   584  		delete(c.subs, id)
   585  		sub.quitWithError(err, false)
   586  	}
   587  }
   588  
   589  func (c *Client) handleNotification(msg *jsonrpcMessage) {
   590  	if !strings.HasSuffix(msg.Method, notificationMethodSuffix) {
   591  		log.Debug(fmt.Sprint("dropping non-subscription message: ", msg))
   592  		return
   593  	}
   594  	var subResult struct {
   595  		ID     string          `json:"subscription"`
   596  		Result json.RawMessage `json:"result"`
   597  	}
   598  	if err := json.Unmarshal(msg.Params, &subResult); err != nil {
   599  		log.Debug(fmt.Sprint("dropping invalid subscription message: ", msg))
   600  		return
   601  	}
   602  	if c.subs[subResult.ID] != nil {
   603  		c.subs[subResult.ID].deliver(subResult.Result)
   604  	}
   605  }
   606  
   607  func (c *Client) handleResponse(msg *jsonrpcMessage) {
   608  	op := c.respWait[string(msg.ID)]
   609  	if op == nil {
   610  		log.Debug(fmt.Sprintf("unsolicited response %v", msg))
   611  		return
   612  	}
   613  	delete(c.respWait, string(msg.ID))
   614  	// For normal responses, just forward the reply to Call/BatchCall.
   615  	if op.sub == nil {
   616  		op.resp <- msg
   617  		return
   618  	}
   619  	// For subscription responses, start the subscription if the server
   620  	// indicates success. AquaSubscribe gets unblocked in either case through
   621  	// the op.resp channel.
   622  	defer close(op.resp)
   623  	if msg.Error != nil {
   624  		op.err = msg.Error
   625  		return
   626  	}
   627  	if op.err = json.Unmarshal(msg.Result, &op.sub.subid); op.err == nil {
   628  		go op.sub.start()
   629  		c.subs[op.sub.subid] = op.sub
   630  	}
   631  }
   632  
   633  // Reading happens on a dedicated goroutine.
   634  
   635  func (c *Client) read(conn net.Conn) error {
   636  	var (
   637  		buf json.RawMessage
   638  		dec = json.NewDecoder(conn)
   639  	)
   640  	readMessage := func() (rs []*jsonrpcMessage, err error) {
   641  		buf = buf[:0]
   642  		if err = dec.Decode(&buf); err != nil {
   643  			return nil, err
   644  		}
   645  		if isBatch(buf) {
   646  			err = json.Unmarshal(buf, &rs)
   647  		} else {
   648  			rs = make([]*jsonrpcMessage, 1)
   649  			err = json.Unmarshal(buf, &rs[0])
   650  		}
   651  		return rs, err
   652  	}
   653  
   654  	for {
   655  		resp, err := readMessage()
   656  		if err != nil {
   657  			c.readErr <- err
   658  			return err
   659  		}
   660  		c.readResp <- resp
   661  	}
   662  }
   663  
   664  // Subscriptions.
   665  
   666  // A ClientSubscription represents a subscription established through AquaSubscribe.
   667  type ClientSubscription struct {
   668  	client    *Client
   669  	etype     reflect.Type
   670  	channel   reflect.Value
   671  	namespace string
   672  	subid     string
   673  	in        chan json.RawMessage
   674  
   675  	quitOnce sync.Once     // ensures quit is closed once
   676  	quit     chan struct{} // quit is closed when the subscription exits
   677  	errOnce  sync.Once     // ensures err is closed once
   678  	err      chan error
   679  }
   680  
   681  func newClientSubscription(c *Client, namespace string, channel reflect.Value) *ClientSubscription {
   682  	sub := &ClientSubscription{
   683  		client:    c,
   684  		namespace: namespace,
   685  		etype:     channel.Type().Elem(),
   686  		channel:   channel,
   687  		quit:      make(chan struct{}),
   688  		err:       make(chan error, 1),
   689  		in:        make(chan json.RawMessage),
   690  	}
   691  	return sub
   692  }
   693  
   694  // Err returns the subscription error channel. The intended use of Err is to schedule
   695  // resubscription when the client connection is closed unexpectedly.
   696  //
   697  // The error channel receives a value when the subscription has ended due
   698  // to an error. The received error is nil if Close has been called
   699  // on the underlying client and no other error has occurred.
   700  //
   701  // The error channel is closed when Unsubscribe is called on the subscription.
   702  func (sub *ClientSubscription) Err() <-chan error {
   703  	return sub.err
   704  }
   705  
   706  // Unsubscribe unsubscribes the notification and closes the error channel.
   707  // It can safely be called more than once.
   708  func (sub *ClientSubscription) Unsubscribe() {
   709  	sub.quitWithError(nil, true)
   710  	sub.errOnce.Do(func() { close(sub.err) })
   711  }
   712  
   713  func (sub *ClientSubscription) quitWithError(err error, unsubscribeServer bool) {
   714  	sub.quitOnce.Do(func() {
   715  		// The dispatch loop won't be able to execute the unsubscribe call
   716  		// if it is blocked on deliver. Close sub.quit first because it
   717  		// unblocks deliver.
   718  		close(sub.quit)
   719  		if unsubscribeServer {
   720  			sub.requestUnsubscribe()
   721  		}
   722  		if err != nil {
   723  			if err == ErrClientQuit {
   724  				err = nil // Adhere to subscription semantics.
   725  			}
   726  			sub.err <- err
   727  		}
   728  	})
   729  }
   730  
   731  func (sub *ClientSubscription) deliver(result json.RawMessage) (ok bool) {
   732  	select {
   733  	case sub.in <- result:
   734  		return true
   735  	case <-sub.quit:
   736  		return false
   737  	}
   738  }
   739  
   740  func (sub *ClientSubscription) start() {
   741  	sub.quitWithError(sub.forward())
   742  }
   743  
   744  func (sub *ClientSubscription) forward() (err error, unsubscribeServer bool) {
   745  	cases := []reflect.SelectCase{
   746  		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.quit)},
   747  		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.in)},
   748  		{Dir: reflect.SelectSend, Chan: sub.channel},
   749  	}
   750  	buffer := list.New()
   751  	defer buffer.Init()
   752  	for {
   753  		var chosen int
   754  		var recv reflect.Value
   755  		if buffer.Len() == 0 {
   756  			// Idle, omit send case.
   757  			chosen, recv, _ = reflect.Select(cases[:2])
   758  		} else {
   759  			// Non-empty buffer, send the first queued item.
   760  			cases[2].Send = reflect.ValueOf(buffer.Front().Value)
   761  			chosen, recv, _ = reflect.Select(cases)
   762  		}
   763  
   764  		switch chosen {
   765  		case 0: // <-sub.quit
   766  			return nil, false
   767  		case 1: // <-sub.in
   768  			val, err := sub.unmarshal(recv.Interface().(json.RawMessage))
   769  			if err != nil {
   770  				return err, true
   771  			}
   772  			if buffer.Len() == maxClientSubscriptionBuffer {
   773  				return ErrSubscriptionQueueOverflow, true
   774  			}
   775  			buffer.PushBack(val)
   776  		case 2: // sub.channel<-
   777  			cases[2].Send = reflect.Value{} // Don't hold onto the value.
   778  			buffer.Remove(buffer.Front())
   779  		}
   780  	}
   781  }
   782  
   783  func (sub *ClientSubscription) unmarshal(result json.RawMessage) (interface{}, error) {
   784  	val := reflect.New(sub.etype)
   785  	err := json.Unmarshal(result, val.Interface())
   786  	return val.Elem().Interface(), err
   787  }
   788  
   789  func (sub *ClientSubscription) requestUnsubscribe() error {
   790  	var result interface{}
   791  	return sub.client.Call(&result, sub.namespace+unsubscribeMethodSuffix, sub.subid)
   792  }