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.

263 lines
5.5 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
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
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. "github.com/stretchr/testify/require"
  14. "github.com/tendermint/tendermint/libs/log"
  15. rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
  16. )
  17. var wsCallTimeout = 5 * time.Second
  18. type myTestHandler struct {
  19. closeConnAfterRead bool
  20. mtx sync.RWMutex
  21. t *testing.T
  22. }
  23. var upgrader = websocket.Upgrader{
  24. ReadBufferSize: 1024,
  25. WriteBufferSize: 1024,
  26. }
  27. func (h *myTestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. conn, err := upgrader.Upgrade(w, r, nil)
  29. require.NoError(h.t, err)
  30. defer conn.Close()
  31. for {
  32. messageType, in, err := conn.ReadMessage()
  33. if err != nil {
  34. return
  35. }
  36. var req rpctypes.RPCRequest
  37. err = json.Unmarshal(in, &req)
  38. require.NoError(h.t, err)
  39. func() {
  40. h.mtx.RLock()
  41. defer h.mtx.RUnlock()
  42. if h.closeConnAfterRead {
  43. require.NoError(h.t, conn.Close())
  44. }
  45. }()
  46. res := json.RawMessage(`{}`)
  47. emptyRespBytes, _ := json.Marshal(rpctypes.RPCResponse{Result: res, ID: req.ID})
  48. if err := conn.WriteMessage(messageType, emptyRespBytes); err != nil {
  49. return
  50. }
  51. }
  52. }
  53. func TestWSClientReconnectsAfterReadFailure(t *testing.T) {
  54. t.Cleanup(leaktest.Check(t))
  55. // start server
  56. h := &myTestHandler{t: t}
  57. s := httptest.NewServer(h)
  58. defer s.Close()
  59. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  60. defer cancel()
  61. c := startClient(ctx, t, "//"+s.Listener.Addr().String())
  62. go handleResponses(ctx, t, c)
  63. h.mtx.Lock()
  64. h.closeConnAfterRead = true
  65. h.mtx.Unlock()
  66. // results in WS read error, no send retry because write succeeded
  67. call(ctx, t, "a", c)
  68. // expect to reconnect almost immediately
  69. time.Sleep(10 * time.Millisecond)
  70. h.mtx.Lock()
  71. h.closeConnAfterRead = false
  72. h.mtx.Unlock()
  73. // should succeed
  74. call(ctx, t, "b", c)
  75. }
  76. func TestWSClientReconnectsAfterWriteFailure(t *testing.T) {
  77. t.Cleanup(leaktest.Check(t))
  78. // start server
  79. h := &myTestHandler{t: t}
  80. s := httptest.NewServer(h)
  81. defer s.Close()
  82. ctx, cancel := context.WithCancel(context.Background())
  83. defer cancel()
  84. c := startClient(ctx, t, "//"+s.Listener.Addr().String())
  85. go handleResponses(ctx, t, c)
  86. // hacky way to abort the connection before write
  87. if err := c.conn.Close(); err != nil {
  88. t.Error(err)
  89. }
  90. // results in WS write error, the client should resend on reconnect
  91. call(ctx, t, "a", c)
  92. // expect to reconnect almost immediately
  93. time.Sleep(10 * time.Millisecond)
  94. // should succeed
  95. call(ctx, t, "b", c)
  96. }
  97. func TestWSClientReconnectFailure(t *testing.T) {
  98. t.Cleanup(leaktest.Check(t))
  99. // start server
  100. h := &myTestHandler{t: t}
  101. s := httptest.NewServer(h)
  102. ctx, cancel := context.WithCancel(context.Background())
  103. defer cancel()
  104. c := startClient(ctx, t, "//"+s.Listener.Addr().String())
  105. go func() {
  106. for {
  107. select {
  108. case <-c.ResponsesCh:
  109. case <-ctx.Done():
  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. cctx, cancel := context.WithTimeout(ctx, wsCallTimeout)
  122. defer cancel()
  123. if err := c.Call(cctx, "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(ctx, 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. t.Cleanup(leaktest.Check(t))
  144. timeout := 3 * time.Second
  145. s := httptest.NewServer(&myTestHandler{t: t})
  146. defer s.Close()
  147. ctx, cancel := context.WithCancel(context.Background())
  148. defer cancel()
  149. c := startClient(ctx, t, "//"+s.Listener.Addr().String())
  150. c.Call(ctx, "a", make(map[string]interface{})) // nolint:errcheck // ignore for tests
  151. // Let the readRoutine get around to blocking
  152. time.Sleep(time.Second)
  153. passCh := make(chan struct{})
  154. go func() {
  155. // Unless we have a non-blocking write to ResponsesCh from readRoutine
  156. // this blocks forever ont the waitgroup
  157. cancel()
  158. require.NoError(t, c.Stop())
  159. select {
  160. case <-ctx.Done():
  161. case passCh <- struct{}{}:
  162. }
  163. }()
  164. runtime.Gosched() // hacks: force context switch
  165. select {
  166. case <-passCh:
  167. // Pass
  168. case <-time.After(timeout):
  169. if c.IsRunning() {
  170. t.Fatalf("WSClient did failed to stop within %v seconds - is one of the read/write routines blocking?",
  171. timeout.Seconds())
  172. }
  173. }
  174. }
  175. func startClient(ctx context.Context, t *testing.T, addr string) *WSClient {
  176. t.Helper()
  177. t.Cleanup(leaktest.Check(t))
  178. opts := DefaultWSOptions()
  179. opts.SkipMetrics = true
  180. c, err := NewWSWithOptions(addr, "/websocket", opts)
  181. require.NoError(t, err)
  182. err = c.Start(ctx)
  183. require.NoError(t, err)
  184. c.Logger = log.NewNopLogger()
  185. return c
  186. }
  187. func call(ctx context.Context, t *testing.T, method string, c *WSClient) {
  188. t.Helper()
  189. err := c.Call(ctx, method, make(map[string]interface{}))
  190. if ctx.Err() == nil {
  191. require.NoError(t, err)
  192. }
  193. }
  194. func handleResponses(ctx context.Context, t *testing.T, c *WSClient) {
  195. t.Helper()
  196. for {
  197. select {
  198. case resp := <-c.ResponsesCh:
  199. if resp.Error != nil {
  200. t.Errorf("unexpected error: %v", resp.Error)
  201. return
  202. }
  203. if resp.Result != nil {
  204. return
  205. }
  206. case <-ctx.Done():
  207. return
  208. }
  209. }
  210. }