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.

376 lines
9.0 KiB

8 years ago
7 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package rpc
  2. import (
  3. "bytes"
  4. "context"
  5. crand "crypto/rand"
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "os"
  10. "os/exec"
  11. "testing"
  12. "time"
  13. "github.com/go-kit/kit/log/term"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/stretchr/testify/require"
  16. amino "github.com/tendermint/go-amino"
  17. cmn "github.com/tendermint/tendermint/libs/common"
  18. "github.com/tendermint/tendermint/libs/log"
  19. client "github.com/tendermint/tendermint/rpc/lib/client"
  20. server "github.com/tendermint/tendermint/rpc/lib/server"
  21. types "github.com/tendermint/tendermint/rpc/lib/types"
  22. )
  23. // Client and Server should work over tcp or unix sockets
  24. const (
  25. tcpAddr = "tcp://0.0.0.0:47768"
  26. unixSocket = "/tmp/rpc_test.sock"
  27. unixAddr = "unix://" + unixSocket
  28. websocketEndpoint = "/websocket/endpoint"
  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 cmn.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. // Amino codec required to encode/decode everything above.
  51. var RoutesCdc = amino.NewCodec()
  52. func EchoResult(ctx *types.Context, v string) (*ResultEcho, error) {
  53. return &ResultEcho{v}, nil
  54. }
  55. func EchoWSResult(ctx *types.Context, v string) (*ResultEcho, error) {
  56. return &ResultEcho{v}, nil
  57. }
  58. func EchoIntResult(ctx *types.Context, v int) (*ResultEchoInt, error) {
  59. return &ResultEchoInt{v}, nil
  60. }
  61. func EchoBytesResult(ctx *types.Context, v []byte) (*ResultEchoBytes, error) {
  62. return &ResultEchoBytes{v}, nil
  63. }
  64. func EchoDataBytesResult(ctx *types.Context, v cmn.HexBytes) (*ResultEchoDataBytes, error) {
  65. return &ResultEchoDataBytes{v}, nil
  66. }
  67. func TestMain(m *testing.M) {
  68. setup()
  69. code := m.Run()
  70. os.Exit(code)
  71. }
  72. var colorFn = func(keyvals ...interface{}) term.FgBgColor {
  73. for i := 0; i < len(keyvals)-1; i += 2 {
  74. if keyvals[i] == "socket" {
  75. if keyvals[i+1] == "tcp" {
  76. return term.FgBgColor{Fg: term.DarkBlue}
  77. } else if keyvals[i+1] == "unix" {
  78. return term.FgBgColor{Fg: term.DarkCyan}
  79. }
  80. }
  81. }
  82. return term.FgBgColor{}
  83. }
  84. // launch unix and tcp servers
  85. func setup() {
  86. logger := log.NewTMLoggerWithColorFn(log.NewSyncWriter(os.Stdout), colorFn)
  87. cmd := exec.Command("rm", "-f", unixSocket)
  88. err := cmd.Start()
  89. if err != nil {
  90. panic(err)
  91. }
  92. if err = cmd.Wait(); err != nil {
  93. panic(err)
  94. }
  95. tcpLogger := logger.With("socket", "tcp")
  96. mux := http.NewServeMux()
  97. server.RegisterRPCFuncs(mux, Routes, RoutesCdc, tcpLogger)
  98. wm := server.NewWebsocketManager(Routes, RoutesCdc, server.ReadWait(5*time.Second), server.PingPeriod(1*time.Second))
  99. wm.SetLogger(tcpLogger)
  100. mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  101. config := server.DefaultConfig()
  102. listener1, err := server.Listen(tcpAddr, config)
  103. if err != nil {
  104. panic(err)
  105. }
  106. go server.StartHTTPServer(listener1, mux, tcpLogger, config)
  107. unixLogger := logger.With("socket", "unix")
  108. mux2 := http.NewServeMux()
  109. server.RegisterRPCFuncs(mux2, Routes, RoutesCdc, unixLogger)
  110. wm = server.NewWebsocketManager(Routes, RoutesCdc)
  111. wm.SetLogger(unixLogger)
  112. mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  113. listener2, err := server.Listen(unixAddr, config)
  114. if err != nil {
  115. panic(err)
  116. }
  117. go server.StartHTTPServer(listener2, mux2, unixLogger, config)
  118. // wait for servers to start
  119. time.Sleep(time.Second * 2)
  120. }
  121. func echoViaHTTP(cl client.HTTPClient, val string) (string, error) {
  122. params := map[string]interface{}{
  123. "arg": val,
  124. }
  125. result := new(ResultEcho)
  126. if _, err := cl.Call("echo", params, result); err != nil {
  127. return "", err
  128. }
  129. return result.Value, nil
  130. }
  131. func echoIntViaHTTP(cl client.HTTPClient, val int) (int, error) {
  132. params := map[string]interface{}{
  133. "arg": val,
  134. }
  135. result := new(ResultEchoInt)
  136. if _, err := cl.Call("echo_int", params, result); err != nil {
  137. return 0, err
  138. }
  139. return result.Value, nil
  140. }
  141. func echoBytesViaHTTP(cl client.HTTPClient, bytes []byte) ([]byte, error) {
  142. params := map[string]interface{}{
  143. "arg": bytes,
  144. }
  145. result := new(ResultEchoBytes)
  146. if _, err := cl.Call("echo_bytes", params, result); err != nil {
  147. return []byte{}, err
  148. }
  149. return result.Value, nil
  150. }
  151. func echoDataBytesViaHTTP(cl client.HTTPClient, bytes cmn.HexBytes) (cmn.HexBytes, error) {
  152. params := map[string]interface{}{
  153. "arg": bytes,
  154. }
  155. result := new(ResultEchoDataBytes)
  156. if _, err := cl.Call("echo_data_bytes", params, result); err != nil {
  157. return []byte{}, err
  158. }
  159. return result.Value, nil
  160. }
  161. func testWithHTTPClient(t *testing.T, cl client.HTTPClient) {
  162. val := "acbd"
  163. got, err := echoViaHTTP(cl, val)
  164. require.Nil(t, err)
  165. assert.Equal(t, got, val)
  166. val2 := randBytes(t)
  167. got2, err := echoBytesViaHTTP(cl, val2)
  168. require.Nil(t, err)
  169. assert.Equal(t, got2, val2)
  170. val3 := cmn.HexBytes(randBytes(t))
  171. got3, err := echoDataBytesViaHTTP(cl, val3)
  172. require.Nil(t, err)
  173. assert.Equal(t, got3, val3)
  174. val4 := cmn.RandIntn(10000)
  175. got4, err := echoIntViaHTTP(cl, val4)
  176. require.Nil(t, err)
  177. assert.Equal(t, got4, val4)
  178. }
  179. func echoViaWS(cl *client.WSClient, val string) (string, error) {
  180. params := map[string]interface{}{
  181. "arg": val,
  182. }
  183. err := cl.Call(context.Background(), "echo", params)
  184. if err != nil {
  185. return "", err
  186. }
  187. msg := <-cl.ResponsesCh
  188. if msg.Error != nil {
  189. return "", err
  190. }
  191. result := new(ResultEcho)
  192. err = json.Unmarshal(msg.Result, result)
  193. if err != nil {
  194. return "", nil
  195. }
  196. return result.Value, nil
  197. }
  198. func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) {
  199. params := map[string]interface{}{
  200. "arg": bytes,
  201. }
  202. err := cl.Call(context.Background(), "echo_bytes", params)
  203. if err != nil {
  204. return []byte{}, err
  205. }
  206. msg := <-cl.ResponsesCh
  207. if msg.Error != nil {
  208. return []byte{}, msg.Error
  209. }
  210. result := new(ResultEchoBytes)
  211. err = json.Unmarshal(msg.Result, result)
  212. if err != nil {
  213. return []byte{}, nil
  214. }
  215. return result.Value, nil
  216. }
  217. func testWithWSClient(t *testing.T, cl *client.WSClient) {
  218. val := "acbd"
  219. got, err := echoViaWS(cl, val)
  220. require.Nil(t, err)
  221. assert.Equal(t, got, val)
  222. val2 := randBytes(t)
  223. got2, err := echoBytesViaWS(cl, val2)
  224. require.Nil(t, err)
  225. assert.Equal(t, got2, val2)
  226. }
  227. //-------------
  228. func TestServersAndClientsBasic(t *testing.T) {
  229. serverAddrs := [...]string{tcpAddr, unixAddr}
  230. for _, addr := range serverAddrs {
  231. cl1 := client.NewURIClient(addr)
  232. fmt.Printf("=== testing server on %s using URI client", addr)
  233. testWithHTTPClient(t, cl1)
  234. cl2 := client.NewJSONRPCClient(addr)
  235. fmt.Printf("=== testing server on %s using JSONRPC client", addr)
  236. testWithHTTPClient(t, cl2)
  237. cl3 := client.NewWSClient(addr, websocketEndpoint)
  238. cl3.SetLogger(log.TestingLogger())
  239. err := cl3.Start()
  240. require.Nil(t, err)
  241. fmt.Printf("=== testing server on %s using WS client", addr)
  242. testWithWSClient(t, cl3)
  243. cl3.Stop()
  244. }
  245. }
  246. func TestHexStringArg(t *testing.T) {
  247. cl := client.NewURIClient(tcpAddr)
  248. // should NOT be handled as hex
  249. val := "0xabc"
  250. got, err := echoViaHTTP(cl, val)
  251. require.Nil(t, err)
  252. assert.Equal(t, got, val)
  253. }
  254. func TestQuotedStringArg(t *testing.T) {
  255. cl := client.NewURIClient(tcpAddr)
  256. // should NOT be unquoted
  257. val := "\"abc\""
  258. got, err := echoViaHTTP(cl, val)
  259. require.Nil(t, err)
  260. assert.Equal(t, got, val)
  261. }
  262. func TestWSNewWSRPCFunc(t *testing.T) {
  263. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  264. cl.SetLogger(log.TestingLogger())
  265. err := cl.Start()
  266. require.Nil(t, err)
  267. defer cl.Stop()
  268. val := "acbd"
  269. params := map[string]interface{}{
  270. "arg": val,
  271. }
  272. err = cl.Call(context.Background(), "echo_ws", params)
  273. require.Nil(t, err)
  274. msg := <-cl.ResponsesCh
  275. if msg.Error != nil {
  276. t.Fatal(err)
  277. }
  278. result := new(ResultEcho)
  279. err = json.Unmarshal(msg.Result, result)
  280. require.Nil(t, err)
  281. got := result.Value
  282. assert.Equal(t, got, val)
  283. }
  284. func TestWSHandlesArrayParams(t *testing.T) {
  285. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  286. cl.SetLogger(log.TestingLogger())
  287. err := cl.Start()
  288. require.Nil(t, err)
  289. defer cl.Stop()
  290. val := "acbd"
  291. params := []interface{}{val}
  292. err = cl.CallWithArrayParams(context.Background(), "echo_ws", params)
  293. require.Nil(t, err)
  294. msg := <-cl.ResponsesCh
  295. if msg.Error != nil {
  296. t.Fatalf("%+v", err)
  297. }
  298. result := new(ResultEcho)
  299. err = json.Unmarshal(msg.Result, result)
  300. require.Nil(t, err)
  301. got := result.Value
  302. assert.Equal(t, got, val)
  303. }
  304. // TestWSClientPingPong checks that a client & server exchange pings
  305. // & pongs so connection stays alive.
  306. func TestWSClientPingPong(t *testing.T) {
  307. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  308. cl.SetLogger(log.TestingLogger())
  309. err := cl.Start()
  310. require.Nil(t, err)
  311. defer cl.Stop()
  312. time.Sleep(6 * time.Second)
  313. }
  314. func randBytes(t *testing.T) []byte {
  315. n := cmn.RandIntn(10) + 2
  316. buf := make([]byte, n)
  317. _, err := crand.Read(buf)
  318. require.Nil(t, err)
  319. return bytes.Replace(buf, []byte("="), []byte{100}, -1)
  320. }