Skip to content

Commit

Permalink
feat: add timeout when connect to rpc (#115)
Browse files Browse the repository at this point in the history
* feat: add timeout when connect to rpc

* chore: fix golangci-lint
  • Loading branch information
lehainam-dev authored May 9, 2024
1 parent edb6d5c commit a4837d5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
6 changes: 4 additions & 2 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ func NewListener(c *cli.Context) (*listener.Listener, error) {
}
wsRPC := c.String(wsRPCFlag.Name)
l.Infow("Connect to node websocket rpc", "rpc", wsRPC)
wsEVMClient, err := evmclient.DialContext(context.Background(), wsRPC, httpClient)
wsEVMClient, err := evmclient.DialContextWithTimeout(
context.Background(), wsRPC, httpClient, defaultRequestTimeout)
if err != nil {
l.Errorw("Fail to connect to node", "rpc", wsRPC, "error", err)

Expand All @@ -65,7 +66,8 @@ func NewListener(c *cli.Context) (*listener.Listener, error) {

httpRPC := c.String(httpRPCFlag.Name)
l.Infow("Connect to node http rpc", "rpc", httpRPC)
httpEVMClient, err := evmclient.DialContext(context.Background(), httpRPC, httpClient)
httpEVMClient, err := evmclient.DialContextWithTimeout(
context.Background(), httpRPC, httpClient, defaultRequestTimeout)
if err != nil {
l.Errorw("Fail to connect to node", "rpc", httpRPC, "error", err)

Expand Down
32 changes: 32 additions & 0 deletions pkg/evmclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package evmclient

import (
"context"
"errors"
"math/big"
"net/http"
"time"

"github.com/KyberNetwork/evmlistener/pkg/common"
"github.com/KyberNetwork/evmlistener/pkg/evmclient/ftmclient"
Expand Down Expand Up @@ -99,6 +101,36 @@ func DialContext(ctx context.Context, rawurl string, httpClient *http.Client) (*
return client, nil
}

func DialContextWithTimeout(
ctx context.Context,
rawurl string,
httpClient *http.Client,
timeout time.Duration,
) (*Client, error) {
type dialContextResponse struct {
client *Client
err error
}

ch := make(chan dialContextResponse, 1)
go func() {
client, err := DialContext(ctx, rawurl, httpClient)
ch <- dialContextResponse{
client: client,
err: err,
}
}()

select {
case res := <-ch:
return res.client, res.err
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(timeout):
return nil, errors.New("timeout when dial RPC")
}
}

func (c *Client) ChainID(ctx context.Context) (*big.Int, error) {
return new(big.Int).SetUint64(c.chainID), nil
}
Expand Down

0 comments on commit a4837d5

Please sign in to comment.