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.

494 lines
13 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
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
8 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
8 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
8 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
8 years ago
  1. package rpcclient
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "sync"
  9. "time"
  10. "github.com/gorilla/websocket"
  11. "github.com/pkg/errors"
  12. metrics "github.com/rcrowley/go-metrics"
  13. "github.com/tendermint/go-amino"
  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. cdc *amino.Codec
  29. Address string // IP:PORT or /path/to/socket
  30. Endpoint string // /websocket/url/endpoint
  31. Dialer func(string, string) (net.Conn, error)
  32. // Time between sending a ping and receiving a pong. See
  33. // https://godoc.org/github.com/rcrowley/go-metrics#Timer.
  34. PingPongLatencyTimer metrics.Timer
  35. // Single user facing channel to read RPCResponses from, closed only when the client is being stopped.
  36. ResponsesCh chan types.RPCResponse
  37. // Callback, which will be called each time after successful reconnect.
  38. onReconnect func()
  39. // internal channels
  40. send chan types.RPCRequest // user requests
  41. backlog chan types.RPCRequest // stores a single user request received during a conn failure
  42. reconnectAfter chan error // reconnect requests
  43. readRoutineQuit chan struct{} // a way for readRoutine to close writeRoutine
  44. wg sync.WaitGroup
  45. mtx sync.RWMutex
  46. sentLastPingAt time.Time
  47. reconnecting bool
  48. // Maximum reconnect attempts (0 or greater; default: 25).
  49. maxReconnectAttempts int
  50. // Time allowed to write a message to the server. 0 means block until operation succeeds.
  51. writeWait time.Duration
  52. // Time allowed to read the next message from the server. 0 means block until operation succeeds.
  53. readWait time.Duration
  54. // Send pings to server with this period. Must be less than readWait. If 0, no pings will be sent.
  55. pingPeriod time.Duration
  56. }
  57. // NewWSClient returns a new client. See the commentary on the func(*WSClient)
  58. // functions for a detailed description of how to configure ping period and
  59. // pong wait time. The endpoint argument must begin with a `/`.
  60. func NewWSClient(remoteAddr, endpoint string, options ...func(*WSClient)) *WSClient {
  61. addr, dialer := makeHTTPDialer(remoteAddr)
  62. c := &WSClient{
  63. cdc: amino.NewCodec(),
  64. Address: addr,
  65. Dialer: dialer,
  66. Endpoint: endpoint,
  67. PingPongLatencyTimer: metrics.NewTimer(),
  68. maxReconnectAttempts: defaultMaxReconnectAttempts,
  69. readWait: defaultReadWait,
  70. writeWait: defaultWriteWait,
  71. pingPeriod: defaultPingPeriod,
  72. }
  73. c.BaseService = *cmn.NewBaseService(nil, "WSClient", c)
  74. for _, option := range options {
  75. option(c)
  76. }
  77. return c
  78. }
  79. // MaxReconnectAttempts sets the maximum number of reconnect attempts before returning an error.
  80. // It should only be used in the constructor and is not Goroutine-safe.
  81. func MaxReconnectAttempts(max int) func(*WSClient) {
  82. return func(c *WSClient) {
  83. c.maxReconnectAttempts = max
  84. }
  85. }
  86. // ReadWait sets the amount of time to wait before a websocket read times out.
  87. // It should only be used in the constructor and is not Goroutine-safe.
  88. func ReadWait(readWait time.Duration) func(*WSClient) {
  89. return func(c *WSClient) {
  90. c.readWait = readWait
  91. }
  92. }
  93. // WriteWait sets the amount of time to wait before a websocket write times out.
  94. // It should only be used in the constructor and is not Goroutine-safe.
  95. func WriteWait(writeWait time.Duration) func(*WSClient) {
  96. return func(c *WSClient) {
  97. c.writeWait = writeWait
  98. }
  99. }
  100. // PingPeriod sets the duration for sending websocket pings.
  101. // It should only be used in the constructor - not Goroutine-safe.
  102. func PingPeriod(pingPeriod time.Duration) func(*WSClient) {
  103. return func(c *WSClient) {
  104. c.pingPeriod = pingPeriod
  105. }
  106. }
  107. // OnReconnect sets the callback, which will be called every time after
  108. // successful reconnect.
  109. func OnReconnect(cb func()) func(*WSClient) {
  110. return func(c *WSClient) {
  111. c.onReconnect = cb
  112. }
  113. }
  114. // String returns WS client full address.
  115. func (c *WSClient) String() string {
  116. return fmt.Sprintf("%s (%s)", c.Address, c.Endpoint)
  117. }
  118. // OnStart implements cmn.Service by dialing a server and creating read and
  119. // write routines.
  120. func (c *WSClient) OnStart() error {
  121. err := c.dial()
  122. if err != nil {
  123. return err
  124. }
  125. c.ResponsesCh = make(chan types.RPCResponse)
  126. c.send = make(chan types.RPCRequest)
  127. // 1 additional error may come from the read/write
  128. // goroutine depending on which failed first.
  129. c.reconnectAfter = make(chan error, 1)
  130. // capacity for 1 request. a user won't be able to send more because the send
  131. // channel is unbuffered.
  132. c.backlog = make(chan types.RPCRequest, 1)
  133. c.startReadWriteRoutines()
  134. go c.reconnectRoutine()
  135. return nil
  136. }
  137. // OnStop implements cmn.Service.
  138. func (c *WSClient) OnStop() {}
  139. // Stop overrides cmn.Service#Stop. There is no other way to wait until Quit
  140. // channel is closed.
  141. func (c *WSClient) Stop() error {
  142. if err := c.BaseService.Stop(); err != nil {
  143. return err
  144. }
  145. // only close user-facing channels when we can't write to them
  146. c.wg.Wait()
  147. close(c.ResponsesCh)
  148. return nil
  149. }
  150. // IsReconnecting returns true if the client is reconnecting right now.
  151. func (c *WSClient) IsReconnecting() bool {
  152. c.mtx.RLock()
  153. defer c.mtx.RUnlock()
  154. return c.reconnecting
  155. }
  156. // IsActive returns true if the client is running and not reconnecting.
  157. func (c *WSClient) IsActive() bool {
  158. return c.IsRunning() && !c.IsReconnecting()
  159. }
  160. // Send the given RPC request to the server. Results will be available on
  161. // ResponsesCh, errors, if any, on ErrorsCh. Will block until send succeeds or
  162. // ctx.Done is closed.
  163. func (c *WSClient) Send(ctx context.Context, request types.RPCRequest) error {
  164. select {
  165. case c.send <- request:
  166. c.Logger.Info("sent a request", "req", request)
  167. return nil
  168. case <-ctx.Done():
  169. return ctx.Err()
  170. }
  171. }
  172. // Call the given method. See Send description.
  173. func (c *WSClient) Call(ctx context.Context, method string, params map[string]interface{}) error {
  174. request, err := types.MapToRequest(c.cdc, "ws-client", method, params)
  175. if err != nil {
  176. return err
  177. }
  178. return c.Send(ctx, request)
  179. }
  180. // CallWithArrayParams the given method with params in a form of array. See
  181. // Send description.
  182. func (c *WSClient) CallWithArrayParams(ctx context.Context, method string, params []interface{}) error {
  183. request, err := types.ArrayToRequest(c.cdc, "ws-client", method, params)
  184. if err != nil {
  185. return err
  186. }
  187. return c.Send(ctx, request)
  188. }
  189. func (c *WSClient) Codec() *amino.Codec {
  190. return c.cdc
  191. }
  192. func (c *WSClient) SetCodec(cdc *amino.Codec) {
  193. c.cdc = cdc
  194. }
  195. ///////////////////////////////////////////////////////////////////////////////
  196. // Private methods
  197. func (c *WSClient) dial() error {
  198. dialer := &websocket.Dialer{
  199. NetDial: c.Dialer,
  200. Proxy: http.ProxyFromEnvironment,
  201. }
  202. rHeader := http.Header{}
  203. conn, _, err := dialer.Dial("ws://"+c.Address+c.Endpoint, rHeader)
  204. if err != nil {
  205. return err
  206. }
  207. c.conn = conn
  208. return nil
  209. }
  210. // reconnect tries to redial up to maxReconnectAttempts with exponential
  211. // backoff.
  212. func (c *WSClient) reconnect() error {
  213. attempt := 0
  214. c.mtx.Lock()
  215. c.reconnecting = true
  216. c.mtx.Unlock()
  217. defer func() {
  218. c.mtx.Lock()
  219. c.reconnecting = false
  220. c.mtx.Unlock()
  221. }()
  222. for {
  223. jitterSeconds := time.Duration(cmn.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns)
  224. backoffDuration := jitterSeconds + ((1 << uint(attempt)) * time.Second)
  225. c.Logger.Info("reconnecting", "attempt", attempt+1, "backoff_duration", backoffDuration)
  226. time.Sleep(backoffDuration)
  227. err := c.dial()
  228. if err != nil {
  229. c.Logger.Error("failed to redial", "err", err)
  230. } else {
  231. c.Logger.Info("reconnected")
  232. if c.onReconnect != nil {
  233. go c.onReconnect()
  234. }
  235. return nil
  236. }
  237. attempt++
  238. if attempt > c.maxReconnectAttempts {
  239. return errors.Wrap(err, "reached maximum reconnect attempts")
  240. }
  241. }
  242. }
  243. func (c *WSClient) startReadWriteRoutines() {
  244. c.wg.Add(2)
  245. c.readRoutineQuit = make(chan struct{})
  246. go c.readRoutine()
  247. go c.writeRoutine()
  248. }
  249. func (c *WSClient) processBacklog() error {
  250. select {
  251. case request := <-c.backlog:
  252. if c.writeWait > 0 {
  253. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  254. c.Logger.Error("failed to set write deadline", "err", err)
  255. }
  256. }
  257. if err := c.conn.WriteJSON(request); err != nil {
  258. c.Logger.Error("failed to resend request", "err", err)
  259. c.reconnectAfter <- err
  260. // requeue request
  261. c.backlog <- request
  262. return err
  263. }
  264. c.Logger.Info("resend a request", "req", request)
  265. default:
  266. }
  267. return nil
  268. }
  269. func (c *WSClient) reconnectRoutine() {
  270. for {
  271. select {
  272. case originalError := <-c.reconnectAfter:
  273. // wait until writeRoutine and readRoutine finish
  274. c.wg.Wait()
  275. if err := c.reconnect(); err != nil {
  276. c.Logger.Error("failed to reconnect", "err", err, "original_err", originalError)
  277. c.Stop()
  278. return
  279. }
  280. // drain reconnectAfter
  281. LOOP:
  282. for {
  283. select {
  284. case <-c.reconnectAfter:
  285. default:
  286. break LOOP
  287. }
  288. }
  289. err := c.processBacklog()
  290. if err == nil {
  291. c.startReadWriteRoutines()
  292. }
  293. case <-c.Quit():
  294. return
  295. }
  296. }
  297. }
  298. // The client ensures that there is at most one writer to a connection by
  299. // executing all writes from this goroutine.
  300. func (c *WSClient) writeRoutine() {
  301. var ticker *time.Ticker
  302. if c.pingPeriod > 0 {
  303. // ticker with a predefined period
  304. ticker = time.NewTicker(c.pingPeriod)
  305. } else {
  306. // ticker that never fires
  307. ticker = &time.Ticker{C: make(<-chan time.Time)}
  308. }
  309. defer func() {
  310. ticker.Stop()
  311. if err := c.conn.Close(); err != nil {
  312. // ignore error; it will trigger in tests
  313. // likely because it's closing an already closed connection
  314. }
  315. c.wg.Done()
  316. }()
  317. for {
  318. select {
  319. case request := <-c.send:
  320. if c.writeWait > 0 {
  321. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  322. c.Logger.Error("failed to set write deadline", "err", err)
  323. }
  324. }
  325. if err := c.conn.WriteJSON(request); err != nil {
  326. c.Logger.Error("failed to send request", "err", err)
  327. c.reconnectAfter <- err
  328. // add request to the backlog, so we don't lose it
  329. c.backlog <- request
  330. return
  331. }
  332. case <-ticker.C:
  333. if c.writeWait > 0 {
  334. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  335. c.Logger.Error("failed to set write deadline", "err", err)
  336. }
  337. }
  338. if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  339. c.Logger.Error("failed to write ping", "err", err)
  340. c.reconnectAfter <- err
  341. return
  342. }
  343. c.mtx.Lock()
  344. c.sentLastPingAt = time.Now()
  345. c.mtx.Unlock()
  346. c.Logger.Debug("sent ping")
  347. case <-c.readRoutineQuit:
  348. return
  349. case <-c.Quit():
  350. if err := c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil {
  351. c.Logger.Error("failed to write message", "err", err)
  352. }
  353. return
  354. }
  355. }
  356. }
  357. // The client ensures that there is at most one reader to a connection by
  358. // executing all reads from this goroutine.
  359. func (c *WSClient) readRoutine() {
  360. defer func() {
  361. if err := c.conn.Close(); err != nil {
  362. // ignore error; it will trigger in tests
  363. // likely because it's closing an already closed connection
  364. }
  365. c.wg.Done()
  366. }()
  367. c.conn.SetPongHandler(func(string) error {
  368. // gather latency stats
  369. c.mtx.RLock()
  370. t := c.sentLastPingAt
  371. c.mtx.RUnlock()
  372. c.PingPongLatencyTimer.UpdateSince(t)
  373. c.Logger.Debug("got pong")
  374. return nil
  375. })
  376. for {
  377. // reset deadline for every message type (control or data)
  378. if c.readWait > 0 {
  379. if err := c.conn.SetReadDeadline(time.Now().Add(c.readWait)); err != nil {
  380. c.Logger.Error("failed to set read deadline", "err", err)
  381. }
  382. }
  383. _, data, err := c.conn.ReadMessage()
  384. if err != nil {
  385. if !websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
  386. return
  387. }
  388. c.Logger.Error("failed to read response", "err", err)
  389. close(c.readRoutineQuit)
  390. c.reconnectAfter <- err
  391. return
  392. }
  393. var response types.RPCResponse
  394. err = json.Unmarshal(data, &response)
  395. if err != nil {
  396. c.Logger.Error("failed to parse response", "err", err, "data", string(data))
  397. continue
  398. }
  399. c.Logger.Info("got response", "resp", response.Result)
  400. // Combine a non-blocking read on BaseService.Quit with a non-blocking write on ResponsesCh to avoid blocking
  401. // c.wg.Wait() in c.Stop(). Note we rely on Quit being closed so that it sends unlimited Quit signals to stop
  402. // both readRoutine and writeRoutine
  403. select {
  404. case <-c.Quit():
  405. case c.ResponsesCh <- response:
  406. }
  407. }
  408. }
  409. ///////////////////////////////////////////////////////////////////////////////
  410. // Predefined methods
  411. // Subscribe to a query. Note the server must have a "subscribe" route
  412. // defined.
  413. func (c *WSClient) Subscribe(ctx context.Context, query string) error {
  414. params := map[string]interface{}{"query": query}
  415. return c.Call(ctx, "subscribe", params)
  416. }
  417. // Unsubscribe from a query. Note the server must have a "unsubscribe" route
  418. // defined.
  419. func (c *WSClient) Unsubscribe(ctx context.Context, query string) error {
  420. params := map[string]interface{}{"query": query}
  421. return c.Call(ctx, "unsubscribe", params)
  422. }
  423. // UnsubscribeAll from all. Note the server must have a "unsubscribe_all" route
  424. // defined.
  425. func (c *WSClient) UnsubscribeAll(ctx context.Context) error {
  426. params := map[string]interface{}{}
  427. return c.Call(ctx, "unsubscribe_all", params)
  428. }