client.go 19 KB

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