client.go 24 KB

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