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.4 KiB

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