From 8167b0f4d91fbf6a5804eb05d4b61372fdaae660 Mon Sep 17 00:00:00 2001 From: 0x6e616d Date: Thu, 29 Aug 2024 11:35:43 +0700 Subject: [PATCH] feat: add timeout when connecting the RPC and set threshold when retrying to connect --- internal/pkg/bcclient/client.go | 5 ++++- internal/pkg/listener/service.go | 11 +++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/internal/pkg/bcclient/client.go b/internal/pkg/bcclient/client.go index 23a5c49..439ff90 100644 --- a/internal/pkg/bcclient/client.go +++ b/internal/pkg/bcclient/client.go @@ -51,7 +51,10 @@ func New(ctx context.Context, wsURL, rpcURL string) (*Client, error) { } func initEthClient(ctx context.Context, url string, httpClient *http.Client) (*ethclient.Client, error) { - rpcClient, err := rpc.DialOptions(ctx, url, rpc.WithHTTPClient(httpClient)) + ctxTimeout, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + rpcClient, err := rpc.DialOptions(ctxTimeout, url, rpc.WithHTTPClient(httpClient)) if err != nil { return nil, err } diff --git a/internal/pkg/listener/service.go b/internal/pkg/listener/service.go index 58a18a5..55a3b49 100644 --- a/internal/pkg/listener/service.go +++ b/internal/pkg/listener/service.go @@ -23,7 +23,8 @@ var ( ) const ( - MaxBatchBlocksSize = 10 + MaxBatchBlocksSize = 10 + defaultRetryThreshold = 5 ) type RequestSubscriber interface { @@ -140,10 +141,16 @@ func (s *EventService) Start(ctx context.Context) error { return err } + retried := uint64(0) s.sub = event.ResubscribeErr(5*time.Second, func(ctx context.Context, err error) (event.Subscription, error) { if err != nil { + retried++ s.l.Errorw("Failed to re-subscribe the event", "err", err) - time.Sleep(1 * time.Second) + + if retried >= defaultRetryThreshold { + s.l.Fatalw("Can't connect subscription", "err", err) + } + time.Sleep(5 * time.Second) } return s.subscribeNewHead(ctx)