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.

232 lines
4.7 KiB

rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
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, in, err := conn.ReadMessage()
  32. if err != nil {
  33. return
  34. }
  35. var req types.RPCRequest
  36. err = json.Unmarshal(in, &req)
  37. if err != nil {
  38. panic(err)
  39. }
  40. h.mtx.RLock()
  41. if h.closeConnAfterRead {
  42. if err := conn.Close(); err != nil {
  43. panic(err)
  44. }
  45. }
  46. h.mtx.RUnlock()
  47. res := json.RawMessage(`{}`)
  48. emptyRespBytes, _ := json.Marshal(types.RPCResponse{Result: res, ID: req.ID})
  49. if err := conn.WriteMessage(messageType, emptyRespBytes); err != nil {
  50. return
  51. }
  52. }
  53. }
  54. func TestWSClientReconnectsAfterReadFailure(t *testing.T) {
  55. var wg sync.WaitGroup
  56. // start server
  57. h := &myHandler{}
  58. s := httptest.NewServer(h)
  59. defer s.Close()
  60. c := startClient(t, "//"+s.Listener.Addr().String())
  61. defer c.Stop()
  62. wg.Add(1)
  63. go callWgDoneOnResult(t, c, &wg)
  64. h.mtx.Lock()
  65. h.closeConnAfterRead = true
  66. h.mtx.Unlock()
  67. // results in WS read error, no send retry because write succeeded
  68. call(t, "a", c)
  69. // expect to reconnect almost immediately
  70. time.Sleep(10 * time.Millisecond)
  71. h.mtx.Lock()
  72. h.closeConnAfterRead = false
  73. h.mtx.Unlock()
  74. // should succeed
  75. call(t, "b", c)
  76. wg.Wait()
  77. }
  78. func TestWSClientReconnectsAfterWriteFailure(t *testing.T) {
  79. var wg sync.WaitGroup
  80. // start server
  81. h := &myHandler{}
  82. s := httptest.NewServer(h)
  83. c := startClient(t, "//"+s.Listener.Addr().String())
  84. defer c.Stop()
  85. wg.Add(2)
  86. go callWgDoneOnResult(t, c, &wg)
  87. // hacky way to abort the connection before write
  88. if err := c.conn.Close(); err != nil {
  89. t.Error(err)
  90. }
  91. // results in WS write error, the client should resend on reconnect
  92. call(t, "a", c)
  93. // expect to reconnect almost immediately
  94. time.Sleep(10 * time.Millisecond)
  95. // should succeed
  96. call(t, "b", c)
  97. wg.Wait()
  98. }
  99. func TestWSClientReconnectFailure(t *testing.T) {
  100. // start server
  101. h := &myHandler{}
  102. s := httptest.NewServer(h)
  103. c := startClient(t, "//"+s.Listener.Addr().String())
  104. defer c.Stop()
  105. go func() {
  106. for {
  107. select {
  108. case <-c.ResponsesCh:
  109. case <-c.Quit():
  110. return
  111. }
  112. }
  113. }()
  114. // hacky way to abort the connection before write
  115. if err := c.conn.Close(); err != nil {
  116. t.Error(err)
  117. }
  118. s.Close()
  119. // results in WS write error
  120. // provide timeout to avoid blocking
  121. ctx, cancel := context.WithTimeout(context.Background(), wsCallTimeout)
  122. defer cancel()
  123. if err := c.Call(ctx, "a", make(map[string]interface{})); err != nil {
  124. t.Error(err)
  125. }
  126. // expect to reconnect almost immediately
  127. time.Sleep(10 * time.Millisecond)
  128. done := make(chan struct{})
  129. go func() {
  130. // client should block on this
  131. call(t, "b", c)
  132. close(done)
  133. }()
  134. // test that client blocks on the second send
  135. select {
  136. case <-done:
  137. t.Fatal("client should block on calling 'b' during reconnect")
  138. case <-time.After(5 * time.Second):
  139. t.Log("All good")
  140. }
  141. }
  142. func TestNotBlockingOnStop(t *testing.T) {
  143. timeout := 2 * time.Second
  144. s := httptest.NewServer(&myHandler{})
  145. c := startClient(t, "//"+s.Listener.Addr().String())
  146. c.Call(context.Background(), "a", make(map[string]interface{}))
  147. // Let the readRoutine get around to blocking
  148. time.Sleep(time.Second)
  149. passCh := make(chan struct{})
  150. go func() {
  151. // Unless we have a non-blocking write to ResponsesCh from readRoutine
  152. // this blocks forever ont the waitgroup
  153. c.Stop()
  154. passCh <- struct{}{}
  155. }()
  156. select {
  157. case <-passCh:
  158. // Pass
  159. case <-time.After(timeout):
  160. t.Fatalf("WSClient did failed to stop within %v seconds - is one of the read/write routines blocking?",
  161. timeout.Seconds())
  162. }
  163. }
  164. func startClient(t *testing.T, addr string) *WSClient {
  165. c, err := NewWSClient(addr, "/websocket")
  166. require.Nil(t, err)
  167. err = c.Start()
  168. require.Nil(t, err)
  169. c.SetLogger(log.TestingLogger())
  170. return c
  171. }
  172. func call(t *testing.T, method string, c *WSClient) {
  173. err := c.Call(context.Background(), method, make(map[string]interface{}))
  174. require.NoError(t, err)
  175. }
  176. func callWgDoneOnResult(t *testing.T, c *WSClient, wg *sync.WaitGroup) {
  177. for {
  178. select {
  179. case resp := <-c.ResponsesCh:
  180. if resp.Error != nil {
  181. t.Errorf("unexpected error: %v", resp.Error)
  182. return
  183. }
  184. if resp.Result != nil {
  185. wg.Done()
  186. }
  187. case <-c.Quit():
  188. return
  189. }
  190. }
  191. }