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.

500 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
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. cmn "github.com/tendermint/tendermint/libs/common"
  15. types "github.com/tendermint/tendermint/rpc/lib/types"
  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. // Stop overrides cmn.Service#Stop. There is no other way to wait until Quit
  145. // channel is closed.
  146. func (c *WSClient) Stop() error {
  147. if err := c.BaseService.Stop(); err != nil {
  148. return err
  149. }
  150. // only close user-facing channels when we can't write to them
  151. c.wg.Wait()
  152. close(c.ResponsesCh)
  153. return nil
  154. }
  155. // IsReconnecting returns true if the client is reconnecting right now.
  156. func (c *WSClient) IsReconnecting() bool {
  157. c.mtx.RLock()
  158. defer c.mtx.RUnlock()
  159. return c.reconnecting
  160. }
  161. // IsActive returns true if the client is running and not reconnecting.
  162. func (c *WSClient) IsActive() bool {
  163. return c.IsRunning() && !c.IsReconnecting()
  164. }
  165. // Send the given RPC request to the server. Results will be available on
  166. // ResponsesCh, errors, if any, on ErrorsCh. Will block until send succeeds or
  167. // ctx.Done is closed.
  168. func (c *WSClient) Send(ctx context.Context, request types.RPCRequest) error {
  169. select {
  170. case c.send <- request:
  171. c.Logger.Info("sent a request", "req", request)
  172. return nil
  173. case <-ctx.Done():
  174. return ctx.Err()
  175. }
  176. }
  177. // Call the given method. See Send description.
  178. func (c *WSClient) Call(ctx context.Context, method string, params map[string]interface{}) error {
  179. request, err := types.MapToRequest(c.cdc, types.JSONRPCStringID("ws-client"), method, params)
  180. if err != nil {
  181. return err
  182. }
  183. return c.Send(ctx, request)
  184. }
  185. // CallWithArrayParams the given method with params in a form of array. See
  186. // Send description.
  187. func (c *WSClient) CallWithArrayParams(ctx context.Context, method string, params []interface{}) error {
  188. request, err := types.ArrayToRequest(c.cdc, types.JSONRPCStringID("ws-client"), method, params)
  189. if err != nil {
  190. return err
  191. }
  192. return c.Send(ctx, request)
  193. }
  194. func (c *WSClient) Codec() *amino.Codec {
  195. return c.cdc
  196. }
  197. func (c *WSClient) SetCodec(cdc *amino.Codec) {
  198. c.cdc = cdc
  199. }
  200. ///////////////////////////////////////////////////////////////////////////////
  201. // Private methods
  202. func (c *WSClient) dial() error {
  203. dialer := &websocket.Dialer{
  204. NetDial: c.Dialer,
  205. Proxy: http.ProxyFromEnvironment,
  206. }
  207. rHeader := http.Header{}
  208. conn, _, err := dialer.Dial(c.protocol+"://"+c.Address+c.Endpoint, rHeader)
  209. if err != nil {
  210. return err
  211. }
  212. c.conn = conn
  213. return nil
  214. }
  215. // reconnect tries to redial up to maxReconnectAttempts with exponential
  216. // backoff.
  217. func (c *WSClient) reconnect() error {
  218. attempt := 0
  219. c.mtx.Lock()
  220. c.reconnecting = true
  221. c.mtx.Unlock()
  222. defer func() {
  223. c.mtx.Lock()
  224. c.reconnecting = false
  225. c.mtx.Unlock()
  226. }()
  227. for {
  228. jitterSeconds := time.Duration(cmn.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns)
  229. backoffDuration := jitterSeconds + ((1 << uint(attempt)) * time.Second)
  230. c.Logger.Info("reconnecting", "attempt", attempt+1, "backoff_duration", backoffDuration)
  231. time.Sleep(backoffDuration)
  232. err := c.dial()
  233. if err != nil {
  234. c.Logger.Error("failed to redial", "err", err)
  235. } else {
  236. c.Logger.Info("reconnected")
  237. if c.onReconnect != nil {
  238. go c.onReconnect()
  239. }
  240. return nil
  241. }
  242. attempt++
  243. if attempt > c.maxReconnectAttempts {
  244. return errors.Wrap(err, "reached maximum reconnect attempts")
  245. }
  246. }
  247. }
  248. func (c *WSClient) startReadWriteRoutines() {
  249. c.wg.Add(2)
  250. c.readRoutineQuit = make(chan struct{})
  251. go c.readRoutine()
  252. go c.writeRoutine()
  253. }
  254. func (c *WSClient) processBacklog() error {
  255. select {
  256. case request := <-c.backlog:
  257. if c.writeWait > 0 {
  258. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  259. c.Logger.Error("failed to set write deadline", "err", err)
  260. }
  261. }
  262. if err := c.conn.WriteJSON(request); err != nil {
  263. c.Logger.Error("failed to resend request", "err", err)
  264. c.reconnectAfter <- err
  265. // requeue request
  266. c.backlog <- request
  267. return err
  268. }
  269. c.Logger.Info("resend a request", "req", request)
  270. default:
  271. }
  272. return nil
  273. }
  274. func (c *WSClient) reconnectRoutine() {
  275. for {
  276. select {
  277. case originalError := <-c.reconnectAfter:
  278. // wait until writeRoutine and readRoutine finish
  279. c.wg.Wait()
  280. if err := c.reconnect(); err != nil {
  281. c.Logger.Error("failed to reconnect", "err", err, "original_err", originalError)
  282. c.Stop()
  283. return
  284. }
  285. // drain reconnectAfter
  286. LOOP:
  287. for {
  288. select {
  289. case <-c.reconnectAfter:
  290. default:
  291. break LOOP
  292. }
  293. }
  294. err := c.processBacklog()
  295. if err == nil {
  296. c.startReadWriteRoutines()
  297. }
  298. case <-c.Quit():
  299. return
  300. }
  301. }
  302. }
  303. // The client ensures that there is at most one writer to a connection by
  304. // executing all writes from this goroutine.
  305. func (c *WSClient) writeRoutine() {
  306. var ticker *time.Ticker
  307. if c.pingPeriod > 0 {
  308. // ticker with a predefined period
  309. ticker = time.NewTicker(c.pingPeriod)
  310. } else {
  311. // ticker that never fires
  312. ticker = &time.Ticker{C: make(<-chan time.Time)}
  313. }
  314. defer func() {
  315. ticker.Stop()
  316. if err := c.conn.Close(); err != nil {
  317. // ignore error; it will trigger in tests
  318. // likely because it's closing an already closed connection
  319. }
  320. c.wg.Done()
  321. }()
  322. for {
  323. select {
  324. case request := <-c.send:
  325. if c.writeWait > 0 {
  326. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  327. c.Logger.Error("failed to set write deadline", "err", err)
  328. }
  329. }
  330. if err := c.conn.WriteJSON(request); err != nil {
  331. c.Logger.Error("failed to send request", "err", err)
  332. c.reconnectAfter <- err
  333. // add request to the backlog, so we don't lose it
  334. c.backlog <- request
  335. return
  336. }
  337. case <-ticker.C:
  338. if c.writeWait > 0 {
  339. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  340. c.Logger.Error("failed to set write deadline", "err", err)
  341. }
  342. }
  343. if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  344. c.Logger.Error("failed to write ping", "err", err)
  345. c.reconnectAfter <- err
  346. return
  347. }
  348. c.mtx.Lock()
  349. c.sentLastPingAt = time.Now()
  350. c.mtx.Unlock()
  351. c.Logger.Debug("sent ping")
  352. case <-c.readRoutineQuit:
  353. return
  354. case <-c.Quit():
  355. if err := c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil {
  356. c.Logger.Error("failed to write message", "err", err)
  357. }
  358. return
  359. }
  360. }
  361. }
  362. // The client ensures that there is at most one reader to a connection by
  363. // executing all reads from this goroutine.
  364. func (c *WSClient) readRoutine() {
  365. defer func() {
  366. if err := c.conn.Close(); err != nil {
  367. // ignore error; it will trigger in tests
  368. // likely because it's closing an already closed connection
  369. }
  370. c.wg.Done()
  371. }()
  372. c.conn.SetPongHandler(func(string) error {
  373. // gather latency stats
  374. c.mtx.RLock()
  375. t := c.sentLastPingAt
  376. c.mtx.RUnlock()
  377. c.PingPongLatencyTimer.UpdateSince(t)
  378. c.Logger.Debug("got pong")
  379. return nil
  380. })
  381. for {
  382. // reset deadline for every message type (control or data)
  383. if c.readWait > 0 {
  384. if err := c.conn.SetReadDeadline(time.Now().Add(c.readWait)); err != nil {
  385. c.Logger.Error("failed to set read deadline", "err", err)
  386. }
  387. }
  388. _, data, err := c.conn.ReadMessage()
  389. if err != nil {
  390. if !websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
  391. return
  392. }
  393. c.Logger.Error("failed to read response", "err", err)
  394. close(c.readRoutineQuit)
  395. c.reconnectAfter <- err
  396. return
  397. }
  398. var response types.RPCResponse
  399. err = json.Unmarshal(data, &response)
  400. if err != nil {
  401. c.Logger.Error("failed to parse response", "err", err, "data", string(data))
  402. continue
  403. }
  404. c.Logger.Info("got response", "resp", response.Result)
  405. // Combine a non-blocking read on BaseService.Quit with a non-blocking write on ResponsesCh to avoid blocking
  406. // c.wg.Wait() in c.Stop(). Note we rely on Quit being closed so that it sends unlimited Quit signals to stop
  407. // both readRoutine and writeRoutine
  408. select {
  409. case <-c.Quit():
  410. case c.ResponsesCh <- response:
  411. }
  412. }
  413. }
  414. ///////////////////////////////////////////////////////////////////////////////
  415. // Predefined methods
  416. // Subscribe to a query. Note the server must have a "subscribe" route
  417. // defined.
  418. func (c *WSClient) Subscribe(ctx context.Context, query string) error {
  419. params := map[string]interface{}{"query": query}
  420. return c.Call(ctx, "subscribe", params)
  421. }
  422. // Unsubscribe from a query. Note the server must have a "unsubscribe" route
  423. // defined.
  424. func (c *WSClient) Unsubscribe(ctx context.Context, query string) error {
  425. params := map[string]interface{}{"query": query}
  426. return c.Call(ctx, "unsubscribe", params)
  427. }
  428. // UnsubscribeAll from all. Note the server must have a "unsubscribe_all" route
  429. // defined.
  430. func (c *WSClient) UnsubscribeAll(ctx context.Context) error {
  431. params := map[string]interface{}{}
  432. return c.Call(ctx, "unsubscribe_all", params)
  433. }