client.go 23 KB

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