2021-02-02 07:45:02 +00:00
|
|
|
package rpcbroadcaster
|
2020-10-08 11:50:10 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/nspcc-dev/neo-go/pkg/rpc/client"
|
|
|
|
"github.com/nspcc-dev/neo-go/pkg/rpc/request"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
2021-02-02 07:45:02 +00:00
|
|
|
// RPCClient represent rpc client for a single node.
|
|
|
|
type RPCClient struct {
|
2020-10-08 11:50:10 +00:00
|
|
|
client *client.Client
|
|
|
|
addr string
|
|
|
|
close chan struct{}
|
|
|
|
responses chan request.RawParams
|
|
|
|
log *zap.Logger
|
|
|
|
sendTimeout time.Duration
|
2021-02-02 07:45:02 +00:00
|
|
|
method SendMethod
|
2020-10-08 11:50:10 +00:00
|
|
|
}
|
|
|
|
|
2021-02-02 07:45:02 +00:00
|
|
|
// SendMethod represents rpc method for sending data to other nodes.
|
|
|
|
type SendMethod func(*client.Client, request.RawParams) error
|
|
|
|
|
|
|
|
// NewRPCClient returns new rpc client for provided address and method.
|
|
|
|
func (r *RPCBroadcaster) NewRPCClient(addr string, method SendMethod, timeout time.Duration, ch chan request.RawParams) *RPCClient {
|
|
|
|
return &RPCClient{
|
2020-10-08 11:50:10 +00:00
|
|
|
addr: addr,
|
|
|
|
close: r.close,
|
|
|
|
responses: ch,
|
2021-02-02 07:45:02 +00:00
|
|
|
log: r.Log.With(zap.String("address", addr)),
|
2020-10-08 11:50:10 +00:00
|
|
|
sendTimeout: timeout,
|
2021-02-02 07:45:02 +00:00
|
|
|
method: method,
|
2020-10-08 11:50:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-02 07:45:02 +00:00
|
|
|
func (c *RPCClient) run() {
|
2020-10-08 11:50:10 +00:00
|
|
|
// We ignore error as not every node can be available on startup.
|
2021-04-02 08:12:50 +00:00
|
|
|
c.client, _ = client.New(context.Background(), c.addr, client.Options{
|
2020-10-08 11:50:10 +00:00
|
|
|
DialTimeout: c.sendTimeout,
|
|
|
|
RequestTimeout: c.sendTimeout,
|
|
|
|
})
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-c.close:
|
|
|
|
return
|
|
|
|
case ps := <-c.responses:
|
|
|
|
if c.client == nil {
|
|
|
|
var err error
|
2021-04-02 08:12:50 +00:00
|
|
|
c.client, err = client.New(context.Background(), c.addr, client.Options{
|
2020-10-08 11:50:10 +00:00
|
|
|
DialTimeout: c.sendTimeout,
|
|
|
|
RequestTimeout: c.sendTimeout,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
2021-02-02 07:45:02 +00:00
|
|
|
err := c.method(c.client, ps)
|
2020-10-08 11:50:10 +00:00
|
|
|
if err != nil {
|
|
|
|
c.log.Error("error while submitting oracle response", zap.Error(err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|