neo-go/pkg/services/helpers/rpcbroadcaster/client.go

79 lines
1.8 KiB
Go
Raw Normal View History

package rpcbroadcaster
2020-10-08 11:50:10 +00:00
import (
"context"
"time"
"github.com/nspcc-dev/neo-go/pkg/rpc/client"
"go.uber.org/zap"
)
// RPCClient represent an 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{}
finished chan struct{}
responses chan []interface{}
2020-10-08 11:50:10 +00:00
log *zap.Logger
sendTimeout time.Duration
method SendMethod
2020-10-08 11:50:10 +00:00
}
// SendMethod represents an rpc method for sending data to other nodes.
type SendMethod func(*client.Client, []interface{}) error
// NewRPCClient returns a new rpc client for the provided address and method.
func (r *RPCBroadcaster) NewRPCClient(addr string, method SendMethod, timeout time.Duration, ch chan []interface{}) *RPCClient {
return &RPCClient{
2020-10-08 11:50:10 +00:00
addr: addr,
close: r.close,
finished: make(chan struct{}),
2020-10-08 11:50:10 +00:00
responses: ch,
log: r.Log.With(zap.String("address", addr)),
2020-10-08 11:50:10 +00:00
sendTimeout: timeout,
method: method,
2020-10-08 11:50:10 +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.
c.client, _ = client.New(context.Background(), c.addr, client.Options{
2020-10-08 11:50:10 +00:00
DialTimeout: c.sendTimeout,
RequestTimeout: c.sendTimeout,
})
run:
2020-10-08 11:50:10 +00:00
for {
select {
case <-c.close:
break run
2020-10-08 11:50:10 +00:00
case ps := <-c.responses:
if c.client == nil {
var err error
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 {
c.log.Error("failed to create client to submit oracle response", zap.Error(err))
2020-10-08 11:50:10 +00:00
continue
}
}
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))
}
}
}
c.client.Close()
drain:
for {
select {
case <-c.responses:
default:
break drain
}
}
close(c.finished)
2020-10-08 11:50:10 +00:00
}