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.

355 lines
8.6 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
8 years ago
  1. package jsonrpc
  2. import (
  3. "bytes"
  4. "context"
  5. crand "crypto/rand"
  6. "encoding/json"
  7. "errors"
  8. mrand "math/rand"
  9. "net/http"
  10. "os/exec"
  11. "testing"
  12. "time"
  13. "github.com/fortytw2/leaktest"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/stretchr/testify/require"
  16. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  17. "github.com/tendermint/tendermint/libs/log"
  18. "github.com/tendermint/tendermint/rpc/jsonrpc/client"
  19. "github.com/tendermint/tendermint/rpc/jsonrpc/server"
  20. )
  21. // Client and Server should work over tcp or unix sockets
  22. const (
  23. tcpAddr = "tcp://127.0.0.1:47768"
  24. unixSocket = "/tmp/rpc_test.sock"
  25. unixAddr = "unix://" + unixSocket
  26. websocketEndpoint = "/websocket/endpoint"
  27. testVal = "acbd"
  28. )
  29. type ResultEcho struct {
  30. Value string `json:"value"`
  31. }
  32. type ResultEchoInt struct {
  33. Value int `json:"value"`
  34. }
  35. type ResultEchoBytes struct {
  36. Value []byte `json:"value"`
  37. }
  38. type ResultEchoDataBytes struct {
  39. Value tmbytes.HexBytes `json:"value"`
  40. }
  41. // Define some routes
  42. var Routes = map[string]*server.RPCFunc{
  43. "echo": server.NewRPCFunc(EchoResult, "arg"),
  44. "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"),
  45. "echo_bytes": server.NewRPCFunc(EchoBytesResult, "arg"),
  46. "echo_data_bytes": server.NewRPCFunc(EchoDataBytesResult, "arg"),
  47. "echo_int": server.NewRPCFunc(EchoIntResult, "arg"),
  48. }
  49. func EchoResult(ctx context.Context, v string) (*ResultEcho, error) {
  50. return &ResultEcho{v}, nil
  51. }
  52. func EchoWSResult(ctx context.Context, v string) (*ResultEcho, error) {
  53. return &ResultEcho{v}, nil
  54. }
  55. func EchoIntResult(ctx context.Context, v int) (*ResultEchoInt, error) {
  56. return &ResultEchoInt{v}, nil
  57. }
  58. func EchoBytesResult(ctx context.Context, v []byte) (*ResultEchoBytes, error) {
  59. return &ResultEchoBytes{v}, nil
  60. }
  61. func EchoDataBytesResult(ctx context.Context, v tmbytes.HexBytes) (*ResultEchoDataBytes, error) {
  62. return &ResultEchoDataBytes{v}, nil
  63. }
  64. // launch unix and tcp servers
  65. func setup(ctx context.Context, t *testing.T, logger log.Logger) error {
  66. cmd := exec.Command("rm", "-f", unixSocket)
  67. err := cmd.Start()
  68. if err != nil {
  69. return err
  70. }
  71. if err = cmd.Wait(); err != nil {
  72. return err
  73. }
  74. tcpLogger := logger.With("socket", "tcp")
  75. mux := http.NewServeMux()
  76. server.RegisterRPCFuncs(mux, Routes, tcpLogger)
  77. wm := server.NewWebsocketManager(tcpLogger, Routes, server.ReadWait(5*time.Second), server.PingPeriod(1*time.Second))
  78. mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  79. config := server.DefaultConfig()
  80. listener1, err := server.Listen(tcpAddr, config.MaxOpenConnections)
  81. if err != nil {
  82. return err
  83. }
  84. go func() {
  85. if err := server.Serve(ctx, listener1, mux, tcpLogger, config); err != nil {
  86. if !errors.Is(err, http.ErrServerClosed) {
  87. require.NoError(t, err)
  88. }
  89. }
  90. }()
  91. unixLogger := logger.With("socket", "unix")
  92. mux2 := http.NewServeMux()
  93. server.RegisterRPCFuncs(mux2, Routes, unixLogger)
  94. wm = server.NewWebsocketManager(unixLogger, Routes)
  95. mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  96. listener2, err := server.Listen(unixAddr, config.MaxOpenConnections)
  97. if err != nil {
  98. return err
  99. }
  100. go func() {
  101. if err := server.Serve(ctx, listener2, mux2, unixLogger, config); err != nil {
  102. if !errors.Is(err, http.ErrServerClosed) {
  103. require.NoError(t, err)
  104. }
  105. }
  106. }()
  107. // wait for servers to start
  108. time.Sleep(time.Second * 2)
  109. return nil
  110. }
  111. func echoViaHTTP(ctx context.Context, cl client.Caller, val string) (string, error) {
  112. params := map[string]interface{}{
  113. "arg": val,
  114. }
  115. result := new(ResultEcho)
  116. if err := cl.Call(ctx, "echo", params, result); err != nil {
  117. return "", err
  118. }
  119. return result.Value, nil
  120. }
  121. func echoIntViaHTTP(ctx context.Context, cl client.Caller, val int) (int, error) {
  122. params := map[string]interface{}{
  123. "arg": val,
  124. }
  125. result := new(ResultEchoInt)
  126. if err := cl.Call(ctx, "echo_int", params, result); err != nil {
  127. return 0, err
  128. }
  129. return result.Value, nil
  130. }
  131. func echoBytesViaHTTP(ctx context.Context, cl client.Caller, bytes []byte) ([]byte, error) {
  132. params := map[string]interface{}{
  133. "arg": bytes,
  134. }
  135. result := new(ResultEchoBytes)
  136. if err := cl.Call(ctx, "echo_bytes", params, result); err != nil {
  137. return []byte{}, err
  138. }
  139. return result.Value, nil
  140. }
  141. func echoDataBytesViaHTTP(ctx context.Context, cl client.Caller, bytes tmbytes.HexBytes) (tmbytes.HexBytes, error) {
  142. params := map[string]interface{}{
  143. "arg": bytes,
  144. }
  145. result := new(ResultEchoDataBytes)
  146. if err := cl.Call(ctx, "echo_data_bytes", params, result); err != nil {
  147. return []byte{}, err
  148. }
  149. return result.Value, nil
  150. }
  151. func testWithHTTPClient(ctx context.Context, t *testing.T, cl client.Caller) {
  152. val := testVal
  153. got, err := echoViaHTTP(ctx, cl, val)
  154. require.NoError(t, err)
  155. assert.Equal(t, got, val)
  156. val2 := randBytes(t)
  157. got2, err := echoBytesViaHTTP(ctx, cl, val2)
  158. require.NoError(t, err)
  159. assert.Equal(t, got2, val2)
  160. val3 := tmbytes.HexBytes(randBytes(t))
  161. got3, err := echoDataBytesViaHTTP(ctx, cl, val3)
  162. require.NoError(t, err)
  163. assert.Equal(t, got3, val3)
  164. val4 := mrand.Intn(10000)
  165. got4, err := echoIntViaHTTP(ctx, cl, val4)
  166. require.NoError(t, err)
  167. assert.Equal(t, got4, val4)
  168. }
  169. func echoViaWS(ctx context.Context, cl *client.WSClient, val string) (string, error) {
  170. params := map[string]interface{}{
  171. "arg": val,
  172. }
  173. err := cl.Call(ctx, "echo", params)
  174. if err != nil {
  175. return "", err
  176. }
  177. msg := <-cl.ResponsesCh
  178. if msg.Error != nil {
  179. return "", err
  180. }
  181. result := new(ResultEcho)
  182. err = json.Unmarshal(msg.Result, result)
  183. if err != nil {
  184. return "", nil
  185. }
  186. return result.Value, nil
  187. }
  188. func echoBytesViaWS(ctx context.Context, cl *client.WSClient, bytes []byte) ([]byte, error) {
  189. params := map[string]interface{}{
  190. "arg": bytes,
  191. }
  192. err := cl.Call(ctx, "echo_bytes", params)
  193. if err != nil {
  194. return []byte{}, err
  195. }
  196. msg := <-cl.ResponsesCh
  197. if msg.Error != nil {
  198. return []byte{}, msg.Error
  199. }
  200. result := new(ResultEchoBytes)
  201. err = json.Unmarshal(msg.Result, result)
  202. if err != nil {
  203. return []byte{}, nil
  204. }
  205. return result.Value, nil
  206. }
  207. func testWithWSClient(ctx context.Context, t *testing.T, cl *client.WSClient) {
  208. val := testVal
  209. got, err := echoViaWS(ctx, cl, val)
  210. require.NoError(t, err)
  211. assert.Equal(t, got, val)
  212. val2 := randBytes(t)
  213. got2, err := echoBytesViaWS(ctx, cl, val2)
  214. require.NoError(t, err)
  215. assert.Equal(t, got2, val2)
  216. }
  217. //-------------
  218. func TestRPC(t *testing.T) {
  219. ctx, cancel := context.WithCancel(context.Background())
  220. defer cancel()
  221. logger := log.NewNopLogger()
  222. t.Cleanup(leaktest.Check(t))
  223. require.NoError(t, setup(ctx, t, logger))
  224. t.Run("ServersAndClientsBasic", func(t *testing.T) {
  225. serverAddrs := [...]string{tcpAddr, unixAddr}
  226. for _, addr := range serverAddrs {
  227. t.Run(addr, func(t *testing.T) {
  228. tctx, tcancel := context.WithCancel(ctx)
  229. defer tcancel()
  230. logger := log.NewNopLogger()
  231. cl2, err := client.New(addr)
  232. require.NoError(t, err)
  233. t.Logf("testing server with JSONRPC client")
  234. testWithHTTPClient(tctx, t, cl2)
  235. cl3, err := client.NewWS(addr, websocketEndpoint)
  236. require.NoError(t, err)
  237. cl3.Logger = logger
  238. err = cl3.Start(tctx)
  239. require.NoError(t, err)
  240. t.Logf("testing server with WS client")
  241. testWithWSClient(tctx, t, cl3)
  242. })
  243. }
  244. })
  245. t.Run("WSNewWSRPCFunc", func(t *testing.T) {
  246. t.Cleanup(leaktest.CheckTimeout(t, 4*time.Second))
  247. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  248. require.NoError(t, err)
  249. cl.Logger = log.NewNopLogger()
  250. tctx, tcancel := context.WithCancel(ctx)
  251. defer tcancel()
  252. require.NoError(t, cl.Start(tctx))
  253. t.Cleanup(func() {
  254. if err := cl.Stop(); err != nil {
  255. t.Error(err)
  256. }
  257. })
  258. val := testVal
  259. params := map[string]interface{}{
  260. "arg": val,
  261. }
  262. err = cl.Call(tctx, "echo_ws", params)
  263. require.NoError(t, err)
  264. select {
  265. case <-tctx.Done():
  266. t.Fatal(tctx.Err())
  267. case msg := <-cl.ResponsesCh:
  268. if msg.Error != nil {
  269. t.Fatal(err)
  270. }
  271. result := new(ResultEcho)
  272. err = json.Unmarshal(msg.Result, result)
  273. require.NoError(t, err)
  274. got := result.Value
  275. assert.Equal(t, got, val)
  276. }
  277. })
  278. t.Run("WSClientPingPong", func(t *testing.T) {
  279. // TestWSClientPingPong checks that a client & server exchange pings
  280. // & pongs so connection stays alive.
  281. t.Cleanup(leaktest.CheckTimeout(t, 4*time.Second))
  282. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  283. require.NoError(t, err)
  284. cl.Logger = log.NewNopLogger()
  285. tctx, tcancel := context.WithCancel(ctx)
  286. defer tcancel()
  287. require.NoError(t, cl.Start(tctx))
  288. t.Cleanup(func() {
  289. if err := cl.Stop(); err != nil {
  290. t.Error(err)
  291. }
  292. })
  293. time.Sleep(6 * time.Second)
  294. })
  295. }
  296. func randBytes(t *testing.T) []byte {
  297. n := mrand.Intn(10) + 2
  298. buf := make([]byte, n)
  299. _, err := crand.Read(buf)
  300. require.NoError(t, err)
  301. return bytes.ReplaceAll(buf, []byte("="), []byte{100})
  302. }