You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

486 lines
13 KiB

7 years ago
7 years ago
7 years ago
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
  1. package rpcclient
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "math/rand"
  7. "net"
  8. "net/http"
  9. "sync"
  10. "time"
  11. "github.com/gorilla/websocket"
  12. "github.com/pkg/errors"
  13. metrics "github.com/rcrowley/go-metrics"
  14. types "github.com/tendermint/tendermint/rpc/lib/types"
  15. cmn "github.com/tendermint/tmlibs/common"
  16. )
  17. const (
  18. defaultMaxReconnectAttempts = 25
  19. defaultWriteWait = 0
  20. defaultReadWait = 0
  21. defaultPingPeriod = 0
  22. )
  23. // WSClient is a WebSocket client. The methods of WSClient are safe for use by
  24. // multiple goroutines.
  25. type WSClient struct {
  26. cmn.BaseService
  27. conn *websocket.Conn
  28. Address string // IP:PORT or /path/to/socket
  29. Endpoint string // /websocket/url/endpoint
  30. Dialer func(string, string) (net.Conn, error)
  31. // Time between sending a ping and receiving a pong. See
  32. // https://godoc.org/github.com/rcrowley/go-metrics#Timer.
  33. PingPongLatencyTimer metrics.Timer
  34. // Single user facing channel to read RPCResponses from, closed only when the client is being stopped.
  35. ResponsesCh chan types.RPCResponse
  36. // Callback, which will be called each time after successful reconnect.
  37. onReconnect func()
  38. // internal channels
  39. send chan types.RPCRequest // user requests
  40. backlog chan types.RPCRequest // stores a single user request received during a conn failure
  41. reconnectAfter chan error // reconnect requests
  42. readRoutineQuit chan struct{} // a way for readRoutine to close writeRoutine
  43. wg sync.WaitGroup
  44. mtx sync.RWMutex
  45. sentLastPingAt time.Time
  46. reconnecting bool
  47. // Maximum reconnect attempts (0 or greater; default: 25).
  48. maxReconnectAttempts int
  49. // Time allowed to write a message to the server. 0 means block until operation succeeds.
  50. writeWait time.Duration
  51. // Time allowed to read the next message from the server. 0 means block until operation succeeds.
  52. readWait time.Duration
  53. // Send pings to server with this period. Must be less than readWait. If 0, no pings will be sent.
  54. pingPeriod time.Duration
  55. }
  56. // NewWSClient returns a new client. See the commentary on the func(*WSClient)
  57. // functions for a detailed description of how to configure ping period and
  58. // pong wait time. The endpoint argument must begin with a `/`.
  59. func NewWSClient(remoteAddr, endpoint string, options ...func(*WSClient)) *WSClient {
  60. addr, dialer := makeHTTPDialer(remoteAddr)
  61. c := &WSClient{
  62. Address: addr,
  63. Dialer: dialer,
  64. Endpoint: endpoint,
  65. PingPongLatencyTimer: metrics.NewTimer(),
  66. maxReconnectAttempts: defaultMaxReconnectAttempts,
  67. readWait: defaultReadWait,
  68. writeWait: defaultWriteWait,
  69. pingPeriod: defaultPingPeriod,
  70. }
  71. c.BaseService = *cmn.NewBaseService(nil, "WSClient", c)
  72. for _, option := range options {
  73. option(c)
  74. }
  75. return c
  76. }
  77. // MaxReconnectAttempts sets the maximum number of reconnect attempts before returning an error.
  78. // It should only be used in the constructor and is not Goroutine-safe.
  79. func MaxReconnectAttempts(max int) func(*WSClient) {
  80. return func(c *WSClient) {
  81. c.maxReconnectAttempts = max
  82. }
  83. }
  84. // ReadWait sets the amount of time to wait before a websocket read times out.
  85. // It should only be used in the constructor and is not Goroutine-safe.
  86. func ReadWait(readWait time.Duration) func(*WSClient) {
  87. return func(c *WSClient) {
  88. c.readWait = readWait
  89. }
  90. }
  91. // WriteWait sets the amount of time to wait before a websocket write times out.
  92. // It should only be used in the constructor and is not Goroutine-safe.
  93. func WriteWait(writeWait time.Duration) func(*WSClient) {
  94. return func(c *WSClient) {
  95. c.writeWait = writeWait
  96. }
  97. }
  98. // PingPeriod sets the duration for sending websocket pings.
  99. // It should only be used in the constructor - not Goroutine-safe.
  100. func PingPeriod(pingPeriod time.Duration) func(*WSClient) {
  101. return func(c *WSClient) {
  102. c.pingPeriod = pingPeriod
  103. }
  104. }
  105. // OnReconnect sets the callback, which will be called every time after
  106. // successful reconnect.
  107. func OnReconnect(cb func()) func(*WSClient) {
  108. return func(c *WSClient) {
  109. c.onReconnect = cb
  110. }
  111. }
  112. // String returns WS client full address.
  113. func (c *WSClient) String() string {
  114. return fmt.Sprintf("%s (%s)", c.Address, c.Endpoint)
  115. }
  116. // OnStart implements cmn.Service by dialing a server and creating read and
  117. // write routines.
  118. func (c *WSClient) OnStart() error {
  119. err := c.dial()
  120. if err != nil {
  121. return err
  122. }
  123. c.ResponsesCh = make(chan types.RPCResponse)
  124. c.send = make(chan types.RPCRequest)
  125. // 1 additional error may come from the read/write
  126. // goroutine depending on which failed first.
  127. c.reconnectAfter = make(chan error, 1)
  128. // capacity for 1 request. a user won't be able to send more because the send
  129. // channel is unbuffered.
  130. c.backlog = make(chan types.RPCRequest, 1)
  131. c.startReadWriteRoutines()
  132. go c.reconnectRoutine()
  133. return nil
  134. }
  135. // OnStop implements cmn.Service.
  136. func (c *WSClient) OnStop() {}
  137. // Stop overrides cmn.Service#Stop. There is no other way to wait until Quit
  138. // channel is closed.
  139. func (c *WSClient) Stop() error {
  140. if err := c.BaseService.Stop(); err != nil {
  141. return err
  142. }
  143. // only close user-facing channels when we can't write to them
  144. c.wg.Wait()
  145. close(c.ResponsesCh)
  146. return nil
  147. }
  148. // IsReconnecting returns true if the client is reconnecting right now.
  149. func (c *WSClient) IsReconnecting() bool {
  150. c.mtx.RLock()
  151. defer c.mtx.RUnlock()
  152. return c.reconnecting
  153. }
  154. // IsActive returns true if the client is running and not reconnecting.
  155. func (c *WSClient) IsActive() bool {
  156. return c.IsRunning() && !c.IsReconnecting()
  157. }
  158. // Send the given RPC request to the server. Results will be available on
  159. // ResponsesCh, errors, if any, on ErrorsCh. Will block until send succeeds or
  160. // ctx.Done is closed.
  161. func (c *WSClient) Send(ctx context.Context, request types.RPCRequest) error {
  162. select {
  163. case c.send <- request:
  164. c.Logger.Info("sent a request", "req", request)
  165. return nil
  166. case <-ctx.Done():
  167. return ctx.Err()
  168. }
  169. }
  170. // Call the given method. See Send description.
  171. func (c *WSClient) Call(ctx context.Context, method string, params map[string]interface{}) error {
  172. request, err := types.MapToRequest("ws-client", method, params)
  173. if err != nil {
  174. return err
  175. }
  176. return c.Send(ctx, request)
  177. }
  178. // CallWithArrayParams the given method with params in a form of array. See
  179. // Send description.
  180. func (c *WSClient) CallWithArrayParams(ctx context.Context, method string, params []interface{}) error {
  181. request, err := types.ArrayToRequest("ws-client", method, params)
  182. if err != nil {
  183. return err
  184. }
  185. return c.Send(ctx, request)
  186. }
  187. ///////////////////////////////////////////////////////////////////////////////
  188. // Private methods
  189. func (c *WSClient) dial() error {
  190. dialer := &websocket.Dialer{
  191. NetDial: c.Dialer,
  192. Proxy: http.ProxyFromEnvironment,
  193. }
  194. rHeader := http.Header{}
  195. conn, _, err := dialer.Dial("ws://"+c.Address+c.Endpoint, rHeader)
  196. if err != nil {
  197. return err
  198. }
  199. c.conn = conn
  200. return nil
  201. }
  202. // reconnect tries to redial up to maxReconnectAttempts with exponential
  203. // backoff.
  204. func (c *WSClient) reconnect() error {
  205. attempt := 0
  206. c.mtx.Lock()
  207. c.reconnecting = true
  208. c.mtx.Unlock()
  209. defer func() {
  210. c.mtx.Lock()
  211. c.reconnecting = false
  212. c.mtx.Unlock()
  213. }()
  214. // 1s == (1e9 ns) == (1 Billion ns)
  215. billionNs := float64(time.Second.Nanoseconds())
  216. for {
  217. jitterSeconds := time.Duration(rand.Float64() * billionNs)
  218. backoffDuration := jitterSeconds + ((1 << uint(attempt)) * time.Second)
  219. c.Logger.Info("reconnecting", "attempt", attempt+1, "backoff_duration", backoffDuration)
  220. time.Sleep(backoffDuration)
  221. err := c.dial()
  222. if err != nil {
  223. c.Logger.Error("failed to redial", "err", err)
  224. } else {
  225. c.Logger.Info("reconnected")
  226. if c.onReconnect != nil {
  227. go c.onReconnect()
  228. }
  229. return nil
  230. }
  231. attempt++
  232. if attempt > c.maxReconnectAttempts {
  233. return errors.Wrap(err, "reached maximum reconnect attempts")
  234. }
  235. }
  236. }
  237. func (c *WSClient) startReadWriteRoutines() {
  238. c.wg.Add(2)
  239. c.readRoutineQuit = make(chan struct{})
  240. go c.readRoutine()
  241. go c.writeRoutine()
  242. }
  243. func (c *WSClient) processBacklog() error {
  244. select {
  245. case request := <-c.backlog:
  246. if c.writeWait > 0 {
  247. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  248. c.Logger.Error("failed to set write deadline", "err", err)
  249. }
  250. }
  251. if err := c.conn.WriteJSON(request); err != nil {
  252. c.Logger.Error("failed to resend request", "err", err)
  253. c.reconnectAfter <- err
  254. // requeue request
  255. c.backlog <- request
  256. return err
  257. }
  258. c.Logger.Info("resend a request", "req", request)
  259. default:
  260. }
  261. return nil
  262. }
  263. func (c *WSClient) reconnectRoutine() {
  264. for {
  265. select {
  266. case originalError := <-c.reconnectAfter:
  267. // wait until writeRoutine and readRoutine finish
  268. c.wg.Wait()
  269. if err := c.reconnect(); err != nil {
  270. c.Logger.Error("failed to reconnect", "err", err, "original_err", originalError)
  271. c.Stop()
  272. return
  273. } else {
  274. // drain reconnectAfter
  275. LOOP:
  276. for {
  277. select {
  278. case <-c.reconnectAfter:
  279. default:
  280. break LOOP
  281. }
  282. }
  283. err = c.processBacklog()
  284. if err == nil {
  285. c.startReadWriteRoutines()
  286. }
  287. }
  288. case <-c.Quit():
  289. return
  290. }
  291. }
  292. }
  293. // The client ensures that there is at most one writer to a connection by
  294. // executing all writes from this goroutine.
  295. func (c *WSClient) writeRoutine() {
  296. var ticker *time.Ticker
  297. if c.pingPeriod > 0 {
  298. // ticker with a predefined period
  299. ticker = time.NewTicker(c.pingPeriod)
  300. } else {
  301. // ticker that never fires
  302. ticker = &time.Ticker{C: make(<-chan time.Time)}
  303. }
  304. defer func() {
  305. ticker.Stop()
  306. if err := c.conn.Close(); err != nil {
  307. // ignore error; it will trigger in tests
  308. // likely because it's closing an already closed connection
  309. }
  310. c.wg.Done()
  311. }()
  312. for {
  313. select {
  314. case request := <-c.send:
  315. if c.writeWait > 0 {
  316. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  317. c.Logger.Error("failed to set write deadline", "err", err)
  318. }
  319. }
  320. if err := c.conn.WriteJSON(request); err != nil {
  321. c.Logger.Error("failed to send request", "err", err)
  322. c.reconnectAfter <- err
  323. // add request to the backlog, so we don't lose it
  324. c.backlog <- request
  325. return
  326. }
  327. case <-ticker.C:
  328. if c.writeWait > 0 {
  329. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  330. c.Logger.Error("failed to set write deadline", "err", err)
  331. }
  332. }
  333. if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  334. c.Logger.Error("failed to write ping", "err", err)
  335. c.reconnectAfter <- err
  336. return
  337. }
  338. c.mtx.Lock()
  339. c.sentLastPingAt = time.Now()
  340. c.mtx.Unlock()
  341. c.Logger.Debug("sent ping")
  342. case <-c.readRoutineQuit:
  343. return
  344. case <-c.Quit():
  345. if err := c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil {
  346. c.Logger.Error("failed to write message", "err", err)
  347. }
  348. return
  349. }
  350. }
  351. }
  352. // The client ensures that there is at most one reader to a connection by
  353. // executing all reads from this goroutine.
  354. func (c *WSClient) readRoutine() {
  355. defer func() {
  356. if err := c.conn.Close(); err != nil {
  357. // ignore error; it will trigger in tests
  358. // likely because it's closing an already closed connection
  359. }
  360. c.wg.Done()
  361. }()
  362. c.conn.SetPongHandler(func(string) error {
  363. // gather latency stats
  364. c.mtx.RLock()
  365. t := c.sentLastPingAt
  366. c.mtx.RUnlock()
  367. c.PingPongLatencyTimer.UpdateSince(t)
  368. c.Logger.Debug("got pong")
  369. return nil
  370. })
  371. for {
  372. // reset deadline for every message type (control or data)
  373. if c.readWait > 0 {
  374. if err := c.conn.SetReadDeadline(time.Now().Add(c.readWait)); err != nil {
  375. c.Logger.Error("failed to set read deadline", "err", err)
  376. }
  377. }
  378. _, data, err := c.conn.ReadMessage()
  379. if err != nil {
  380. if !websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
  381. return
  382. }
  383. c.Logger.Error("failed to read response", "err", err)
  384. close(c.readRoutineQuit)
  385. c.reconnectAfter <- err
  386. return
  387. }
  388. var response types.RPCResponse
  389. err = json.Unmarshal(data, &response)
  390. if err != nil {
  391. c.Logger.Error("failed to parse response", "err", err, "data", string(data))
  392. continue
  393. }
  394. c.Logger.Info("got response", "resp", response.Result)
  395. // Combine a non-blocking read on BaseService.Quit with a non-blocking write on ResponsesCh to avoid blocking
  396. // c.wg.Wait() in c.Stop(). Note we rely on Quit being closed so that it sends unlimited Quit signals to stop
  397. // both readRoutine and writeRoutine
  398. select {
  399. case <-c.Quit():
  400. case c.ResponsesCh <- response:
  401. }
  402. }
  403. }
  404. ///////////////////////////////////////////////////////////////////////////////
  405. // Predefined methods
  406. // Subscribe to a query. Note the server must have a "subscribe" route
  407. // defined.
  408. func (c *WSClient) Subscribe(ctx context.Context, query string) error {
  409. params := map[string]interface{}{"query": query}
  410. return c.Call(ctx, "subscribe", params)
  411. }
  412. // Unsubscribe from a query. Note the server must have a "unsubscribe" route
  413. // defined.
  414. func (c *WSClient) Unsubscribe(ctx context.Context, query string) error {
  415. params := map[string]interface{}{"query": query}
  416. return c.Call(ctx, "unsubscribe", params)
  417. }
  418. // UnsubscribeAll from all. Note the server must have a "unsubscribe_all" route
  419. // defined.
  420. func (c *WSClient) UnsubscribeAll(ctx context.Context) error {
  421. params := map[string]interface{}{}
  422. return c.Call(ctx, "unsubscribe_all", params)
  423. }