mirror of
https://github.com/fluencelabs/tendermint
synced 2025-06-26 03:01:42 +00:00
rpc: add support for batched requests/responses (#3534)
Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
This commit is contained in:
committed by
Anton Kaliaev
parent
621c0e629d
commit
90465f727f
126
rpc/client/examples_test.go
Normal file
126
rpc/client/examples_test.go
Normal file
@ -0,0 +1,126 @@
|
||||
package client_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"github.com/tendermint/tendermint/abci/example/kvstore"
|
||||
"github.com/tendermint/tendermint/rpc/client"
|
||||
ctypes "github.com/tendermint/tendermint/rpc/core/types"
|
||||
rpctest "github.com/tendermint/tendermint/rpc/test"
|
||||
)
|
||||
|
||||
func ExampleHTTP_simple() {
|
||||
// Start a tendermint node (and kvstore) in the background to test against
|
||||
app := kvstore.NewKVStoreApplication()
|
||||
node := rpctest.StartTendermint(app, rpctest.SuppressStdout, rpctest.RecreateConfig)
|
||||
defer rpctest.StopTendermint(node)
|
||||
|
||||
// Create our RPC client
|
||||
rpcAddr := rpctest.GetConfig().RPC.ListenAddress
|
||||
c := client.NewHTTP(rpcAddr, "/websocket")
|
||||
|
||||
// Create a transaction
|
||||
k := []byte("name")
|
||||
v := []byte("satoshi")
|
||||
tx := append(k, append([]byte("="), v...)...)
|
||||
|
||||
// Broadcast the transaction and wait for it to commit (rather use
|
||||
// c.BroadcastTxSync though in production)
|
||||
bres, err := c.BroadcastTxCommit(tx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if bres.CheckTx.IsErr() || bres.DeliverTx.IsErr() {
|
||||
panic("BroadcastTxCommit transaction failed")
|
||||
}
|
||||
|
||||
// Now try to fetch the value for the key
|
||||
qres, err := c.ABCIQuery("/key", k)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if qres.Response.IsErr() {
|
||||
panic("ABCIQuery failed")
|
||||
}
|
||||
if !bytes.Equal(qres.Response.Key, k) {
|
||||
panic("returned key does not match queried key")
|
||||
}
|
||||
if !bytes.Equal(qres.Response.Value, v) {
|
||||
panic("returned value does not match sent value")
|
||||
}
|
||||
|
||||
fmt.Println("Sent tx :", string(tx))
|
||||
fmt.Println("Queried for :", string(qres.Response.Key))
|
||||
fmt.Println("Got value :", string(qres.Response.Value))
|
||||
|
||||
// Output:
|
||||
// Sent tx : name=satoshi
|
||||
// Queried for : name
|
||||
// Got value : satoshi
|
||||
}
|
||||
|
||||
func ExampleHTTP_batching() {
|
||||
// Start a tendermint node (and kvstore) in the background to test against
|
||||
app := kvstore.NewKVStoreApplication()
|
||||
node := rpctest.StartTendermint(app, rpctest.SuppressStdout, rpctest.RecreateConfig)
|
||||
defer rpctest.StopTendermint(node)
|
||||
|
||||
// Create our RPC client
|
||||
rpcAddr := rpctest.GetConfig().RPC.ListenAddress
|
||||
c := client.NewHTTP(rpcAddr, "/websocket")
|
||||
|
||||
// Create our two transactions
|
||||
k1 := []byte("firstName")
|
||||
v1 := []byte("satoshi")
|
||||
tx1 := append(k1, append([]byte("="), v1...)...)
|
||||
|
||||
k2 := []byte("lastName")
|
||||
v2 := []byte("nakamoto")
|
||||
tx2 := append(k2, append([]byte("="), v2...)...)
|
||||
|
||||
txs := [][]byte{tx1, tx2}
|
||||
|
||||
// Create a new batch
|
||||
batch := c.NewBatch()
|
||||
|
||||
// Queue up our transactions
|
||||
for _, tx := range txs {
|
||||
if _, err := batch.BroadcastTxCommit(tx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Send the batch of 2 transactions
|
||||
if _, err := batch.Send(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Now let's query for the original results as a batch
|
||||
keys := [][]byte{k1, k2}
|
||||
for _, key := range keys {
|
||||
if _, err := batch.ABCIQuery("/key", key); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Send the 2 queries and keep the results
|
||||
results, err := batch.Send()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Each result in the returned list is the deserialized result of each
|
||||
// respective ABCIQuery response
|
||||
for _, result := range results {
|
||||
qr, ok := result.(*ctypes.ResultABCIQuery)
|
||||
if !ok {
|
||||
panic("invalid result type from ABCIQuery request")
|
||||
}
|
||||
fmt.Println(string(qr.Response.Key), "=", string(qr.Response.Value))
|
||||
}
|
||||
|
||||
// Output:
|
||||
// firstName = satoshi
|
||||
// lastName = nakamoto
|
||||
}
|
@ -15,7 +15,7 @@ type Waiter func(delta int64) (abort error)
|
||||
// but you can plug in another one
|
||||
func DefaultWaitStrategy(delta int64) (abort error) {
|
||||
if delta > 10 {
|
||||
return errors.Errorf("Waiting for %d blocks... aborting", delta)
|
||||
return errors.Errorf("waiting for %d blocks... aborting", delta)
|
||||
} else if delta > 0 {
|
||||
// estimate of wait time....
|
||||
// wait half a second for the next block (in progress)
|
||||
|
@ -18,27 +18,72 @@ import (
|
||||
)
|
||||
|
||||
/*
|
||||
HTTP is a Client implementation that communicates with a tendermint node over
|
||||
json rpc and websockets.
|
||||
HTTP is a Client implementation that communicates with a Tendermint node over
|
||||
JSON RPC and WebSockets.
|
||||
|
||||
This is the main implementation you probably want to use in production code.
|
||||
There are other implementations when calling the tendermint node in-process
|
||||
There are other implementations when calling the Tendermint node in-process
|
||||
(Local), or when you want to mock out the server for test code (mock).
|
||||
|
||||
You can subscribe for any event published by Tendermint using Subscribe method.
|
||||
Note delivery is best-effort. If you don't read events fast enough or network
|
||||
is slow, Tendermint might cancel the subscription. The client will attempt to
|
||||
Note delivery is best-effort. If you don't read events fast enough or network is
|
||||
slow, Tendermint might cancel the subscription. The client will attempt to
|
||||
resubscribe (you don't need to do anything). It will keep trying every second
|
||||
indefinitely until successful.
|
||||
|
||||
Request batching is available for JSON RPC requests over HTTP, which conforms to
|
||||
the JSON RPC specification (https://www.jsonrpc.org/specification#batch). See
|
||||
the example for more details.
|
||||
*/
|
||||
type HTTP struct {
|
||||
remote string
|
||||
rpc *rpcclient.JSONRPCClient
|
||||
|
||||
*baseRPCClient
|
||||
*WSEvents
|
||||
}
|
||||
|
||||
// NewHTTP takes a remote endpoint in the form tcp://<host>:<port>
|
||||
// and the websocket path (which always seems to be "/websocket")
|
||||
// BatchHTTP provides the same interface as `HTTP`, but allows for batching of
|
||||
// requests (as per https://www.jsonrpc.org/specification#batch). Do not
|
||||
// instantiate directly - rather use the HTTP.NewBatch() method to create an
|
||||
// instance of this struct.
|
||||
//
|
||||
// Batching of HTTP requests is thread-safe in the sense that multiple
|
||||
// goroutines can each create their own batches and send them using the same
|
||||
// HTTP client. Multiple goroutines could also enqueue transactions in a single
|
||||
// batch, but ordering of transactions in the batch cannot be guaranteed in such
|
||||
// an example.
|
||||
type BatchHTTP struct {
|
||||
rpcBatch *rpcclient.JSONRPCRequestBatch
|
||||
*baseRPCClient
|
||||
}
|
||||
|
||||
// rpcClient is an internal interface to which our RPC clients (batch and
|
||||
// non-batch) must conform. Acts as an additional code-level sanity check to
|
||||
// make sure the implementations stay coherent.
|
||||
type rpcClient interface {
|
||||
ABCIClient
|
||||
HistoryClient
|
||||
NetworkClient
|
||||
SignClient
|
||||
StatusClient
|
||||
}
|
||||
|
||||
// baseRPCClient implements the basic RPC method logic without the actual
|
||||
// underlying RPC call functionality, which is provided by `caller`.
|
||||
type baseRPCClient struct {
|
||||
caller rpcclient.JSONRPCCaller
|
||||
}
|
||||
|
||||
var _ rpcClient = (*HTTP)(nil)
|
||||
var _ rpcClient = (*BatchHTTP)(nil)
|
||||
var _ rpcClient = (*baseRPCClient)(nil)
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// HTTP
|
||||
|
||||
// NewHTTP takes a remote endpoint in the form <protocol>://<host>:<port> and
|
||||
// the websocket path (which always seems to be "/websocket")
|
||||
func NewHTTP(remote, wsEndpoint string) *HTTP {
|
||||
rc := rpcclient.NewJSONRPCClient(remote)
|
||||
cdc := rc.Codec()
|
||||
@ -46,39 +91,76 @@ func NewHTTP(remote, wsEndpoint string) *HTTP {
|
||||
rc.SetCodec(cdc)
|
||||
|
||||
return &HTTP{
|
||||
rpc: rc,
|
||||
remote: remote,
|
||||
WSEvents: newWSEvents(cdc, remote, wsEndpoint),
|
||||
rpc: rc,
|
||||
remote: remote,
|
||||
baseRPCClient: &baseRPCClient{caller: rc},
|
||||
WSEvents: newWSEvents(cdc, remote, wsEndpoint),
|
||||
}
|
||||
}
|
||||
|
||||
var _ Client = (*HTTP)(nil)
|
||||
|
||||
func (c *HTTP) Status() (*ctypes.ResultStatus, error) {
|
||||
// NewBatch creates a new batch client for this HTTP client.
|
||||
func (c *HTTP) NewBatch() *BatchHTTP {
|
||||
rpcBatch := c.rpc.NewRequestBatch()
|
||||
return &BatchHTTP{
|
||||
rpcBatch: rpcBatch,
|
||||
baseRPCClient: &baseRPCClient{
|
||||
caller: rpcBatch,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// BatchHTTP
|
||||
|
||||
// Send is a convenience function for an HTTP batch that will trigger the
|
||||
// compilation of the batched requests and send them off using the client as a
|
||||
// single request. On success, this returns a list of the deserialized results
|
||||
// from each request in the sent batch.
|
||||
func (b *BatchHTTP) Send() ([]interface{}, error) {
|
||||
return b.rpcBatch.Send()
|
||||
}
|
||||
|
||||
// Clear will empty out this batch of requests and return the number of requests
|
||||
// that were cleared out.
|
||||
func (b *BatchHTTP) Clear() int {
|
||||
return b.rpcBatch.Clear()
|
||||
}
|
||||
|
||||
// Count returns the number of enqueued requests waiting to be sent.
|
||||
func (b *BatchHTTP) Count() int {
|
||||
return b.rpcBatch.Count()
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// baseRPCClient
|
||||
|
||||
func (c *baseRPCClient) Status() (*ctypes.ResultStatus, error) {
|
||||
result := new(ctypes.ResultStatus)
|
||||
_, err := c.rpc.Call("status", map[string]interface{}{}, result)
|
||||
_, err := c.caller.Call("status", map[string]interface{}{}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Status")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) ABCIInfo() (*ctypes.ResultABCIInfo, error) {
|
||||
func (c *baseRPCClient) ABCIInfo() (*ctypes.ResultABCIInfo, error) {
|
||||
result := new(ctypes.ResultABCIInfo)
|
||||
_, err := c.rpc.Call("abci_info", map[string]interface{}{}, result)
|
||||
_, err := c.caller.Call("abci_info", map[string]interface{}{}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "ABCIInfo")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) ABCIQuery(path string, data cmn.HexBytes) (*ctypes.ResultABCIQuery, error) {
|
||||
func (c *baseRPCClient) ABCIQuery(path string, data cmn.HexBytes) (*ctypes.ResultABCIQuery, error) {
|
||||
return c.ABCIQueryWithOptions(path, data, DefaultABCIQueryOptions)
|
||||
}
|
||||
|
||||
func (c *HTTP) ABCIQueryWithOptions(path string, data cmn.HexBytes, opts ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) {
|
||||
func (c *baseRPCClient) ABCIQueryWithOptions(path string, data cmn.HexBytes, opts ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) {
|
||||
result := new(ctypes.ResultABCIQuery)
|
||||
_, err := c.rpc.Call("abci_query",
|
||||
_, err := c.caller.Call("abci_query",
|
||||
map[string]interface{}{"path": path, "data": data, "height": opts.Height, "prove": opts.Prove},
|
||||
result)
|
||||
if err != nil {
|
||||
@ -87,89 +169,89 @@ func (c *HTTP) ABCIQueryWithOptions(path string, data cmn.HexBytes, opts ABCIQue
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) {
|
||||
func (c *baseRPCClient) BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) {
|
||||
result := new(ctypes.ResultBroadcastTxCommit)
|
||||
_, err := c.rpc.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, result)
|
||||
_, err := c.caller.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "broadcast_tx_commit")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) BroadcastTxAsync(tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
|
||||
func (c *baseRPCClient) BroadcastTxAsync(tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
|
||||
return c.broadcastTX("broadcast_tx_async", tx)
|
||||
}
|
||||
|
||||
func (c *HTTP) BroadcastTxSync(tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
|
||||
func (c *baseRPCClient) BroadcastTxSync(tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
|
||||
return c.broadcastTX("broadcast_tx_sync", tx)
|
||||
}
|
||||
|
||||
func (c *HTTP) broadcastTX(route string, tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
|
||||
func (c *baseRPCClient) broadcastTX(route string, tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
|
||||
result := new(ctypes.ResultBroadcastTx)
|
||||
_, err := c.rpc.Call(route, map[string]interface{}{"tx": tx}, result)
|
||||
_, err := c.caller.Call(route, map[string]interface{}{"tx": tx}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, route)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) UnconfirmedTxs(limit int) (*ctypes.ResultUnconfirmedTxs, error) {
|
||||
func (c *baseRPCClient) UnconfirmedTxs(limit int) (*ctypes.ResultUnconfirmedTxs, error) {
|
||||
result := new(ctypes.ResultUnconfirmedTxs)
|
||||
_, err := c.rpc.Call("unconfirmed_txs", map[string]interface{}{"limit": limit}, result)
|
||||
_, err := c.caller.Call("unconfirmed_txs", map[string]interface{}{"limit": limit}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "unconfirmed_txs")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) {
|
||||
func (c *baseRPCClient) NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) {
|
||||
result := new(ctypes.ResultUnconfirmedTxs)
|
||||
_, err := c.rpc.Call("num_unconfirmed_txs", map[string]interface{}{}, result)
|
||||
_, err := c.caller.Call("num_unconfirmed_txs", map[string]interface{}{}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "num_unconfirmed_txs")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) NetInfo() (*ctypes.ResultNetInfo, error) {
|
||||
func (c *baseRPCClient) NetInfo() (*ctypes.ResultNetInfo, error) {
|
||||
result := new(ctypes.ResultNetInfo)
|
||||
_, err := c.rpc.Call("net_info", map[string]interface{}{}, result)
|
||||
_, err := c.caller.Call("net_info", map[string]interface{}{}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "NetInfo")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) DumpConsensusState() (*ctypes.ResultDumpConsensusState, error) {
|
||||
func (c *baseRPCClient) DumpConsensusState() (*ctypes.ResultDumpConsensusState, error) {
|
||||
result := new(ctypes.ResultDumpConsensusState)
|
||||
_, err := c.rpc.Call("dump_consensus_state", map[string]interface{}{}, result)
|
||||
_, err := c.caller.Call("dump_consensus_state", map[string]interface{}{}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "DumpConsensusState")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) ConsensusState() (*ctypes.ResultConsensusState, error) {
|
||||
func (c *baseRPCClient) ConsensusState() (*ctypes.ResultConsensusState, error) {
|
||||
result := new(ctypes.ResultConsensusState)
|
||||
_, err := c.rpc.Call("consensus_state", map[string]interface{}{}, result)
|
||||
_, err := c.caller.Call("consensus_state", map[string]interface{}{}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "ConsensusState")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) Health() (*ctypes.ResultHealth, error) {
|
||||
func (c *baseRPCClient) Health() (*ctypes.ResultHealth, error) {
|
||||
result := new(ctypes.ResultHealth)
|
||||
_, err := c.rpc.Call("health", map[string]interface{}{}, result)
|
||||
_, err := c.caller.Call("health", map[string]interface{}{}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Health")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) BlockchainInfo(minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) {
|
||||
func (c *baseRPCClient) BlockchainInfo(minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) {
|
||||
result := new(ctypes.ResultBlockchainInfo)
|
||||
_, err := c.rpc.Call("blockchain",
|
||||
_, err := c.caller.Call("blockchain",
|
||||
map[string]interface{}{"minHeight": minHeight, "maxHeight": maxHeight},
|
||||
result)
|
||||
if err != nil {
|
||||
@ -178,56 +260,56 @@ func (c *HTTP) BlockchainInfo(minHeight, maxHeight int64) (*ctypes.ResultBlockch
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) Genesis() (*ctypes.ResultGenesis, error) {
|
||||
func (c *baseRPCClient) Genesis() (*ctypes.ResultGenesis, error) {
|
||||
result := new(ctypes.ResultGenesis)
|
||||
_, err := c.rpc.Call("genesis", map[string]interface{}{}, result)
|
||||
_, err := c.caller.Call("genesis", map[string]interface{}{}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Genesis")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) Block(height *int64) (*ctypes.ResultBlock, error) {
|
||||
func (c *baseRPCClient) Block(height *int64) (*ctypes.ResultBlock, error) {
|
||||
result := new(ctypes.ResultBlock)
|
||||
_, err := c.rpc.Call("block", map[string]interface{}{"height": height}, result)
|
||||
_, err := c.caller.Call("block", map[string]interface{}{"height": height}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Block")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) BlockResults(height *int64) (*ctypes.ResultBlockResults, error) {
|
||||
func (c *baseRPCClient) BlockResults(height *int64) (*ctypes.ResultBlockResults, error) {
|
||||
result := new(ctypes.ResultBlockResults)
|
||||
_, err := c.rpc.Call("block_results", map[string]interface{}{"height": height}, result)
|
||||
_, err := c.caller.Call("block_results", map[string]interface{}{"height": height}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Block Result")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) Commit(height *int64) (*ctypes.ResultCommit, error) {
|
||||
func (c *baseRPCClient) Commit(height *int64) (*ctypes.ResultCommit, error) {
|
||||
result := new(ctypes.ResultCommit)
|
||||
_, err := c.rpc.Call("commit", map[string]interface{}{"height": height}, result)
|
||||
_, err := c.caller.Call("commit", map[string]interface{}{"height": height}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Commit")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) {
|
||||
func (c *baseRPCClient) Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) {
|
||||
result := new(ctypes.ResultTx)
|
||||
params := map[string]interface{}{
|
||||
"hash": hash,
|
||||
"prove": prove,
|
||||
}
|
||||
_, err := c.rpc.Call("tx", params, result)
|
||||
_, err := c.caller.Call("tx", params, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Tx")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) TxSearch(query string, prove bool, page, perPage int) (*ctypes.ResultTxSearch, error) {
|
||||
func (c *baseRPCClient) TxSearch(query string, prove bool, page, perPage int) (*ctypes.ResultTxSearch, error) {
|
||||
result := new(ctypes.ResultTxSearch)
|
||||
params := map[string]interface{}{
|
||||
"query": query,
|
||||
@ -235,23 +317,24 @@ func (c *HTTP) TxSearch(query string, prove bool, page, perPage int) (*ctypes.Re
|
||||
"page": page,
|
||||
"per_page": perPage,
|
||||
}
|
||||
_, err := c.rpc.Call("tx_search", params, result)
|
||||
_, err := c.caller.Call("tx_search", params, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "TxSearch")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTP) Validators(height *int64) (*ctypes.ResultValidators, error) {
|
||||
func (c *baseRPCClient) Validators(height *int64) (*ctypes.ResultValidators, error) {
|
||||
result := new(ctypes.ResultValidators)
|
||||
_, err := c.rpc.Call("validators", map[string]interface{}{"height": height}, result)
|
||||
_, err := c.caller.Call("validators", map[string]interface{}{"height": height}, result)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Validators")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
/** websocket event stuff here... **/
|
||||
//-----------------------------------------------------------------------------
|
||||
// WSEvents
|
||||
|
||||
type WSEvents struct {
|
||||
cmn.BaseService
|
||||
|
@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@ -11,7 +12,9 @@ import (
|
||||
|
||||
abci "github.com/tendermint/tendermint/abci/types"
|
||||
|
||||
cmn "github.com/tendermint/tendermint/libs/common"
|
||||
"github.com/tendermint/tendermint/rpc/client"
|
||||
ctypes "github.com/tendermint/tendermint/rpc/core/types"
|
||||
rpctest "github.com/tendermint/tendermint/rpc/test"
|
||||
"github.com/tendermint/tendermint/types"
|
||||
)
|
||||
@ -441,3 +444,100 @@ func TestTxSearch(t *testing.T) {
|
||||
require.Len(t, result.Txs, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchedJSONRPCCalls(t *testing.T) {
|
||||
c := getHTTPClient()
|
||||
testBatchedJSONRPCCalls(t, c)
|
||||
}
|
||||
|
||||
func testBatchedJSONRPCCalls(t *testing.T, c *client.HTTP) {
|
||||
k1, v1, tx1 := MakeTxKV()
|
||||
k2, v2, tx2 := MakeTxKV()
|
||||
|
||||
batch := c.NewBatch()
|
||||
r1, err := batch.BroadcastTxCommit(tx1)
|
||||
require.NoError(t, err)
|
||||
r2, err := batch.BroadcastTxCommit(tx2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, batch.Count())
|
||||
bresults, err := batch.Send()
|
||||
require.NoError(t, err)
|
||||
require.Len(t, bresults, 2)
|
||||
require.Equal(t, 0, batch.Count())
|
||||
|
||||
bresult1, ok := bresults[0].(*ctypes.ResultBroadcastTxCommit)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, *bresult1, *r1)
|
||||
bresult2, ok := bresults[1].(*ctypes.ResultBroadcastTxCommit)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, *bresult2, *r2)
|
||||
apph := cmn.MaxInt64(bresult1.Height, bresult2.Height) + 1
|
||||
|
||||
client.WaitForHeight(c, apph, nil)
|
||||
|
||||
q1, err := batch.ABCIQuery("/key", k1)
|
||||
require.NoError(t, err)
|
||||
q2, err := batch.ABCIQuery("/key", k2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, batch.Count())
|
||||
qresults, err := batch.Send()
|
||||
require.NoError(t, err)
|
||||
require.Len(t, qresults, 2)
|
||||
require.Equal(t, 0, batch.Count())
|
||||
|
||||
qresult1, ok := qresults[0].(*ctypes.ResultABCIQuery)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, *qresult1, *q1)
|
||||
qresult2, ok := qresults[1].(*ctypes.ResultABCIQuery)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, *qresult2, *q2)
|
||||
|
||||
require.Equal(t, qresult1.Response.Key, k1)
|
||||
require.Equal(t, qresult2.Response.Key, k2)
|
||||
require.Equal(t, qresult1.Response.Value, v1)
|
||||
require.Equal(t, qresult2.Response.Value, v2)
|
||||
}
|
||||
|
||||
func TestBatchedJSONRPCCallsCancellation(t *testing.T) {
|
||||
c := getHTTPClient()
|
||||
_, _, tx1 := MakeTxKV()
|
||||
_, _, tx2 := MakeTxKV()
|
||||
|
||||
batch := c.NewBatch()
|
||||
_, err := batch.BroadcastTxCommit(tx1)
|
||||
require.NoError(t, err)
|
||||
_, err = batch.BroadcastTxCommit(tx2)
|
||||
require.NoError(t, err)
|
||||
// we should have 2 requests waiting
|
||||
require.Equal(t, 2, batch.Count())
|
||||
// we want to make sure we cleared 2 pending requests
|
||||
require.Equal(t, 2, batch.Clear())
|
||||
// now there should be no batched requests
|
||||
require.Equal(t, 0, batch.Count())
|
||||
}
|
||||
|
||||
func TestSendingEmptyJSONRPCRequestBatch(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) {
|
||||
c := getHTTPClient()
|
||||
batch := c.NewBatch()
|
||||
require.Zero(t, batch.Clear(), "clearing an empty batch of JSON RPC requests should result in a 0 result")
|
||||
}
|
||||
|
||||
func TestConcurrentJSONRPCBatching(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
c := getHTTPClient()
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
testBatchedJSONRPCCalls(t, c)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
Reference in New Issue
Block a user