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.

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