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.

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