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