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.

271 lines
5.7 KiB

cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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 client
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "net/http/httptest"
  7. "runtime"
  8. "sync"
  9. "testing"
  10. "time"
  11. "github.com/fortytw2/leaktest"
  12. "github.com/gorilla/websocket"
  13. metrics "github.com/rcrowley/go-metrics"
  14. "github.com/stretchr/testify/require"
  15. "github.com/tendermint/tendermint/libs/log"
  16. rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
  17. )
  18. func init() {
  19. // Disable go-metrics metrics in tests, since they start unsupervised
  20. // goroutines that trip the leak tester. Calling Stop on the metric is not
  21. // sufficient, as that does not wait for the goroutine.
  22. metrics.UseNilMetrics = true
  23. }
  24. const wsCallTimeout = 5 * time.Second
  25. type myTestHandler struct {
  26. closeConnAfterRead bool
  27. mtx sync.RWMutex
  28. t *testing.T
  29. }
  30. var upgrader = websocket.Upgrader{
  31. ReadBufferSize: 1024,
  32. WriteBufferSize: 1024,
  33. }
  34. func (h *myTestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  35. conn, err := upgrader.Upgrade(w, r, nil)
  36. require.NoError(h.t, err)
  37. defer conn.Close()
  38. for {
  39. messageType, in, err := conn.ReadMessage()
  40. if err != nil {
  41. return
  42. }
  43. var req rpctypes.RPCRequest
  44. err = json.Unmarshal(in, &req)
  45. require.NoError(h.t, err)
  46. func() {
  47. h.mtx.RLock()
  48. defer h.mtx.RUnlock()
  49. if h.closeConnAfterRead {
  50. require.NoError(h.t, conn.Close())
  51. }
  52. }()
  53. res := json.RawMessage(`{}`)
  54. emptyRespBytes, err := json.Marshal(req.MakeResponse(res))
  55. require.NoError(h.t, err)
  56. if err := conn.WriteMessage(messageType, emptyRespBytes); err != nil {
  57. return
  58. }
  59. }
  60. }
  61. func TestWSClientReconnectsAfterReadFailure(t *testing.T) {
  62. t.Cleanup(leaktest.Check(t))
  63. // start server
  64. h := &myTestHandler{t: t}
  65. s := httptest.NewServer(h)
  66. defer s.Close()
  67. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  68. defer cancel()
  69. c := startClient(ctx, t, "//"+s.Listener.Addr().String())
  70. go handleResponses(ctx, t, c)
  71. h.mtx.Lock()
  72. h.closeConnAfterRead = true
  73. h.mtx.Unlock()
  74. // results in WS read error, no send retry because write succeeded
  75. call(ctx, t, "a", c)
  76. // expect to reconnect almost immediately
  77. time.Sleep(10 * time.Millisecond)
  78. h.mtx.Lock()
  79. h.closeConnAfterRead = false
  80. h.mtx.Unlock()
  81. // should succeed
  82. call(ctx, t, "b", c)
  83. }
  84. func TestWSClientReconnectsAfterWriteFailure(t *testing.T) {
  85. t.Cleanup(leaktest.Check(t))
  86. // start server
  87. h := &myTestHandler{t: t}
  88. s := httptest.NewServer(h)
  89. defer s.Close()
  90. ctx, cancel := context.WithCancel(context.Background())
  91. defer cancel()
  92. c := startClient(ctx, t, "//"+s.Listener.Addr().String())
  93. go handleResponses(ctx, t, c)
  94. // hacky way to abort the connection before write
  95. if err := c.conn.Close(); err != nil {
  96. t.Error(err)
  97. }
  98. // results in WS write error, the client should resend on reconnect
  99. call(ctx, t, "a", c)
  100. // expect to reconnect almost immediately
  101. time.Sleep(10 * time.Millisecond)
  102. // should succeed
  103. call(ctx, t, "b", c)
  104. }
  105. func TestWSClientReconnectFailure(t *testing.T) {
  106. t.Cleanup(leaktest.Check(t))
  107. // start server
  108. h := &myTestHandler{t: t}
  109. s := httptest.NewServer(h)
  110. ctx, cancel := context.WithCancel(context.Background())
  111. defer cancel()
  112. c := startClient(ctx, t, "//"+s.Listener.Addr().String())
  113. go func() {
  114. for {
  115. select {
  116. case <-c.ResponsesCh:
  117. case <-ctx.Done():
  118. return
  119. }
  120. }
  121. }()
  122. // hacky way to abort the connection before write
  123. if err := c.conn.Close(); err != nil {
  124. t.Error(err)
  125. }
  126. s.Close()
  127. // results in WS write error
  128. // provide timeout to avoid blocking
  129. cctx, cancel := context.WithTimeout(ctx, wsCallTimeout)
  130. defer cancel()
  131. if err := c.Call(cctx, "a", make(map[string]interface{})); err != nil {
  132. t.Error(err)
  133. }
  134. // expect to reconnect almost immediately
  135. time.Sleep(10 * time.Millisecond)
  136. done := make(chan struct{})
  137. go func() {
  138. // client should block on this
  139. call(ctx, t, "b", c)
  140. close(done)
  141. }()
  142. // test that client blocks on the second send
  143. select {
  144. case <-done:
  145. t.Fatal("client should block on calling 'b' during reconnect")
  146. case <-time.After(5 * time.Second):
  147. t.Log("All good")
  148. }
  149. }
  150. func TestNotBlockingOnStop(t *testing.T) {
  151. t.Cleanup(leaktest.Check(t))
  152. timeout := 3 * time.Second
  153. s := httptest.NewServer(&myTestHandler{t: t})
  154. defer s.Close()
  155. ctx, cancel := context.WithCancel(context.Background())
  156. defer cancel()
  157. c := startClient(ctx, t, "//"+s.Listener.Addr().String())
  158. c.Call(ctx, "a", make(map[string]interface{})) // nolint:errcheck // ignore for tests
  159. // Let the readRoutine get around to blocking
  160. time.Sleep(time.Second)
  161. passCh := make(chan struct{})
  162. go func() {
  163. // Unless we have a non-blocking write to ResponsesCh from readRoutine
  164. // this blocks forever ont the waitgroup
  165. cancel()
  166. require.NoError(t, c.Stop())
  167. select {
  168. case <-ctx.Done():
  169. case passCh <- struct{}{}:
  170. }
  171. }()
  172. runtime.Gosched() // hacks: force context switch
  173. select {
  174. case <-passCh:
  175. // Pass
  176. case <-time.After(timeout):
  177. if c.IsRunning() {
  178. t.Fatalf("WSClient did failed to stop within %v seconds - is one of the read/write routines blocking?",
  179. timeout.Seconds())
  180. }
  181. }
  182. }
  183. func startClient(ctx context.Context, t *testing.T, addr string) *WSClient {
  184. t.Helper()
  185. t.Cleanup(leaktest.Check(t))
  186. c, err := NewWS(addr, "/websocket")
  187. require.NoError(t, err)
  188. err = c.Start(ctx)
  189. require.NoError(t, err)
  190. c.Logger = log.NewNopLogger()
  191. return c
  192. }
  193. func call(ctx context.Context, t *testing.T, method string, c *WSClient) {
  194. t.Helper()
  195. err := c.Call(ctx, method, make(map[string]interface{}))
  196. if ctx.Err() == nil {
  197. require.NoError(t, err)
  198. }
  199. }
  200. func handleResponses(ctx context.Context, t *testing.T, c *WSClient) {
  201. t.Helper()
  202. for {
  203. select {
  204. case resp := <-c.ResponsesCh:
  205. if resp.Error != nil {
  206. t.Errorf("unexpected error: %v", resp.Error)
  207. return
  208. }
  209. if resp.Result != nil {
  210. return
  211. }
  212. case <-ctx.Done():
  213. return
  214. }
  215. }
  216. }