rpc: refactor lib folder (#4836)

Closes https://github.com/tendermint/tendermint/issues/3857

Moves `lib/` folder to `jsonrpc/`.

Renames:

**packages**

`rpc` package -> `jsonrpc` package
`rpcclient` package -> `client` package
`rpcserver` package -> `server` package

**structs and interfaces**

```
JSONRPCClient to Client
JSONRPCRequestBatch to RequestBatch
JSONRPCCaller to Caller
```

**functions**

```
StartHTTPServer to Serve
StartHTTPAndTLSServer to ServeTLS

rpc/jsonrpc/client: rename NewURIClient to NewURI

NewJSONRPCClient to New
NewJSONRPCClientWithHTTPClient to NewWithHTTPClient
NewWSClient to NewWS
```

**misc**

- unexpose `ResponseWriterWrapper`
- remove unused http_params.go
This commit is contained in:
Anton Kaliaev
2020-05-13 16:40:57 +04:00
committed by GitHub
parent e20105e658
commit a14ff5cb30
57 changed files with 191 additions and 248 deletions
+9 -9
View File
@@ -16,7 +16,7 @@ import (
"github.com/tendermint/tendermint/libs/service"
rpcclient "github.com/tendermint/tendermint/rpc/client"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpcclientlib "github.com/tendermint/tendermint/rpc/lib/client"
jsonrpcclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
"github.com/tendermint/tendermint/types"
)
@@ -61,7 +61,7 @@ Example:
*/
type HTTP struct {
remote string
rpc *rpcclientlib.JSONRPCClient
rpc *jsonrpcclient.Client
*baseRPCClient
*WSEvents
@@ -78,7 +78,7 @@ type HTTP struct {
// batch, but ordering of transactions in the batch cannot be guaranteed in such
// an example.
type BatchHTTP struct {
rpcBatch *rpcclientlib.JSONRPCRequestBatch
rpcBatch *jsonrpcclient.RequestBatch
*baseRPCClient
}
@@ -96,7 +96,7 @@ type rpcClient interface {
// baseRPCClient implements the basic RPC method logic without the actual
// underlying RPC call functionality, which is provided by `caller`.
type baseRPCClient struct {
caller rpcclientlib.JSONRPCCaller
caller jsonrpcclient.Caller
}
var _ rpcClient = (*HTTP)(nil)
@@ -110,7 +110,7 @@ var _ rpcClient = (*baseRPCClient)(nil)
// the websocket path (which always seems to be "/websocket")
// An error is returned on invalid remote. The function panics when remote is nil.
func New(remote, wsEndpoint string) (*HTTP, error) {
httpClient, err := rpcclientlib.DefaultHTTPClient(remote)
httpClient, err := jsonrpcclient.DefaultHTTPClient(remote)
if err != nil {
return nil, err
}
@@ -119,7 +119,7 @@ func New(remote, wsEndpoint string) (*HTTP, error) {
// Create timeout enabled http client
func NewWithTimeout(remote, wsEndpoint string, timeout uint) (*HTTP, error) {
httpClient, err := rpcclientlib.DefaultHTTPClient(remote)
httpClient, err := jsonrpcclient.DefaultHTTPClient(remote)
if err != nil {
return nil, err
}
@@ -134,7 +134,7 @@ func NewWithClient(remote, wsEndpoint string, client *http.Client) (*HTTP, error
panic("nil http.Client provided")
}
rc, err := rpcclientlib.NewJSONRPCClientWithHTTPClient(remote, client)
rc, err := jsonrpcclient.NewWithHTTPClient(remote, client)
if err != nil {
return nil, err
}
@@ -459,7 +459,7 @@ type WSEvents struct {
cdc *amino.Codec
remote string
endpoint string
ws *rpcclientlib.WSClient
ws *jsonrpcclient.WSClient
mtx sync.RWMutex
subscriptions map[string]chan ctypes.ResultEvent // query -> chan
@@ -475,7 +475,7 @@ func newWSEvents(cdc *amino.Codec, remote, endpoint string) (*WSEvents, error) {
w.BaseService = *service.NewBaseService(nil, "WSEvents", w)
var err error
w.ws, err = rpcclientlib.NewWSClient(w.remote, w.endpoint, rpcclientlib.OnReconnect(func() {
w.ws, err = jsonrpcclient.NewWS(w.remote, w.endpoint, jsonrpcclient.OnReconnect(func() {
// resubscribe immediately
w.redoSubscriptionsAfter(0 * time.Second)
}))
+1 -1
View File
@@ -13,7 +13,7 @@ import (
rpcclient "github.com/tendermint/tendermint/rpc/client"
"github.com/tendermint/tendermint/rpc/core"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
+1 -1
View File
@@ -22,7 +22,7 @@ import (
"github.com/tendermint/tendermint/rpc/client"
"github.com/tendermint/tendermint/rpc/core"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
+4 -4
View File
@@ -20,7 +20,7 @@ import (
rpchttp "github.com/tendermint/tendermint/rpc/client/http"
rpclocal "github.com/tendermint/tendermint/rpc/client/local"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpcclient "github.com/tendermint/tendermint/rpc/lib/client"
rpcclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
rpctest "github.com/tendermint/tendermint/rpc/test"
"github.com/tendermint/tendermint/types"
)
@@ -62,7 +62,7 @@ func TestNilCustomHTTPClient(t *testing.T) {
_, _ = rpchttp.NewWithClient("http://example.com", "/websocket", nil)
})
require.Panics(t, func() {
_, _ = rpcclient.NewJSONRPCClientWithHTTPClient("http://example.com", nil)
_, _ = rpcclient.NewWithHTTPClient("http://example.com", nil)
})
}
@@ -634,14 +634,14 @@ func TestBatchedJSONRPCCallsCancellation(t *testing.T) {
require.Equal(t, 0, batch.Count())
}
func TestSendingEmptyJSONRPCRequestBatch(t *testing.T) {
func TestSendingEmptyRequestBatch(t *testing.T) {
c := getHTTPClient()
batch := c.NewBatch()
_, err := batch.Send()
require.Error(t, err, "sending an empty batch of JSON RPC requests should result in an error")
}
func TestClearingEmptyJSONRPCRequestBatch(t *testing.T) {
func TestClearingEmptyRequestBatch(t *testing.T) {
c := getHTTPClient()
batch := c.NewBatch()
require.Zero(t, batch.Clear(), "clearing an empty batch of JSON RPC requests should result in a 0 result")
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"github.com/tendermint/tendermint/libs/bytes"
"github.com/tendermint/tendermint/proxy"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
// ABCIQuery queries the application for some information.
+1 -1
View File
@@ -5,7 +5,7 @@ import (
tmmath "github.com/tendermint/tendermint/libs/math"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
sm "github.com/tendermint/tendermint/state"
"github.com/tendermint/tendermint/types"
)
+1 -1
View File
@@ -11,7 +11,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
sm "github.com/tendermint/tendermint/state"
"github.com/tendermint/tendermint/types"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
cm "github.com/tendermint/tendermint/consensus"
tmmath "github.com/tendermint/tendermint/libs/math"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
sm "github.com/tendermint/tendermint/state"
"github.com/tendermint/tendermint/types"
)
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"runtime/pprof"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
// UnsafeFlushMempool removes all transactions from the mempool.
+1 -1
View File
@@ -7,7 +7,7 @@ import (
tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
tmquery "github.com/tendermint/tendermint/libs/pubsub/query"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
const (
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"fmt"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
+1 -1
View File
@@ -2,7 +2,7 @@ package core
import (
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
// Health gets node health. Returns empty result (200 OK) on success, no
+1 -1
View File
@@ -9,7 +9,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
mempl "github.com/tendermint/tendermint/mempool"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/types"
)
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"github.com/tendermint/tendermint/p2p"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
// NetInfo returns network info.
+1 -1
View File
@@ -9,7 +9,7 @@ import (
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/p2p"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
func TestUnsafeDialSeeds(t *testing.T) {
+1 -1
View File
@@ -1,7 +1,7 @@
package core
import (
rpc "github.com/tendermint/tendermint/rpc/lib/server"
rpc "github.com/tendermint/tendermint/rpc/jsonrpc/server"
)
// TODO: better system than "unsafe" prefix
+1 -1
View File
@@ -7,7 +7,7 @@ import (
tmbytes "github.com/tendermint/tendermint/libs/bytes"
"github.com/tendermint/tendermint/p2p"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
sm "github.com/tendermint/tendermint/state"
"github.com/tendermint/tendermint/types"
)
+1 -1
View File
@@ -8,7 +8,7 @@ import (
tmmath "github.com/tendermint/tendermint/libs/math"
tmquery "github.com/tendermint/tendermint/libs/pubsub/query"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
"github.com/tendermint/tendermint/state/txindex/null"
"github.com/tendermint/tendermint/types"
)
+1 -1
View File
@@ -5,7 +5,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
core "github.com/tendermint/tendermint/rpc/core"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
type broadcastAPI struct {
@@ -1,4 +1,4 @@
package rpcclient
package client
import (
"testing"
@@ -1,4 +1,4 @@
package rpcclient
package client
import (
"encoding/json"
@@ -7,7 +7,7 @@ import (
amino "github.com/tendermint/go-amino"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
func unmarshalResponseBytes(
@@ -1,4 +1,4 @@
package rpcclient
package client
import (
"fmt"
@@ -1,4 +1,4 @@
package rpcclient
package client
import (
"bytes"
@@ -13,7 +13,7 @@ import (
amino "github.com/tendermint/go-amino"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
const (
@@ -87,21 +87,21 @@ type HTTPClient interface {
SetCodec(*amino.Codec)
}
// JSONRPCCaller implementers can facilitate calling the JSON-RPC endpoint.
type JSONRPCCaller interface {
// Caller implementers can facilitate calling the JSON-RPC endpoint.
type Caller interface {
Call(method string, params map[string]interface{}, result interface{}) (interface{}, error)
}
//-------------------------------------------------------------
// JSONRPCClient is a JSON-RPC client, which sends POST HTTP requests to the
// Client is a JSON-RPC client, which sends POST HTTP requests to the
// remote server.
//
// Request values are amino encoded. Response is expected to be amino encoded.
// New amino codec is used if no other codec was set using SetCodec.
//
// JSONRPCClient is safe for concurrent use by multiple goroutines.
type JSONRPCClient struct {
// Client is safe for concurrent use by multiple goroutines.
type Client struct {
address string
username string
password string
@@ -113,27 +113,27 @@ type JSONRPCClient struct {
nextReqID int
}
var _ HTTPClient = (*JSONRPCClient)(nil)
var _ HTTPClient = (*Client)(nil)
// Both JSONRPCClient and JSONRPCRequestBatch can facilitate calls to the JSON
// Both Client and RequestBatch can facilitate calls to the JSON
// RPC endpoint.
var _ JSONRPCCaller = (*JSONRPCClient)(nil)
var _ JSONRPCCaller = (*JSONRPCRequestBatch)(nil)
var _ Caller = (*Client)(nil)
var _ Caller = (*RequestBatch)(nil)
// NewJSONRPCClient returns a JSONRPCClient pointed at the given address.
// New returns a Client pointed at the given address.
// An error is returned on invalid remote. The function panics when remote is nil.
func NewJSONRPCClient(remote string) (*JSONRPCClient, error) {
func New(remote string) (*Client, error) {
httpClient, err := DefaultHTTPClient(remote)
if err != nil {
return nil, err
}
return NewJSONRPCClientWithHTTPClient(remote, httpClient)
return NewWithHTTPClient(remote, httpClient)
}
// NewJSONRPCClientWithHTTPClient returns a JSONRPCClient pointed at the given
// NewWithHTTPClient returns a Client pointed at the given
// address using a custom http client. An error is returned on invalid remote.
// The function panics when remote is nil.
func NewJSONRPCClientWithHTTPClient(remote string, client *http.Client) (*JSONRPCClient, error) {
func NewWithHTTPClient(remote string, client *http.Client) (*Client, error) {
if client == nil {
panic("nil http.Client provided")
}
@@ -149,7 +149,7 @@ func NewJSONRPCClientWithHTTPClient(remote string, client *http.Client) (*JSONRP
username := parsedURL.User.Username()
password, _ := parsedURL.User.Password()
rpcClient := &JSONRPCClient{
rpcClient := &Client{
address: address,
username: username,
password: password,
@@ -162,7 +162,7 @@ func NewJSONRPCClientWithHTTPClient(remote string, client *http.Client) (*JSONRP
// Call issues a POST HTTP request. Requests are JSON encoded. Content-Type:
// text/json.
func (c *JSONRPCClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
func (c *Client) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
id := c.nextRequestID()
request, err := types.MapToRequest(c.cdc, id, method, params)
@@ -198,18 +198,18 @@ func (c *JSONRPCClient) Call(method string, params map[string]interface{}, resul
return unmarshalResponseBytes(c.cdc, responseBytes, id, result)
}
func (c *JSONRPCClient) Codec() *amino.Codec { return c.cdc }
func (c *JSONRPCClient) SetCodec(cdc *amino.Codec) { c.cdc = cdc }
func (c *Client) Codec() *amino.Codec { return c.cdc }
func (c *Client) SetCodec(cdc *amino.Codec) { c.cdc = cdc }
// NewRequestBatch starts a batch of requests for this client.
func (c *JSONRPCClient) NewRequestBatch() *JSONRPCRequestBatch {
return &JSONRPCRequestBatch{
func (c *Client) NewRequestBatch() *RequestBatch {
return &RequestBatch{
requests: make([]*jsonRPCBufferedRequest, 0),
client: c,
}
}
func (c *JSONRPCClient) sendBatch(requests []*jsonRPCBufferedRequest) ([]interface{}, error) {
func (c *Client) sendBatch(requests []*jsonRPCBufferedRequest) ([]interface{}, error) {
reqs := make([]types.RPCRequest, 0, len(requests))
results := make([]interface{}, 0, len(requests))
for _, req := range requests {
@@ -251,7 +251,7 @@ func (c *JSONRPCClient) sendBatch(requests []*jsonRPCBufferedRequest) ([]interfa
return unmarshalResponseBytesArray(c.cdc, responseBytes, ids, results)
}
func (c *JSONRPCClient) nextRequestID() types.JSONRPCIntID {
func (c *Client) nextRequestID() types.JSONRPCIntID {
c.mtx.Lock()
id := c.nextReqID
c.nextReqID++
@@ -268,37 +268,37 @@ type jsonRPCBufferedRequest struct {
result interface{} // The result will be deserialized into this object.
}
// JSONRPCRequestBatch allows us to buffer multiple request/response structures
// RequestBatch allows us to buffer multiple request/response structures
// into a single batch request. Note that this batch acts like a FIFO queue, and
// is thread-safe.
type JSONRPCRequestBatch struct {
client *JSONRPCClient
type RequestBatch struct {
client *Client
mtx sync.Mutex
requests []*jsonRPCBufferedRequest
}
// Count returns the number of enqueued requests waiting to be sent.
func (b *JSONRPCRequestBatch) Count() int {
func (b *RequestBatch) Count() int {
b.mtx.Lock()
defer b.mtx.Unlock()
return len(b.requests)
}
func (b *JSONRPCRequestBatch) enqueue(req *jsonRPCBufferedRequest) {
func (b *RequestBatch) enqueue(req *jsonRPCBufferedRequest) {
b.mtx.Lock()
defer b.mtx.Unlock()
b.requests = append(b.requests, req)
}
// Clear empties out the request batch.
func (b *JSONRPCRequestBatch) Clear() int {
func (b *RequestBatch) Clear() int {
b.mtx.Lock()
defer b.mtx.Unlock()
return b.clear()
}
func (b *JSONRPCRequestBatch) clear() int {
func (b *RequestBatch) clear() int {
count := len(b.requests)
b.requests = make([]*jsonRPCBufferedRequest, 0)
return count
@@ -307,7 +307,7 @@ func (b *JSONRPCRequestBatch) clear() int {
// Send will attempt to send the current batch of enqueued requests, and then
// will clear out the requests once done. On success, this returns the
// deserialized list of results from each of the enqueued requests.
func (b *JSONRPCRequestBatch) Send() ([]interface{}, error) {
func (b *RequestBatch) Send() ([]interface{}, error) {
b.mtx.Lock()
defer func() {
b.clear()
@@ -317,8 +317,8 @@ func (b *JSONRPCRequestBatch) Send() ([]interface{}, error) {
}
// Call enqueues a request to call the given RPC method with the specified
// parameters, in the same way that the `JSONRPCClient.Call` function would.
func (b *JSONRPCRequestBatch) Call(
// parameters, in the same way that the `Client.Call` function would.
func (b *RequestBatch) Call(
method string,
params map[string]interface{},
result interface{},
@@ -1,4 +1,4 @@
package rpcclient
package client
import (
"testing"
@@ -1,4 +1,4 @@
package rpcclient
package client
import (
"fmt"
@@ -7,7 +7,7 @@ import (
amino "github.com/tendermint/go-amino"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
const (
@@ -30,10 +30,10 @@ type URIClient struct {
var _ HTTPClient = (*URIClient)(nil)
// NewURIClient returns a new client.
// NewURI returns a new client.
// An error is returned on invalid remote.
// The function panics when remote is nil.
func NewURIClient(remote string) (*URIClient, error) {
func NewURI(remote string) (*URIClient, error) {
parsedURL, err := newParsedURL(remote)
if err != nil {
return nil, err
@@ -3,7 +3,7 @@
// The code in here is comprehensive as an integration
// test and is long, hence is only run before releases.
package rpcclient
package client
import (
"bytes"
@@ -29,7 +29,7 @@ func TestWSClientReconnectWithJitter(t *testing.T) {
buf := new(bytes.Buffer)
logger := log.NewTMLogger(buf)
for i := 0; i < n; i++ {
c, err := NewWSClient("tcp://foo", "/websocket")
c, err := NewWS("tcp://foo", "/websocket")
require.Nil(t, err)
c.Dialer = func(string, string) (net.Conn, error) {
return nil, errNotConnected
@@ -1,4 +1,4 @@
package rpcclient
package client
import (
"context"
@@ -16,7 +16,7 @@ import (
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/libs/service"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
const (
@@ -81,11 +81,11 @@ type WSClient struct { // nolint: maligned
PingPongLatencyTimer metrics.Timer
}
// NewWSClient returns a new client. See the commentary on the func(*WSClient)
// NewWS returns a new client. See the commentary on the func(*WSClient)
// functions for a detailed description of how to configure ping period and
// pong wait time. The endpoint argument must begin with a `/`.
// An error is returned on invalid remote. The function panics when remote is nil.
func NewWSClient(remoteAddr, endpoint string, options ...func(*WSClient)) (*WSClient, error) {
func NewWS(remoteAddr, endpoint string, options ...func(*WSClient)) (*WSClient, error) {
parsedURL, err := newParsedURL(remoteAddr)
if err != nil {
return nil, err
@@ -1,4 +1,4 @@
package rpcclient
package client
import (
"context"
@@ -14,7 +14,7 @@ import (
"github.com/tendermint/tendermint/libs/log"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
var wsCallTimeout = 5 * time.Second
@@ -201,7 +201,7 @@ func TestNotBlockingOnStop(t *testing.T) {
}
func startClient(t *testing.T, addr string) *WSClient {
c, err := NewWSClient(addr, "/websocket")
c, err := NewWS(addr, "/websocket")
require.Nil(t, err)
err = c.Start()
require.Nil(t, err)
+2 -2
View File
@@ -73,7 +73,7 @@
// logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
// listener, err := rpc.Listen("0.0.0.0:8080", rpcserver.Config{})
// if err != nil { panic(err) }
// go rpcserver.StartHTTPServer(listener, mux, logger)
// go rpcserver.Serve(listener, mux, logger)
//
// Note that unix sockets are supported as well (eg. `/path/to/socket` instead of `0.0.0.0:8008`)
// Now see all available endpoints by sending a GET request to `0.0.0.0:8008`.
@@ -82,4 +82,4 @@
// Examples
//
// - [Tendermint](https://github.com/tendermint/tendermint/blob/master/rpc/core/routes.go)
package rpc
package jsonrpc
@@ -1,4 +1,4 @@
package rpc
package jsonrpc
import (
"bytes"
@@ -22,9 +22,9 @@ import (
"github.com/tendermint/tendermint/libs/log"
tmrand "github.com/tendermint/tendermint/libs/rand"
client "github.com/tendermint/tendermint/rpc/lib/client"
server "github.com/tendermint/tendermint/rpc/lib/server"
types "github.com/tendermint/tendermint/rpc/lib/types"
client "github.com/tendermint/tendermint/rpc/jsonrpc/client"
server "github.com/tendermint/tendermint/rpc/jsonrpc/server"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
// Client and Server should work over tcp or unix sockets
@@ -130,7 +130,7 @@ func setup() {
if err != nil {
panic(err)
}
go server.StartHTTPServer(listener1, mux, tcpLogger, config)
go server.Serve(listener1, mux, tcpLogger, config)
unixLogger := logger.With("socket", "unix")
mux2 := http.NewServeMux()
@@ -142,13 +142,13 @@ func setup() {
if err != nil {
panic(err)
}
go server.StartHTTPServer(listener2, mux2, unixLogger, config)
go server.Serve(listener2, mux2, unixLogger, config)
// wait for servers to start
time.Sleep(time.Second * 2)
}
func echoViaHTTP(cl client.JSONRPCCaller, val string) (string, error) {
func echoViaHTTP(cl client.Caller, val string) (string, error) {
params := map[string]interface{}{
"arg": val,
}
@@ -159,7 +159,7 @@ func echoViaHTTP(cl client.JSONRPCCaller, val string) (string, error) {
return result.Value, nil
}
func echoIntViaHTTP(cl client.JSONRPCCaller, val int) (int, error) {
func echoIntViaHTTP(cl client.Caller, val int) (int, error) {
params := map[string]interface{}{
"arg": val,
}
@@ -170,7 +170,7 @@ func echoIntViaHTTP(cl client.JSONRPCCaller, val int) (int, error) {
return result.Value, nil
}
func echoBytesViaHTTP(cl client.JSONRPCCaller, bytes []byte) ([]byte, error) {
func echoBytesViaHTTP(cl client.Caller, bytes []byte) ([]byte, error) {
params := map[string]interface{}{
"arg": bytes,
}
@@ -181,7 +181,7 @@ func echoBytesViaHTTP(cl client.JSONRPCCaller, bytes []byte) ([]byte, error) {
return result.Value, nil
}
func echoDataBytesViaHTTP(cl client.JSONRPCCaller, bytes tmbytes.HexBytes) (tmbytes.HexBytes, error) {
func echoDataBytesViaHTTP(cl client.Caller, bytes tmbytes.HexBytes) (tmbytes.HexBytes, error) {
params := map[string]interface{}{
"arg": bytes,
}
@@ -275,17 +275,17 @@ func testWithWSClient(t *testing.T, cl *client.WSClient) {
func TestServersAndClientsBasic(t *testing.T) {
serverAddrs := [...]string{tcpAddr, unixAddr}
for _, addr := range serverAddrs {
cl1, err := client.NewURIClient(addr)
cl1, err := client.NewURI(addr)
require.Nil(t, err)
fmt.Printf("=== testing server on %s using URI client", addr)
testWithHTTPClient(t, cl1)
cl2, err := client.NewJSONRPCClient(addr)
cl2, err := client.New(addr)
require.Nil(t, err)
fmt.Printf("=== testing server on %s using JSONRPC client", addr)
testWithHTTPClient(t, cl2)
cl3, err := client.NewWSClient(addr, websocketEndpoint)
cl3, err := client.NewWS(addr, websocketEndpoint)
require.Nil(t, err)
cl3.SetLogger(log.TestingLogger())
err = cl3.Start()
@@ -297,7 +297,7 @@ func TestServersAndClientsBasic(t *testing.T) {
}
func TestHexStringArg(t *testing.T) {
cl, err := client.NewURIClient(tcpAddr)
cl, err := client.NewURI(tcpAddr)
require.Nil(t, err)
// should NOT be handled as hex
val := "0xabc"
@@ -307,7 +307,7 @@ func TestHexStringArg(t *testing.T) {
}
func TestQuotedStringArg(t *testing.T) {
cl, err := client.NewURIClient(tcpAddr)
cl, err := client.NewURI(tcpAddr)
require.Nil(t, err)
// should NOT be unquoted
val := "\"abc\""
@@ -317,7 +317,7 @@ func TestQuotedStringArg(t *testing.T) {
}
func TestWSNewWSRPCFunc(t *testing.T) {
cl, err := client.NewWSClient(tcpAddr, websocketEndpoint)
cl, err := client.NewWS(tcpAddr, websocketEndpoint)
require.Nil(t, err)
cl.SetLogger(log.TestingLogger())
err = cl.Start()
@@ -343,7 +343,7 @@ func TestWSNewWSRPCFunc(t *testing.T) {
}
func TestWSHandlesArrayParams(t *testing.T) {
cl, err := client.NewWSClient(tcpAddr, websocketEndpoint)
cl, err := client.NewWS(tcpAddr, websocketEndpoint)
require.Nil(t, err)
cl.SetLogger(log.TestingLogger())
err = cl.Start()
@@ -369,7 +369,7 @@ func TestWSHandlesArrayParams(t *testing.T) {
// TestWSClientPingPong checks that a client & server exchange pings
// & pongs so connection stays alive.
func TestWSClientPingPong(t *testing.T) {
cl, err := client.NewWSClient(tcpAddr, websocketEndpoint)
cl, err := client.NewWS(tcpAddr, websocketEndpoint)
require.Nil(t, err)
cl.SetLogger(log.TestingLogger())
err = cl.Start()
@@ -1,4 +1,4 @@
package rpcserver
package server
import (
"bytes"
@@ -12,7 +12,7 @@ import (
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/log"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
///////////////////////////////////////////////////////////////////////////////
@@ -1,4 +1,4 @@
package rpcserver
package server
import (
"bytes"
@@ -15,7 +15,7 @@ import (
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/log"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
func testMux() *http.ServeMux {
@@ -1,5 +1,5 @@
// Commons for HTTP handling
package rpcserver
package server
import (
"bufio"
@@ -16,7 +16,7 @@ import (
"golang.org/x/net/netutil"
"github.com/tendermint/tendermint/libs/log"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
// Config is a RPC server configuration.
@@ -45,10 +45,12 @@ func DefaultConfig() *Config {
}
}
// StartHTTPServer takes a listener and starts an HTTP server with the given handler.
// It wraps handler with RecoverAndLogHandler.
// Serve creates a http.Server and calls Serve with the given listener. It
// wraps handler with RecoverAndLogHandler and a handler, which limits the max
// body size to config.MaxBodyBytes.
//
// NOTE: This function blocks - you may want to call it in a go-routine.
func StartHTTPServer(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error {
func Serve(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error {
logger.Info(fmt.Sprintf("Starting RPC HTTP server on %s", listener.Addr()))
s := &http.Server{
Handler: RecoverAndLogHandler(maxBytesHandler{h: handler, n: config.MaxBodyBytes}, logger),
@@ -61,10 +63,12 @@ func StartHTTPServer(listener net.Listener, handler http.Handler, logger log.Log
return err
}
// StartHTTPAndTLSServer takes a listener and starts an HTTPS server with the given handler.
// It wraps handler with RecoverAndLogHandler.
// Serve creates a http.Server and calls ServeTLS with the given listener,
// certFile and keyFile. It wraps handler with RecoverAndLogHandler and a
// handler, which limits the max body size to config.MaxBodyBytes.
//
// NOTE: This function blocks - you may want to call it in a go-routine.
func StartHTTPAndTLSServer(
func ServeTLS(
listener net.Listener,
handler http.Handler,
certFile, keyFile string,
@@ -141,7 +145,7 @@ func WriteRPCResponseArrayHTTP(w http.ResponseWriter, res []types.RPCResponse) {
func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Wrap the ResponseWriter to remember the status
rww := &ResponseWriterWrapper{-1, w}
rww := &responseWriterWrapper{-1, w}
begin := time.Now()
rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix()))
@@ -211,18 +215,18 @@ func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler
}
// Remember the status for logging
type ResponseWriterWrapper struct {
type responseWriterWrapper struct {
Status int
http.ResponseWriter
}
func (w *ResponseWriterWrapper) WriteHeader(status int) {
func (w *responseWriterWrapper) WriteHeader(status int) {
w.Status = status
w.ResponseWriter.WriteHeader(status)
}
// implements http.Hijacker
func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
func (w *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.ResponseWriter.(http.Hijacker).Hijack()
}
@@ -1,4 +1,4 @@
package rpcserver
package server
import (
"crypto/tls"
@@ -37,7 +37,7 @@ func TestMaxOpenConnections(t *testing.T) {
l, err := Listen("tcp://127.0.0.1:0", config)
require.NoError(t, err)
defer l.Close()
go StartHTTPServer(l, mux, log.TestingLogger(), config)
go Serve(l, mux, log.TestingLogger(), config)
// Make N GET calls to the server.
attempts := max * 2
@@ -67,7 +67,7 @@ func TestMaxOpenConnections(t *testing.T) {
}
}
func TestStartHTTPAndTLSServer(t *testing.T) {
func TestServeTLS(t *testing.T) {
ln, err := net.Listen("tcp", "localhost:0")
require.NoError(t, err)
defer ln.Close()
@@ -77,7 +77,7 @@ func TestStartHTTPAndTLSServer(t *testing.T) {
fmt.Fprint(w, "some body")
})
go StartHTTPAndTLSServer(ln, mux, "test.crt", "test.key", log.TestingLogger(), DefaultConfig())
go ServeTLS(ln, mux, "test.crt", "test.key", log.TestingLogger(), DefaultConfig())
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // nolint: gosec
@@ -1,22 +1,25 @@
package rpcserver
package server
import (
"encoding/hex"
"fmt"
"net/http"
"reflect"
"regexp"
"strings"
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/log"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
///////////////////////////////////////////////////////////////////////////////
// HTTP + URI handler
///////////////////////////////////////////////////////////////////////////////
var reInt = regexp.MustCompile(`^-?[0-9]+$`)
// convert from a function name to the http handler
func makeHTTPHandler(rpcFunc *RPCFunc, cdc *amino.Codec, logger log.Logger) func(http.ResponseWriter, *http.Request) {
// Always return -1 as there's no ID here.
@@ -74,7 +77,7 @@ func httpParamsToArgs(rpcFunc *RPCFunc, cdc *amino.Codec, r *http.Request) ([]re
values[i] = reflect.Zero(argType) // set default for that type
arg := GetParam(r, name)
arg := getParam(r, name)
// log.Notice("param to arg", "argType", argType, "name", name, "arg", arg)
if arg == "" {
@@ -129,7 +132,7 @@ func nonJSONStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.
// NOTE: rt.Kind() isn't a pointer.
func _nonJSONStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.Value, bool, error) {
isIntString := ReInt.Match([]byte(arg))
isIntString := reInt.Match([]byte(arg))
isQuotedString := strings.HasPrefix(arg, `"`) && strings.HasSuffix(arg, `"`)
isHexString := strings.HasPrefix(strings.ToLower(arg), "0x")
@@ -192,3 +195,11 @@ func _nonJSONStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect
return reflect.ValueOf(nil), false, nil
}
func getParam(r *http.Request, param string) string {
s := r.URL.Query().Get(param)
if s == "" {
s = r.FormValue(param)
}
return s
}
@@ -1,4 +1,4 @@
package rpcserver
package server
import (
"encoding/json"
@@ -11,7 +11,7 @@ import (
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/bytes"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
func TestParseJSONMap(t *testing.T) {
@@ -1,4 +1,4 @@
package rpcserver
package server
import (
"fmt"
@@ -1,4 +1,4 @@
package rpcserver
package server
import (
"context"
@@ -15,7 +15,7 @@ import (
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/service"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
///////////////////////////////////////////////////////////////////////////////
@@ -1,4 +1,4 @@
package rpcserver
package server
import (
"net/http"
@@ -11,7 +11,7 @@ import (
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/log"
types "github.com/tendermint/tendermint/rpc/lib/types"
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
func TestWebsocketManagerHandler(t *testing.T) {
@@ -9,8 +9,8 @@ import (
"github.com/tendermint/tendermint/libs/log"
tmos "github.com/tendermint/tendermint/libs/os"
rpcserver "github.com/tendermint/tendermint/rpc/lib/server"
rpctypes "github.com/tendermint/tendermint/rpc/lib/types"
rpcserver "github.com/tendermint/tendermint/rpc/jsonrpc/server"
rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
var routes = map[string]*rpcserver.RPCFunc{
@@ -41,5 +41,5 @@ func main() {
if err != nil {
tmos.Exit(err.Error())
}
rpcserver.StartHTTPServer(listener, mux, logger, config)
rpcserver.Serve(listener, mux, logger, config)
}
@@ -1,4 +1,4 @@
package rpctypes
package types
import (
"context"
@@ -1,4 +1,4 @@
package rpctypes
package types
import (
"encoding/json"
-90
View File
@@ -1,90 +0,0 @@
package rpcserver
import (
"encoding/hex"
"fmt"
"net/http"
"regexp"
"strconv"
)
var (
// Parts of regular expressions
atom = "[A-Z0-9!#$%&'*+\\-/=?^_`{|}~]+"
dotAtom = atom + `(?:\.` + atom + `)*`
domain = `[A-Z0-9.-]+\.[A-Z]{2,4}`
ReInt = regexp.MustCompile(`^-?[0-9]+$`)
ReHex = regexp.MustCompile(`^(?i)[a-f0-9]+$`)
ReEmail = regexp.MustCompile(`^(?i)(` + dotAtom + `)@(` + dotAtom + `)$`)
ReAddress = regexp.MustCompile(`^(?i)[a-z0-9]{25,34}$`)
ReHost = regexp.MustCompile(`^(?i)(` + domain + `)$`)
//RE_ID12 = regexp.MustCompile(`^[a-zA-Z0-9]{12}$`)
)
func GetParam(r *http.Request, param string) string {
s := r.URL.Query().Get(param)
if s == "" {
s = r.FormValue(param)
}
return s
}
func GetParamByteSlice(r *http.Request, param string) ([]byte, error) {
s := GetParam(r, param)
return hex.DecodeString(s)
}
func GetParamInt64(r *http.Request, param string) (int64, error) {
s := GetParam(r, param)
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, fmt.Errorf(param, err.Error())
}
return i, nil
}
func GetParamInt32(r *http.Request, param string) (int32, error) {
s := GetParam(r, param)
i, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return 0, fmt.Errorf(param, err.Error())
}
return int32(i), nil
}
func GetParamUint64(r *http.Request, param string) (uint64, error) {
s := GetParam(r, param)
i, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return 0, fmt.Errorf(param, err.Error())
}
return i, nil
}
func GetParamUint(r *http.Request, param string) (uint, error) {
s := GetParam(r, param)
i, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return 0, fmt.Errorf(param, err.Error())
}
return uint(i), nil
}
func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) {
s := GetParam(r, param)
if !re.MatchString(s) {
return "", fmt.Errorf(param, "did not match regular expression %v", re.String())
}
return s, nil
}
func GetParamFloat64(r *http.Request, param string) (float64, error) {
s := GetParam(r, param)
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, fmt.Errorf(param, err.Error())
}
return f, nil
}
+2 -2
View File
@@ -19,7 +19,7 @@ import (
"github.com/tendermint/tendermint/proxy"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
core_grpc "github.com/tendermint/tendermint/rpc/grpc"
rpcclient "github.com/tendermint/tendermint/rpc/lib/client"
rpcclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
)
// Options helps with specifying some parameters for our RPC testing for greater
@@ -37,7 +37,7 @@ var defaultOptions = Options{
func waitForRPC() {
laddr := GetConfig().RPC.ListenAddress
client, err := rpcclient.NewJSONRPCClient(laddr)
client, err := rpcclient.New(laddr)
if err != nil {
panic(err)
}