client.go 24 KB

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