client.go 22 KB

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