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