client.go 19 KB

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