github.com/digdeepmining/go-atheios@v1.5.13-0.20180902133602-d5687a2e6f43/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  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"net"
    26  	"net/url"
    27  	"reflect"
    28  	"strconv"
    29  	"sync"
    30  	"sync/atomic"
    31  	"time"
    32  
    33  	"github.com/atheioschain/go-atheios/logger"
    34  	"github.com/atheioschain/go-atheios/logger/glog"
    35  	"golang.org/x/net/context"
    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 calls the "eth_subscribe" method with the given arguments,
   353  // registering a subscription. Server notifications for the subscription are
   354  // sent to the given channel. The element type of the channel must match the
   355  // expected type of content returned by the subscription.
   356  //
   357  // The context argument cancels the RPC request that sets up the subscription but has no
   358  // effect on the subscription after EthSubscribe has returned.
   359  //
   360  // Slow subscribers will be dropped eventually. Client buffers up to 8000 notifications
   361  // before considering the subscriber dead. The subscription Err channel will receive
   362  // ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure
   363  // that the channel usually has at least one reader to prevent this issue.
   364  func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
   365  	// Check type of channel first.
   366  	chanVal := reflect.ValueOf(channel)
   367  	if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 {
   368  		panic("first argument to EthSubscribe must be a writable channel")
   369  	}
   370  	if chanVal.IsNil() {
   371  		panic("channel given to EthSubscribe must not be nil")
   372  	}
   373  	if c.isHTTP {
   374  		return nil, ErrNotificationsUnsupported
   375  	}
   376  
   377  	msg, err := c.newMessage(subscribeMethod, args...)
   378  	if err != nil {
   379  		return nil, err
   380  	}
   381  	op := &requestOp{
   382  		ids:  []json.RawMessage{msg.ID},
   383  		resp: make(chan *jsonrpcMessage),
   384  		sub:  newClientSubscription(c, chanVal),
   385  	}
   386  
   387  	// Send the subscription request.
   388  	// The arrival and validity of the response is signaled on sub.quit.
   389  	if err := c.send(ctx, op, msg); err != nil {
   390  		return nil, err
   391  	}
   392  	if _, err := op.wait(ctx); err != nil {
   393  		return nil, err
   394  	}
   395  	return op.sub, nil
   396  }
   397  
   398  func (c *Client) newMessage(method string, paramsIn ...interface{}) (*jsonrpcMessage, error) {
   399  	params, err := json.Marshal(paramsIn)
   400  	if err != nil {
   401  		return nil, err
   402  	}
   403  	return &jsonrpcMessage{Version: "2.0", ID: c.nextID(), Method: method, Params: params}, nil
   404  }
   405  
   406  // send registers op with the dispatch loop, then sends msg on the connection.
   407  // if sending fails, op is deregistered.
   408  func (c *Client) send(ctx context.Context, op *requestOp, msg interface{}) error {
   409  	select {
   410  	case c.requestOp <- op:
   411  		if glog.V(logger.Detail) {
   412  			glog.Info("sending ", msg)
   413  		}
   414  		err := c.write(ctx, msg)
   415  		c.sendDone <- err
   416  		return err
   417  	case <-ctx.Done():
   418  		// This can happen if the client is overloaded or unable to keep up with
   419  		// subscription notifications.
   420  		return ctx.Err()
   421  	case <-c.didQuit:
   422  		return ErrClientQuit
   423  	}
   424  }
   425  
   426  func (c *Client) write(ctx context.Context, msg interface{}) error {
   427  	deadline, ok := ctx.Deadline()
   428  	if !ok {
   429  		deadline = time.Now().Add(defaultWriteTimeout)
   430  	}
   431  	// The previous write failed. Try to establish a new connection.
   432  	if c.writeConn == nil {
   433  		if err := c.reconnect(ctx); err != nil {
   434  			return err
   435  		}
   436  	}
   437  	c.writeConn.SetWriteDeadline(deadline)
   438  	err := json.NewEncoder(c.writeConn).Encode(msg)
   439  	if err != nil {
   440  		c.writeConn = nil
   441  	}
   442  	return err
   443  }
   444  
   445  func (c *Client) reconnect(ctx context.Context) error {
   446  	newconn, err := c.connectFunc(ctx)
   447  	if err != nil {
   448  		glog.V(logger.Detail).Infof("reconnect failed: %v", err)
   449  		return err
   450  	}
   451  	select {
   452  	case c.reconnected <- newconn:
   453  		c.writeConn = newconn
   454  		return nil
   455  	case <-c.didQuit:
   456  		newconn.Close()
   457  		return ErrClientQuit
   458  	}
   459  }
   460  
   461  // dispatch is the main loop of the client.
   462  // It sends read messages to waiting calls to Call and BatchCall
   463  // and subscription notifications to registered subscriptions.
   464  func (c *Client) dispatch(conn net.Conn) {
   465  	// Spawn the initial read loop.
   466  	go c.read(conn)
   467  
   468  	var (
   469  		lastOp        *requestOp    // tracks last send operation
   470  		requestOpLock = c.requestOp // nil while the send lock is held
   471  		reading       = true        // if true, a read loop is running
   472  	)
   473  	defer close(c.didQuit)
   474  	defer func() {
   475  		c.closeRequestOps(ErrClientQuit)
   476  		conn.Close()
   477  		if reading {
   478  			// Empty read channels until read is dead.
   479  			for {
   480  				select {
   481  				case <-c.readResp:
   482  				case <-c.readErr:
   483  					return
   484  				}
   485  			}
   486  		}
   487  	}()
   488  
   489  	for {
   490  		select {
   491  		case <-c.close:
   492  			return
   493  
   494  		// Read path.
   495  		case batch := <-c.readResp:
   496  			for _, msg := range batch {
   497  				switch {
   498  				case msg.isNotification():
   499  					if glog.V(logger.Detail) {
   500  						glog.Info("<-readResp: notification ", msg)
   501  					}
   502  					c.handleNotification(msg)
   503  				case msg.isResponse():
   504  					if glog.V(logger.Detail) {
   505  						glog.Info("<-readResp: response ", msg)
   506  					}
   507  					c.handleResponse(msg)
   508  				default:
   509  					if glog.V(logger.Debug) {
   510  						glog.Error("<-readResp: dropping weird message", msg)
   511  					}
   512  					// TODO: maybe close
   513  				}
   514  			}
   515  
   516  		case err := <-c.readErr:
   517  			glog.V(logger.Debug).Infof("<-readErr: %v", err)
   518  			c.closeRequestOps(err)
   519  			conn.Close()
   520  			reading = false
   521  
   522  		case newconn := <-c.reconnected:
   523  			glog.V(logger.Debug).Infof("<-reconnected: (reading=%t) %v", reading, conn.RemoteAddr())
   524  			if reading {
   525  				// Wait for the previous read loop to exit. This is a rare case.
   526  				conn.Close()
   527  				<-c.readErr
   528  			}
   529  			go c.read(newconn)
   530  			reading = true
   531  			conn = newconn
   532  
   533  		// Send path.
   534  		case op := <-requestOpLock:
   535  			// Stop listening for further send ops until the current one is done.
   536  			requestOpLock = nil
   537  			lastOp = op
   538  			for _, id := range op.ids {
   539  				c.respWait[string(id)] = op
   540  			}
   541  
   542  		case err := <-c.sendDone:
   543  			if err != nil {
   544  				// Remove response handlers for the last send. We remove those here
   545  				// because the error is already handled in Call or BatchCall. When the
   546  				// read loop goes down, it will signal all other current operations.
   547  				for _, id := range lastOp.ids {
   548  					delete(c.respWait, string(id))
   549  				}
   550  			}
   551  			// Listen for send ops again.
   552  			requestOpLock = c.requestOp
   553  			lastOp = nil
   554  		}
   555  	}
   556  }
   557  
   558  // closeRequestOps unblocks pending send ops and active subscriptions.
   559  func (c *Client) closeRequestOps(err error) {
   560  	didClose := make(map[*requestOp]bool)
   561  
   562  	for id, op := range c.respWait {
   563  		// Remove the op so that later calls will not close op.resp again.
   564  		delete(c.respWait, id)
   565  
   566  		if !didClose[op] {
   567  			op.err = err
   568  			close(op.resp)
   569  			didClose[op] = true
   570  		}
   571  	}
   572  	for id, sub := range c.subs {
   573  		delete(c.subs, id)
   574  		sub.quitWithError(err, false)
   575  	}
   576  }
   577  
   578  func (c *Client) handleNotification(msg *jsonrpcMessage) {
   579  	if msg.Method != notificationMethod {
   580  		glog.V(logger.Debug).Info("dropping non-subscription message: ", msg)
   581  		return
   582  	}
   583  	var subResult struct {
   584  		ID     string          `json:"subscription"`
   585  		Result json.RawMessage `json:"result"`
   586  	}
   587  	if err := json.Unmarshal(msg.Params, &subResult); err != nil {
   588  		glog.V(logger.Debug).Info("dropping invalid subscription message: ", msg)
   589  		return
   590  	}
   591  	if c.subs[subResult.ID] != nil {
   592  		c.subs[subResult.ID].deliver(subResult.Result)
   593  	}
   594  }
   595  
   596  func (c *Client) handleResponse(msg *jsonrpcMessage) {
   597  	op := c.respWait[string(msg.ID)]
   598  	if op == nil {
   599  		glog.V(logger.Debug).Infof("unsolicited response %v", msg)
   600  		return
   601  	}
   602  	delete(c.respWait, string(msg.ID))
   603  	// For normal responses, just forward the reply to Call/BatchCall.
   604  	if op.sub == nil {
   605  		op.resp <- msg
   606  		return
   607  	}
   608  	// For subscription responses, start the subscription if the server
   609  	// indicates success. EthSubscribe gets unblocked in either case through
   610  	// the op.resp channel.
   611  	defer close(op.resp)
   612  	if msg.Error != nil {
   613  		op.err = msg.Error
   614  		return
   615  	}
   616  	if op.err = json.Unmarshal(msg.Result, &op.sub.subid); op.err == nil {
   617  		go op.sub.start()
   618  		c.subs[op.sub.subid] = op.sub
   619  	}
   620  }
   621  
   622  // Reading happens on a dedicated goroutine.
   623  
   624  func (c *Client) read(conn net.Conn) error {
   625  	var (
   626  		buf json.RawMessage
   627  		dec = json.NewDecoder(conn)
   628  	)
   629  	readMessage := func() (rs []*jsonrpcMessage, err error) {
   630  		buf = buf[:0]
   631  		if err = dec.Decode(&buf); err != nil {
   632  			return nil, err
   633  		}
   634  		if isBatch(buf) {
   635  			err = json.Unmarshal(buf, &rs)
   636  		} else {
   637  			rs = make([]*jsonrpcMessage, 1)
   638  			err = json.Unmarshal(buf, &rs[0])
   639  		}
   640  		return rs, err
   641  	}
   642  
   643  	for {
   644  		resp, err := readMessage()
   645  		if err != nil {
   646  			c.readErr <- err
   647  			return err
   648  		}
   649  		c.readResp <- resp
   650  	}
   651  }
   652  
   653  // Subscriptions.
   654  
   655  // A ClientSubscription represents a subscription established through EthSubscribe.
   656  type ClientSubscription struct {
   657  	client  *Client
   658  	etype   reflect.Type
   659  	channel reflect.Value
   660  	subid   string
   661  	in      chan json.RawMessage
   662  
   663  	quitOnce sync.Once     // ensures quit is closed once
   664  	quit     chan struct{} // quit is closed when the subscription exits
   665  	errOnce  sync.Once     // ensures err is closed once
   666  	err      chan error
   667  }
   668  
   669  func newClientSubscription(c *Client, channel reflect.Value) *ClientSubscription {
   670  	sub := &ClientSubscription{
   671  		client:  c,
   672  		etype:   channel.Type().Elem(),
   673  		channel: channel,
   674  		quit:    make(chan struct{}),
   675  		err:     make(chan error, 1),
   676  		in:      make(chan json.RawMessage),
   677  	}
   678  	return sub
   679  }
   680  
   681  // Err returns the subscription error channel. The intended use of Err is to schedule
   682  // resubscription when the client connection is closed unexpectedly.
   683  //
   684  // The error channel receives a value when the subscription has ended due
   685  // to an error. The received error is nil if Close has been called
   686  // on the underlying client and no other error has occurred.
   687  //
   688  // The error channel is closed when Unsubscribe is called on the subscription.
   689  func (sub *ClientSubscription) Err() <-chan error {
   690  	return sub.err
   691  }
   692  
   693  // Unsubscribe unsubscribes the notification and closes the error channel.
   694  // It can safely be called more than once.
   695  func (sub *ClientSubscription) Unsubscribe() {
   696  	sub.quitWithError(nil, true)
   697  	sub.errOnce.Do(func() { close(sub.err) })
   698  }
   699  
   700  func (sub *ClientSubscription) quitWithError(err error, unsubscribeServer bool) {
   701  	sub.quitOnce.Do(func() {
   702  		// The dispatch loop won't be able to execute the unsubscribe call
   703  		// if it is blocked on deliver. Close sub.quit first because it
   704  		// unblocks deliver.
   705  		close(sub.quit)
   706  		if unsubscribeServer {
   707  			sub.requestUnsubscribe()
   708  		}
   709  		if err != nil {
   710  			if err == ErrClientQuit {
   711  				err = nil // Adhere to subscription semantics.
   712  			}
   713  			sub.err <- err
   714  		}
   715  	})
   716  }
   717  
   718  func (sub *ClientSubscription) deliver(result json.RawMessage) (ok bool) {
   719  	select {
   720  	case sub.in <- result:
   721  		return true
   722  	case <-sub.quit:
   723  		return false
   724  	}
   725  }
   726  
   727  func (sub *ClientSubscription) start() {
   728  	sub.quitWithError(sub.forward())
   729  }
   730  
   731  func (sub *ClientSubscription) forward() (err error, unsubscribeServer bool) {
   732  	cases := []reflect.SelectCase{
   733  		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.quit)},
   734  		{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.in)},
   735  		{Dir: reflect.SelectSend, Chan: sub.channel},
   736  	}
   737  	buffer := list.New()
   738  	defer buffer.Init()
   739  	for {
   740  		var chosen int
   741  		var recv reflect.Value
   742  		if buffer.Len() == 0 {
   743  			// Idle, omit send case.
   744  			chosen, recv, _ = reflect.Select(cases[:2])
   745  		} else {
   746  			// Non-empty buffer, send the first queued item.
   747  			cases[2].Send = reflect.ValueOf(buffer.Front().Value)
   748  			chosen, recv, _ = reflect.Select(cases)
   749  		}
   750  
   751  		switch chosen {
   752  		case 0: // <-sub.quit
   753  			return nil, false
   754  		case 1: // <-sub.in
   755  			val, err := sub.unmarshal(recv.Interface().(json.RawMessage))
   756  			if err != nil {
   757  				return err, true
   758  			}
   759  			if buffer.Len() == maxClientSubscriptionBuffer {
   760  				return ErrSubscriptionQueueOverflow, true
   761  			}
   762  			buffer.PushBack(val)
   763  		case 2: // sub.channel<-
   764  			cases[2].Send = reflect.Value{} // Don't hold onto the value.
   765  			buffer.Remove(buffer.Front())
   766  		}
   767  	}
   768  }
   769  
   770  func (sub *ClientSubscription) unmarshal(result json.RawMessage) (interface{}, error) {
   771  	val := reflect.New(sub.etype)
   772  	err := json.Unmarshal(result, val.Interface())
   773  	return val.Elem().Interface(), err
   774  }
   775  
   776  func (sub *ClientSubscription) requestUnsubscribe() error {
   777  	var result interface{}
   778  	return sub.client.Call(&result, unsubscribeMethod, sub.subid)
   779  }