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.

214 lines
4.3 KiB

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