Skip to content

Commit

Permalink
add semaphore to rate limit activations
Browse files Browse the repository at this point in the history
  • Loading branch information
Lazar955 committed Dec 6, 2024
1 parent b75c9cf commit ccd7955
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions btcstaking-tracker/stakingeventwatcher/stakingeventwatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"errors"
"fmt"
"golang.org/x/sync/semaphore"
"sync"
"sync/atomic"
"time"
Expand All @@ -26,8 +27,9 @@ import (
)

var (
fixedDelyTypeWithJitter = retry.DelayType(retry.CombineDelay(retry.FixedDelay, retry.RandomDelay))
retryForever = retry.Attempts(0)
fixedDelyTypeWithJitter = retry.DelayType(retry.CombineDelay(retry.FixedDelay, retry.RandomDelay))
retryForever = retry.Attempts(0)
maxConcurrentActivations = int64(1000)
)

func (sew *StakingEventWatcher) quitContext() (context.Context, func()) {
Expand Down Expand Up @@ -83,6 +85,7 @@ type StakingEventWatcher struct {
unbondingDelegationChan chan *newDelegation
unbondingRemovalChan chan *delegationInactive
currentBestBlockHeight atomic.Uint32
activationLimiter *semaphore.Weighted
}

func NewStakingEventWatcher(
Expand All @@ -106,6 +109,7 @@ func NewStakingEventWatcher(
inProgressTracker: NewTrackedDelegations(),
unbondingDelegationChan: make(chan *newDelegation),
unbondingRemovalChan: make(chan *delegationInactive),
activationLimiter: semaphore.NewWeighted(maxConcurrentActivations), // todo(lazar): this should be in config
}
}

Expand Down Expand Up @@ -613,6 +617,11 @@ func (sew *StakingEventWatcher) checkBtcForStakingTx() {
continue
}

if err := sew.activationLimiter.Acquire(context.Background(), 1); err != nil {
sew.logger.Warnf("error acquiring a activation semaphore %s", err)
continue
}

if _, err = sew.inProgressTracker.AddDelegation(
del.StakingTx,
del.StakingOutputIdx,
Expand All @@ -624,7 +633,10 @@ func (sew *StakingEventWatcher) checkBtcForStakingTx() {
continue
}

go sew.activateBtcDelegation(txHash, proof, details.Block.BlockHash(), params.ConfirmationTimeBlocks)
go func() {
defer sew.activationLimiter.Release(1)
sew.activateBtcDelegation(txHash, proof, details.Block.BlockHash(), params.ConfirmationTimeBlocks)
}()
}
}

Expand Down

0 comments on commit ccd7955

Please sign in to comment.