client.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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. "context"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "net/url"
  24. "reflect"
  25. "strconv"
  26. "sync/atomic"
  27. "time"
  28. "github.com/ethereum/go-ethereum/log"
  29. )
  30. var (
  31. ErrClientQuit = errors.New("client is closed")
  32. ErrNoResult = errors.New("no result in JSON-RPC response")
  33. ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow")
  34. errClientReconnected = errors.New("client reconnected")
  35. errDead = errors.New("connection lost")
  36. )
  37. const (
  38. // Timeouts
  39. tcpKeepAliveInterval = 30 * time.Second
  40. defaultDialTimeout = 10 * time.Second // used if context has no deadline
  41. subscribeTimeout = 5 * time.Second // overall timeout eth_subscribe, rpc_modules calls
  42. )
  43. const (
  44. // Subscriptions are removed when the subscriber cannot keep up.
  45. //
  46. // This can be worked around by supplying a channel with sufficiently sized buffer,
  47. // but this can be inconvenient and hard to explain in the docs. Another issue with
  48. // buffered channels is that the buffer is static even though it might not be needed
  49. // most of the time.
  50. //
  51. // The approach taken here is to maintain a per-subscription linked list buffer
  52. // shrinks on demand. If the buffer reaches the size below, the subscription is
  53. // dropped.
  54. maxClientSubscriptionBuffer = 20000
  55. )
  56. // BatchElem is an element in a batch request.
  57. type BatchElem struct {
  58. Method string
  59. Args []interface{}
  60. // The result is unmarshaled into this field. Result must be set to a
  61. // non-nil pointer value of the desired type, otherwise the response will be
  62. // discarded.
  63. Result interface{}
  64. // Error is set if the server returns an error for this request, or if
  65. // unmarshaling into Result fails. It is not set for I/O errors.
  66. Error error
  67. }
  68. // Client represents a connection to an RPC server.
  69. type Client struct {
  70. idgen func() ID // for subscriptions
  71. isHTTP bool
  72. services *serviceRegistry
  73. idCounter uint32
  74. // This function, if non-nil, is called when the connection is lost.
  75. reconnectFunc reconnectFunc
  76. // writeConn is used for writing to the connection on the caller's goroutine. It should
  77. // only be accessed outside of dispatch, with the write lock held. The write lock is
  78. // taken by sending on requestOp and released by sending on sendDone.
  79. writeConn jsonWriter
  80. // for dispatch
  81. close chan struct{}
  82. closing chan struct{} // closed when client is quitting
  83. didClose chan struct{} // closed when client quits
  84. reconnected chan ServerCodec // where write/reconnect sends the new connection
  85. readOp chan readOp // read messages
  86. readErr chan error // errors from read
  87. reqInit chan *requestOp // register response IDs, takes write lock
  88. reqSent chan error // signals write completion, releases write lock
  89. reqTimeout chan *requestOp // removes response IDs when call timeout expires
  90. }
  91. type reconnectFunc func(ctx context.Context) (ServerCodec, error)
  92. type clientContextKey struct{}
  93. type clientConn struct {
  94. codec ServerCodec
  95. handler *handler
  96. }
  97. func (c *Client) newClientConn(conn ServerCodec) *clientConn {
  98. ctx := context.WithValue(context.Background(), clientContextKey{}, c)
  99. handler := newHandler(ctx, conn, c.idgen, c.services)
  100. return &clientConn{conn, handler}
  101. }
  102. func (cc *clientConn) close(err error, inflightReq *requestOp) {
  103. cc.handler.close(err, inflightReq)
  104. cc.codec.Close()
  105. }
  106. type readOp struct {
  107. msgs []*jsonrpcMessage
  108. batch bool
  109. }
  110. type requestOp struct {
  111. ids []json.RawMessage
  112. err error
  113. resp chan *jsonrpcMessage // receives up to len(ids) responses
  114. sub *ClientSubscription // only set for EthSubscribe requests
  115. }
  116. func (op *requestOp) wait(ctx context.Context, c *Client) (*jsonrpcMessage, error) {
  117. select {
  118. case <-ctx.Done():
  119. // Send the timeout to dispatch so it can remove the request IDs.
  120. select {
  121. case c.reqTimeout <- op:
  122. case <-c.closing:
  123. }
  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. // Client retrieves the client from the context, if any. This can be used to perform
  165. // 'reverse calls' in a handler method.
  166. func ClientFromContext(ctx context.Context) (*Client, bool) {
  167. client, ok := ctx.Value(clientContextKey{}).(*Client)
  168. return client, ok
  169. }
  170. func newClient(initctx context.Context, connect reconnectFunc) (*Client, error) {
  171. conn, err := connect(initctx)
  172. if err != nil {
  173. return nil, err
  174. }
  175. c := initClient(conn, randomIDGenerator(), new(serviceRegistry))
  176. c.reconnectFunc = connect
  177. return c, nil
  178. }
  179. func initClient(conn ServerCodec, idgen func() ID, services *serviceRegistry) *Client {
  180. _, isHTTP := conn.(*httpConn)
  181. c := &Client{
  182. idgen: idgen,
  183. isHTTP: isHTTP,
  184. services: services,
  185. writeConn: conn,
  186. close: make(chan struct{}),
  187. closing: make(chan struct{}),
  188. didClose: make(chan struct{}),
  189. reconnected: make(chan ServerCodec),
  190. readOp: make(chan readOp),
  191. readErr: make(chan error),
  192. reqInit: make(chan *requestOp),
  193. reqSent: make(chan error, 1),
  194. reqTimeout: make(chan *requestOp),
  195. }
  196. if !isHTTP {
  197. go c.dispatch(conn)
  198. }
  199. return c
  200. }
  201. // RegisterName creates a service for the given receiver type under the given name. When no
  202. // methods on the given receiver match the criteria to be either a RPC method or a
  203. // subscription an error is returned. Otherwise a new service is created and added to the
  204. // service collection this client provides to the server.
  205. func (c *Client) RegisterName(name string, receiver interface{}) error {
  206. return c.services.registerName(name, receiver)
  207. }
  208. func (c *Client) nextID() json.RawMessage {
  209. id := atomic.AddUint32(&c.idCounter, 1)
  210. return strconv.AppendUint(nil, uint64(id), 10)
  211. }
  212. // SupportedModules calls the rpc_modules method, retrieving the list of
  213. // APIs that are available on the server.
  214. func (c *Client) SupportedModules() (map[string]string, error) {
  215. var result map[string]string
  216. ctx, cancel := context.WithTimeout(context.Background(), subscribeTimeout)
  217. defer cancel()
  218. err := c.CallContext(ctx, &result, "rpc_modules")
  219. return result, err
  220. }
  221. // Close closes the client, aborting any in-flight requests.
  222. func (c *Client) Close() {
  223. if c.isHTTP {
  224. return
  225. }
  226. select {
  227. case c.close <- struct{}{}:
  228. <-c.didClose
  229. case <-c.didClose:
  230. }
  231. }
  232. // Call performs a JSON-RPC call with the given arguments and unmarshals into
  233. // result if no error occurred.
  234. //
  235. // The result must be a pointer so that package json can unmarshal into it. You
  236. // can also pass nil, in which case the result is ignored.
  237. func (c *Client) Call(result interface{}, method string, args ...interface{}) error {
  238. ctx := context.Background()
  239. return c.CallContext(ctx, result, method, args...)
  240. }
  241. // CallContext performs a JSON-RPC call with the given arguments. If the context is
  242. // canceled before the call has successfully returned, CallContext returns immediately.
  243. //
  244. // The result must be a pointer so that package json can unmarshal into it. You
  245. // can also pass nil, in which case the result is ignored.
  246. func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error {
  247. msg, err := c.newMessage(method, args...)
  248. if err != nil {
  249. return err
  250. }
  251. op := &requestOp{ids: []json.RawMessage{msg.ID}, resp: make(chan *jsonrpcMessage, 1)}
  252. if c.isHTTP {
  253. err = c.sendHTTP(ctx, op, msg)
  254. } else {
  255. err = c.send(ctx, op, msg)
  256. }
  257. if err != nil {
  258. return err
  259. }
  260. // dispatch has accepted the request and will close the channel when it quits.
  261. switch resp, err := op.wait(ctx, c); {
  262. case err != nil:
  263. return err
  264. case resp.Error != nil:
  265. return resp.Error
  266. case len(resp.Result) == 0:
  267. return ErrNoResult
  268. default:
  269. return json.Unmarshal(resp.Result, &result)
  270. }
  271. }
  272. // BatchCall sends all given requests as a single batch and waits for the server
  273. // to return a response for all of them.
  274. //
  275. // In contrast to Call, BatchCall only returns I/O errors. Any error specific to
  276. // a request is reported through the Error field of the corresponding BatchElem.
  277. //
  278. // Note that batch calls may not be executed atomically on the server side.
  279. func (c *Client) BatchCall(b []BatchElem) error {
  280. ctx := context.Background()
  281. return c.BatchCallContext(ctx, b)
  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. The wait duration is bounded by the
  285. // context's deadline.
  286. //
  287. // In contrast to CallContext, BatchCallContext only returns errors that have occurred
  288. // while sending the request. Any error specific to a request is reported through the
  289. // Error field of the corresponding BatchElem.
  290. //
  291. // Note that batch calls may not be executed atomically on the server side.
  292. func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error {
  293. msgs := make([]*jsonrpcMessage, len(b))
  294. op := &requestOp{
  295. ids: make([]json.RawMessage, len(b)),
  296. resp: make(chan *jsonrpcMessage, len(b)),
  297. }
  298. for i, elem := range b {
  299. msg, err := c.newMessage(elem.Method, elem.Args...)
  300. if err != nil {
  301. return err
  302. }
  303. msgs[i] = msg
  304. op.ids[i] = msg.ID
  305. }
  306. var err error
  307. if c.isHTTP {
  308. err = c.sendBatchHTTP(ctx, op, msgs)
  309. } else {
  310. err = c.send(ctx, op, msgs)
  311. }
  312. // Wait for all responses to come back.
  313. for n := 0; n < len(b) && err == nil; n++ {
  314. var resp *jsonrpcMessage
  315. resp, err = op.wait(ctx, c)
  316. if err != nil {
  317. break
  318. }
  319. // Find the element corresponding to this response.
  320. // The element is guaranteed to be present because dispatch
  321. // only sends valid IDs to our channel.
  322. var elem *BatchElem
  323. for i := range msgs {
  324. if bytes.Equal(msgs[i].ID, resp.ID) {
  325. elem = &b[i]
  326. break
  327. }
  328. }
  329. if resp.Error != nil {
  330. elem.Error = resp.Error
  331. continue
  332. }
  333. if len(resp.Result) == 0 {
  334. elem.Error = ErrNoResult
  335. continue
  336. }
  337. elem.Error = json.Unmarshal(resp.Result, elem.Result)
  338. }
  339. return err
  340. }
  341. // Notify sends a notification, i.e. a method call that doesn't expect a response.
  342. func (c *Client) Notify(ctx context.Context, method string, args ...interface{}) error {
  343. op := new(requestOp)
  344. msg, err := c.newMessage(method, args...)
  345. if err != nil {
  346. return err
  347. }
  348. msg.ID = nil
  349. if c.isHTTP {
  350. return c.sendHTTP(ctx, op, msg)
  351. } else {
  352. return c.send(ctx, op, msg)
  353. }
  354. }
  355. // EthSubscribe registers a subscripion under the "eth" namespace.
  356. func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
  357. return c.Subscribe(ctx, "eth", channel, args...)
  358. }
  359. // ShhSubscribe registers a subscripion under the "shh" namespace.
  360. func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
  361. return c.Subscribe(ctx, "shh", channel, args...)
  362. }
  363. // Subscribe calls the "<namespace>_subscribe" method with the given arguments,
  364. // registering a subscription. Server notifications for the subscription are
  365. // sent to the given channel. The element type of the channel must match the
  366. // expected type of content returned by the subscription.
  367. //
  368. // The context argument cancels the RPC request that sets up the subscription but has no
  369. // effect on the subscription after Subscribe has returned.
  370. //
  371. // Slow subscribers will be dropped eventually. Client buffers up to 8000 notifications
  372. // before considering the subscriber dead. The subscription Err channel will receive
  373. // ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure
  374. // that the channel usually has at least one reader to prevent this issue.
  375. func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error) {
  376. // Check type of channel first.
  377. chanVal := reflect.ValueOf(channel)
  378. if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 {
  379. panic("first argument to Subscribe must be a writable channel")
  380. }
  381. if chanVal.IsNil() {
  382. panic("channel given to Subscribe must not be nil")
  383. }
  384. if c.isHTTP {
  385. return nil, ErrNotificationsUnsupported
  386. }
  387. msg, err := c.newMessage(namespace+subscribeMethodSuffix, args...)
  388. if err != nil {
  389. return nil, err
  390. }
  391. op := &requestOp{
  392. ids: []json.RawMessage{msg.ID},
  393. resp: make(chan *jsonrpcMessage),
  394. sub: newClientSubscription(c, namespace, chanVal),
  395. }
  396. // Send the subscription request.
  397. // The arrival and validity of the response is signaled on sub.quit.
  398. if err := c.send(ctx, op, msg); err != nil {
  399. return nil, err
  400. }
  401. if _, err := op.wait(ctx, c); err != nil {
  402. return nil, err
  403. }
  404. return op.sub, nil
  405. }
  406. func (c *Client) newMessage(method string, paramsIn ...interface{}) (*jsonrpcMessage, error) {
  407. msg := &jsonrpcMessage{Version: vsn, ID: c.nextID(), Method: method}
  408. if paramsIn != nil { // prevent sending "params":null
  409. var err error
  410. if msg.Params, err = json.Marshal(paramsIn); err != nil {
  411. return nil, err
  412. }
  413. }
  414. return msg, nil
  415. }
  416. // send registers op with the dispatch loop, then sends msg on the connection.
  417. // if sending fails, op is deregistered.
  418. func (c *Client) send(ctx context.Context, op *requestOp, msg interface{}) error {
  419. select {
  420. case c.reqInit <- op:
  421. err := c.write(ctx, msg)
  422. c.reqSent <- err
  423. return err
  424. case <-ctx.Done():
  425. // This can happen if the client is overloaded or unable to keep up with
  426. // subscription notifications.
  427. return ctx.Err()
  428. case <-c.closing:
  429. return ErrClientQuit
  430. }
  431. }
  432. func (c *Client) write(ctx context.Context, msg interface{}) error {
  433. // The previous write failed. Try to establish a new connection.
  434. if c.writeConn == nil {
  435. if err := c.reconnect(ctx); err != nil {
  436. return err
  437. }
  438. }
  439. err := c.writeConn.Write(ctx, msg)
  440. if err != nil {
  441. c.writeConn = nil
  442. }
  443. return err
  444. }
  445. func (c *Client) reconnect(ctx context.Context) error {
  446. if c.reconnectFunc == nil {
  447. return errDead
  448. }
  449. if _, ok := ctx.Deadline(); !ok {
  450. var cancel func()
  451. ctx, cancel = context.WithTimeout(ctx, defaultDialTimeout)
  452. defer cancel()
  453. }
  454. newconn, err := c.reconnectFunc(ctx)
  455. if err != nil {
  456. log.Trace("RPC client reconnect failed", "err", err)
  457. return err
  458. }
  459. select {
  460. case c.reconnected <- newconn:
  461. c.writeConn = newconn
  462. return nil
  463. case <-c.didClose:
  464. newconn.Close()
  465. return ErrClientQuit
  466. }
  467. }
  468. // dispatch is the main loop of the client.
  469. // It sends read messages to waiting calls to Call and BatchCall
  470. // and subscription notifications to registered subscriptions.
  471. func (c *Client) dispatch(codec ServerCodec) {
  472. var (
  473. lastOp *requestOp // tracks last send operation
  474. reqInitLock = c.reqInit // nil while the send lock is held
  475. conn = c.newClientConn(codec)
  476. reading = true
  477. )
  478. defer func() {
  479. close(c.closing)
  480. if reading {
  481. conn.close(ErrClientQuit, nil)
  482. c.drainRead()
  483. }
  484. close(c.didClose)
  485. }()
  486. // Spawn the initial read loop.
  487. go c.read(codec)
  488. for {
  489. select {
  490. case <-c.close:
  491. return
  492. // Read path:
  493. case op := <-c.readOp:
  494. if op.batch {
  495. conn.handler.handleBatch(op.msgs)
  496. } else {
  497. conn.handler.handleMsg(op.msgs[0])
  498. }
  499. case err := <-c.readErr:
  500. conn.handler.log.Debug("RPC connection read error", "err", err)
  501. conn.close(err, lastOp)
  502. reading = false
  503. // Reconnect:
  504. case newcodec := <-c.reconnected:
  505. log.Debug("RPC client reconnected", "reading", reading, "conn", newcodec.RemoteAddr())
  506. if reading {
  507. // Wait for the previous read loop to exit. This is a rare case which
  508. // happens if this loop isn't notified in time after the connection breaks.
  509. // In those cases the caller will notice first and reconnect. Closing the
  510. // handler terminates all waiting requests (closing op.resp) except for
  511. // lastOp, which will be transferred to the new handler.
  512. conn.close(errClientReconnected, lastOp)
  513. c.drainRead()
  514. }
  515. go c.read(newcodec)
  516. reading = true
  517. conn = c.newClientConn(newcodec)
  518. // Re-register the in-flight request on the new handler
  519. // because that's where it will be sent.
  520. conn.handler.addRequestOp(lastOp)
  521. // Send path:
  522. case op := <-reqInitLock:
  523. // Stop listening for further requests until the current one has been sent.
  524. reqInitLock = nil
  525. lastOp = op
  526. conn.handler.addRequestOp(op)
  527. case err := <-c.reqSent:
  528. if err != nil {
  529. // Remove response handlers for the last send. When the read loop
  530. // goes down, it will signal all other current operations.
  531. conn.handler.removeRequestOp(lastOp)
  532. }
  533. // Let the next request in.
  534. reqInitLock = c.reqInit
  535. lastOp = nil
  536. case op := <-c.reqTimeout:
  537. conn.handler.removeRequestOp(op)
  538. }
  539. }
  540. }
  541. // drainRead drops read messages until an error occurs.
  542. func (c *Client) drainRead() {
  543. for {
  544. select {
  545. case <-c.readOp:
  546. case <-c.readErr:
  547. return
  548. }
  549. }
  550. }
  551. // read decodes RPC messages from a codec, feeding them into dispatch.
  552. func (c *Client) read(codec ServerCodec) {
  553. for {
  554. msgs, batch, err := codec.Read()
  555. if _, ok := err.(*json.SyntaxError); ok {
  556. codec.Write(context.Background(), errorMessage(&parseError{err.Error()}))
  557. }
  558. if err != nil {
  559. c.readErr <- err
  560. return
  561. }
  562. c.readOp <- readOp{msgs, batch}
  563. }
  564. }