client.go 22 KB

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