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.

378 lines
9.0 KiB

7 years ago
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>
5 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>
5 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>
5 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>
5 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>
5 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 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. testVal = "acbd"
  30. )
  31. type ResultEcho struct {
  32. Value string `json:"value"`
  33. }
  34. type ResultEchoInt struct {
  35. Value int `json:"value"`
  36. }
  37. type ResultEchoBytes struct {
  38. Value []byte `json:"value"`
  39. }
  40. type ResultEchoDataBytes struct {
  41. Value cmn.HexBytes `json:"value"`
  42. }
  43. // Define some routes
  44. var Routes = map[string]*server.RPCFunc{
  45. "echo": server.NewRPCFunc(EchoResult, "arg"),
  46. "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"),
  47. "echo_bytes": server.NewRPCFunc(EchoBytesResult, "arg"),
  48. "echo_data_bytes": server.NewRPCFunc(EchoDataBytesResult, "arg"),
  49. "echo_int": server.NewRPCFunc(EchoIntResult, "arg"),
  50. }
  51. // Amino codec required to encode/decode everything above.
  52. var RoutesCdc = amino.NewCodec()
  53. func EchoResult(ctx *types.Context, v string) (*ResultEcho, error) {
  54. return &ResultEcho{v}, nil
  55. }
  56. func EchoWSResult(ctx *types.Context, v string) (*ResultEcho, error) {
  57. return &ResultEcho{v}, nil
  58. }
  59. func EchoIntResult(ctx *types.Context, v int) (*ResultEchoInt, error) {
  60. return &ResultEchoInt{v}, nil
  61. }
  62. func EchoBytesResult(ctx *types.Context, v []byte) (*ResultEchoBytes, error) {
  63. return &ResultEchoBytes{v}, nil
  64. }
  65. func EchoDataBytesResult(ctx *types.Context, v cmn.HexBytes) (*ResultEchoDataBytes, error) {
  66. return &ResultEchoDataBytes{v}, nil
  67. }
  68. func TestMain(m *testing.M) {
  69. setup()
  70. code := m.Run()
  71. os.Exit(code)
  72. }
  73. var colorFn = func(keyvals ...interface{}) term.FgBgColor {
  74. for i := 0; i < len(keyvals)-1; i += 2 {
  75. if keyvals[i] == "socket" {
  76. if keyvals[i+1] == "tcp" {
  77. return term.FgBgColor{Fg: term.DarkBlue}
  78. } else if keyvals[i+1] == "unix" {
  79. return term.FgBgColor{Fg: term.DarkCyan}
  80. }
  81. }
  82. }
  83. return term.FgBgColor{}
  84. }
  85. // launch unix and tcp servers
  86. func setup() {
  87. logger := log.NewTMLoggerWithColorFn(log.NewSyncWriter(os.Stdout), colorFn)
  88. cmd := exec.Command("rm", "-f", unixSocket)
  89. err := cmd.Start()
  90. if err != nil {
  91. panic(err)
  92. }
  93. if err = cmd.Wait(); err != nil {
  94. panic(err)
  95. }
  96. tcpLogger := logger.With("socket", "tcp")
  97. mux := http.NewServeMux()
  98. server.RegisterRPCFuncs(mux, Routes, RoutesCdc, tcpLogger)
  99. wm := server.NewWebsocketManager(Routes, RoutesCdc, server.ReadWait(5*time.Second), server.PingPeriod(1*time.Second))
  100. wm.SetLogger(tcpLogger)
  101. mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  102. config := server.DefaultConfig()
  103. listener1, err := server.Listen(tcpAddr, config)
  104. if err != nil {
  105. panic(err)
  106. }
  107. go server.StartHTTPServer(listener1, mux, tcpLogger, config)
  108. unixLogger := logger.With("socket", "unix")
  109. mux2 := http.NewServeMux()
  110. server.RegisterRPCFuncs(mux2, Routes, RoutesCdc, unixLogger)
  111. wm = server.NewWebsocketManager(Routes, RoutesCdc)
  112. wm.SetLogger(unixLogger)
  113. mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  114. listener2, err := server.Listen(unixAddr, config)
  115. if err != nil {
  116. panic(err)
  117. }
  118. go server.StartHTTPServer(listener2, mux2, unixLogger, config)
  119. // wait for servers to start
  120. time.Sleep(time.Second * 2)
  121. }
  122. func echoViaHTTP(cl client.JSONRPCCaller, val string) (string, error) {
  123. params := map[string]interface{}{
  124. "arg": val,
  125. }
  126. result := new(ResultEcho)
  127. if _, err := cl.Call("echo", params, result); err != nil {
  128. return "", err
  129. }
  130. return result.Value, nil
  131. }
  132. func echoIntViaHTTP(cl client.JSONRPCCaller, val int) (int, error) {
  133. params := map[string]interface{}{
  134. "arg": val,
  135. }
  136. result := new(ResultEchoInt)
  137. if _, err := cl.Call("echo_int", params, result); err != nil {
  138. return 0, err
  139. }
  140. return result.Value, nil
  141. }
  142. func echoBytesViaHTTP(cl client.JSONRPCCaller, bytes []byte) ([]byte, error) {
  143. params := map[string]interface{}{
  144. "arg": bytes,
  145. }
  146. result := new(ResultEchoBytes)
  147. if _, err := cl.Call("echo_bytes", params, result); err != nil {
  148. return []byte{}, err
  149. }
  150. return result.Value, nil
  151. }
  152. func echoDataBytesViaHTTP(cl client.JSONRPCCaller, bytes cmn.HexBytes) (cmn.HexBytes, error) {
  153. params := map[string]interface{}{
  154. "arg": bytes,
  155. }
  156. result := new(ResultEchoDataBytes)
  157. if _, err := cl.Call("echo_data_bytes", params, result); err != nil {
  158. return []byte{}, err
  159. }
  160. return result.Value, nil
  161. }
  162. func testWithHTTPClient(t *testing.T, cl client.HTTPClient) {
  163. val := testVal
  164. got, err := echoViaHTTP(cl, val)
  165. require.Nil(t, err)
  166. assert.Equal(t, got, val)
  167. val2 := randBytes(t)
  168. got2, err := echoBytesViaHTTP(cl, val2)
  169. require.Nil(t, err)
  170. assert.Equal(t, got2, val2)
  171. val3 := cmn.HexBytes(randBytes(t))
  172. got3, err := echoDataBytesViaHTTP(cl, val3)
  173. require.Nil(t, err)
  174. assert.Equal(t, got3, val3)
  175. val4 := cmn.RandIntn(10000)
  176. got4, err := echoIntViaHTTP(cl, val4)
  177. require.Nil(t, err)
  178. assert.Equal(t, got4, val4)
  179. }
  180. func echoViaWS(cl *client.WSClient, val string) (string, error) {
  181. params := map[string]interface{}{
  182. "arg": val,
  183. }
  184. err := cl.Call(context.Background(), "echo", params)
  185. if err != nil {
  186. return "", err
  187. }
  188. msg := <-cl.ResponsesCh
  189. if msg.Error != nil {
  190. return "", err
  191. }
  192. result := new(ResultEcho)
  193. err = json.Unmarshal(msg.Result, result)
  194. if err != nil {
  195. return "", nil
  196. }
  197. return result.Value, nil
  198. }
  199. func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) {
  200. params := map[string]interface{}{
  201. "arg": bytes,
  202. }
  203. err := cl.Call(context.Background(), "echo_bytes", params)
  204. if err != nil {
  205. return []byte{}, err
  206. }
  207. msg := <-cl.ResponsesCh
  208. if msg.Error != nil {
  209. return []byte{}, msg.Error
  210. }
  211. result := new(ResultEchoBytes)
  212. err = json.Unmarshal(msg.Result, result)
  213. if err != nil {
  214. return []byte{}, nil
  215. }
  216. return result.Value, nil
  217. }
  218. func testWithWSClient(t *testing.T, cl *client.WSClient) {
  219. val := testVal
  220. got, err := echoViaWS(cl, val)
  221. require.Nil(t, err)
  222. assert.Equal(t, got, val)
  223. val2 := randBytes(t)
  224. got2, err := echoBytesViaWS(cl, val2)
  225. require.Nil(t, err)
  226. assert.Equal(t, got2, val2)
  227. }
  228. //-------------
  229. func TestServersAndClientsBasic(t *testing.T) {
  230. serverAddrs := [...]string{tcpAddr, unixAddr}
  231. for _, addr := range serverAddrs {
  232. cl1 := client.NewURIClient(addr)
  233. fmt.Printf("=== testing server on %s using URI client", addr)
  234. testWithHTTPClient(t, cl1)
  235. cl2 := client.NewJSONRPCClient(addr)
  236. fmt.Printf("=== testing server on %s using JSONRPC client", addr)
  237. testWithHTTPClient(t, cl2)
  238. cl3 := client.NewWSClient(addr, websocketEndpoint)
  239. cl3.SetLogger(log.TestingLogger())
  240. err := cl3.Start()
  241. require.Nil(t, err)
  242. fmt.Printf("=== testing server on %s using WS client", addr)
  243. testWithWSClient(t, cl3)
  244. cl3.Stop()
  245. }
  246. }
  247. func TestHexStringArg(t *testing.T) {
  248. cl := client.NewURIClient(tcpAddr)
  249. // should NOT be handled as hex
  250. val := "0xabc"
  251. got, err := echoViaHTTP(cl, val)
  252. require.Nil(t, err)
  253. assert.Equal(t, got, val)
  254. }
  255. func TestQuotedStringArg(t *testing.T) {
  256. cl := client.NewURIClient(tcpAddr)
  257. // should NOT be unquoted
  258. val := "\"abc\""
  259. got, err := echoViaHTTP(cl, val)
  260. require.Nil(t, err)
  261. assert.Equal(t, got, val)
  262. }
  263. func TestWSNewWSRPCFunc(t *testing.T) {
  264. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  265. cl.SetLogger(log.TestingLogger())
  266. err := cl.Start()
  267. require.Nil(t, err)
  268. defer cl.Stop()
  269. val := testVal
  270. params := map[string]interface{}{
  271. "arg": val,
  272. }
  273. err = cl.Call(context.Background(), "echo_ws", params)
  274. require.Nil(t, err)
  275. msg := <-cl.ResponsesCh
  276. if msg.Error != nil {
  277. t.Fatal(err)
  278. }
  279. result := new(ResultEcho)
  280. err = json.Unmarshal(msg.Result, result)
  281. require.Nil(t, err)
  282. got := result.Value
  283. assert.Equal(t, got, val)
  284. }
  285. func TestWSHandlesArrayParams(t *testing.T) {
  286. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  287. cl.SetLogger(log.TestingLogger())
  288. err := cl.Start()
  289. require.Nil(t, err)
  290. defer cl.Stop()
  291. val := testVal
  292. params := []interface{}{val}
  293. err = cl.CallWithArrayParams(context.Background(), "echo_ws", params)
  294. require.Nil(t, err)
  295. msg := <-cl.ResponsesCh
  296. if msg.Error != nil {
  297. t.Fatalf("%+v", err)
  298. }
  299. result := new(ResultEcho)
  300. err = json.Unmarshal(msg.Result, result)
  301. require.Nil(t, err)
  302. got := result.Value
  303. assert.Equal(t, got, val)
  304. }
  305. // TestWSClientPingPong checks that a client & server exchange pings
  306. // & pongs so connection stays alive.
  307. func TestWSClientPingPong(t *testing.T) {
  308. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  309. cl.SetLogger(log.TestingLogger())
  310. err := cl.Start()
  311. require.Nil(t, err)
  312. defer cl.Stop()
  313. time.Sleep(6 * time.Second)
  314. }
  315. func randBytes(t *testing.T) []byte {
  316. n := cmn.RandIntn(10) + 2
  317. buf := make([]byte, n)
  318. _, err := crand.Read(buf)
  319. require.Nil(t, err)
  320. return bytes.Replace(buf, []byte("="), []byte{100}, -1)
  321. }