Skip to content

Commit

Permalink
fix: add cancel context to stop blockHeight fetcher (#123)
Browse files Browse the repository at this point in the history
* fix: add cancel context to stop blockHeight fetcher

* fix: check non-nil cancelFn on chainClient Close()
  • Loading branch information
vinhphuctadang authored Apr 27, 2023
1 parent 846dd47 commit 31c98b1
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions client/chain/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@ type chainClient struct {
msgC chan sdk.Msg
syncMux *sync.Mutex

cancelCtx context.Context
cancelFn func()

accNum uint64
accSeq uint64
gasWanted uint64
Expand Down Expand Up @@ -208,6 +211,7 @@ func NewChainClient(
}
}

cancelCtx, cancelFn := context.WithCancel(context.Background())
// build client
cc := &chainClient{
ctx: ctx,
Expand All @@ -224,6 +228,8 @@ func NewChainClient(
syncMux: new(sync.Mutex),
msgC: make(chan sdk.Msg, msgCommitBatchSizeLimit),
doneC: make(chan bool, 1),
cancelCtx: cancelCtx,
cancelFn: cancelFn,

sessionEnabled: stickySessionEnabled,

Expand Down Expand Up @@ -280,15 +286,23 @@ func (c *chainClient) syncNonce() {
}

func (c *chainClient) syncTimeoutHeight() {
t := time.NewTicker(defaultTimeoutHeightSyncInterval)
defer t.Stop()

for {
ctx := context.Background()
block, err := c.ctx.Client.Block(ctx, nil)
block, err := c.ctx.Client.Block(c.cancelCtx, nil)
if err != nil {
c.logger.WithError(err).Errorln("failed to get current block")
return
}
c.txFactory.WithTimeoutHeight(uint64(block.Block.Height) + defaultTimeoutHeight)
time.Sleep(defaultTimeoutHeightSyncInterval)

select {
case <-c.cancelCtx.Done():
return
case <-t.C:
continue
}
}
}

Expand Down Expand Up @@ -442,6 +456,10 @@ func (c *chainClient) Close() {
if atomic.CompareAndSwapInt64(&c.closed, 0, 1) {
close(c.msgC)
}

if c.cancelFn != nil {
c.cancelFn()
}
<-c.doneC
if c.conn != nil {
c.conn.Close()
Expand Down

0 comments on commit 31c98b1

Please sign in to comment.