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.

224 lines
4.6 KiB

7 years ago
  1. package rpcclient
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "net/http/httptest"
  7. "sync"
  8. "testing"
  9. "time"
  10. "github.com/gorilla/websocket"
  11. "github.com/stretchr/testify/require"
  12. "github.com/tendermint/tendermint/libs/log"
  13. types "github.com/tendermint/tendermint/rpc/lib/types"
  14. )
  15. var wsCallTimeout = 5 * time.Second
  16. type myHandler struct {
  17. closeConnAfterRead bool
  18. mtx sync.RWMutex
  19. }
  20. var upgrader = websocket.Upgrader{
  21. ReadBufferSize: 1024,
  22. WriteBufferSize: 1024,
  23. }
  24. func (h *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  25. conn, err := upgrader.Upgrade(w, r, nil)
  26. if err != nil {
  27. panic(err)
  28. }
  29. defer conn.Close() // nolint: errcheck
  30. for {
  31. messageType, _, err := conn.ReadMessage()
  32. if err != nil {
  33. return
  34. }
  35. h.mtx.RLock()
  36. if h.closeConnAfterRead {
  37. if err := conn.Close(); err != nil {
  38. panic(err)
  39. }
  40. }
  41. h.mtx.RUnlock()
  42. res := json.RawMessage(`{}`)
  43. emptyRespBytes, _ := json.Marshal(types.RPCResponse{Result: res})
  44. if err := conn.WriteMessage(messageType, emptyRespBytes); err != nil {
  45. return
  46. }
  47. }
  48. }
  49. func TestWSClientReconnectsAfterReadFailure(t *testing.T) {
  50. var wg sync.WaitGroup
  51. // start server
  52. h := &myHandler{}
  53. s := httptest.NewServer(h)
  54. defer s.Close()
  55. c := startClient(t, s.Listener.Addr().String())
  56. defer c.Stop()
  57. wg.Add(1)
  58. go callWgDoneOnResult(t, c, &wg)
  59. h.mtx.Lock()
  60. h.closeConnAfterRead = true
  61. h.mtx.Unlock()
  62. // results in WS read error, no send retry because write succeeded
  63. call(t, "a", c)
  64. // expect to reconnect almost immediately
  65. time.Sleep(10 * time.Millisecond)
  66. h.mtx.Lock()
  67. h.closeConnAfterRead = false
  68. h.mtx.Unlock()
  69. // should succeed
  70. call(t, "b", c)
  71. wg.Wait()
  72. }
  73. func TestWSClientReconnectsAfterWriteFailure(t *testing.T) {
  74. var wg sync.WaitGroup
  75. // start server
  76. h := &myHandler{}
  77. s := httptest.NewServer(h)
  78. c := startClient(t, s.Listener.Addr().String())
  79. defer c.Stop()
  80. wg.Add(2)
  81. go callWgDoneOnResult(t, c, &wg)
  82. // hacky way to abort the connection before write
  83. if err := c.conn.Close(); err != nil {
  84. t.Error(err)
  85. }
  86. // results in WS write error, the client should resend on reconnect
  87. call(t, "a", c)
  88. // expect to reconnect almost immediately
  89. time.Sleep(10 * time.Millisecond)
  90. // should succeed
  91. call(t, "b", c)
  92. wg.Wait()
  93. }
  94. func TestWSClientReconnectFailure(t *testing.T) {
  95. // start server
  96. h := &myHandler{}
  97. s := httptest.NewServer(h)
  98. c := startClient(t, s.Listener.Addr().String())
  99. defer c.Stop()
  100. go func() {
  101. for {
  102. select {
  103. case <-c.ResponsesCh:
  104. case <-c.Quit():
  105. return
  106. }
  107. }
  108. }()
  109. // hacky way to abort the connection before write
  110. if err := c.conn.Close(); err != nil {
  111. t.Error(err)
  112. }
  113. s.Close()
  114. // results in WS write error
  115. // provide timeout to avoid blocking
  116. ctx, cancel := context.WithTimeout(context.Background(), wsCallTimeout)
  117. defer cancel()
  118. if err := c.Call(ctx, "a", make(map[string]interface{})); err != nil {
  119. t.Error(err)
  120. }
  121. // expect to reconnect almost immediately
  122. time.Sleep(10 * time.Millisecond)
  123. done := make(chan struct{})
  124. go func() {
  125. // client should block on this
  126. call(t, "b", c)
  127. close(done)
  128. }()
  129. // test that client blocks on the second send
  130. select {
  131. case <-done:
  132. t.Fatal("client should block on calling 'b' during reconnect")
  133. case <-time.After(5 * time.Second):
  134. t.Log("All good")
  135. }
  136. }
  137. func TestNotBlockingOnStop(t *testing.T) {
  138. timeout := 2 * time.Second
  139. s := httptest.NewServer(&myHandler{})
  140. c := startClient(t, s.Listener.Addr().String())
  141. c.Call(context.Background(), "a", make(map[string]interface{}))
  142. // Let the readRoutine get around to blocking
  143. time.Sleep(time.Second)
  144. passCh := make(chan struct{})
  145. go func() {
  146. // Unless we have a non-blocking write to ResponsesCh from readRoutine
  147. // this blocks forever ont the waitgroup
  148. c.Stop()
  149. passCh <- struct{}{}
  150. }()
  151. select {
  152. case <-passCh:
  153. // Pass
  154. case <-time.After(timeout):
  155. t.Fatalf("WSClient did failed to stop within %v seconds - is one of the read/write routines blocking?",
  156. timeout.Seconds())
  157. }
  158. }
  159. func startClient(t *testing.T, addr string) *WSClient {
  160. c := NewWSClient(addr, "/websocket")
  161. err := c.Start()
  162. require.Nil(t, err)
  163. c.SetLogger(log.TestingLogger())
  164. return c
  165. }
  166. func call(t *testing.T, method string, c *WSClient) {
  167. err := c.Call(context.Background(), method, make(map[string]interface{}))
  168. require.NoError(t, err)
  169. }
  170. func callWgDoneOnResult(t *testing.T, c *WSClient, wg *sync.WaitGroup) {
  171. for {
  172. select {
  173. case resp := <-c.ResponsesCh:
  174. if resp.Error != nil {
  175. t.Errorf("unexpected error: %v", resp.Error)
  176. return
  177. }
  178. if resp.Result != nil {
  179. wg.Done()
  180. }
  181. case <-c.Quit():
  182. return
  183. }
  184. }
  185. }