-
Notifications
You must be signed in to change notification settings - Fork 108
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
81 additions
and
51 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package beefy | ||
|
||
import ( | ||
"context" | ||
"sync/atomic" | ||
"time" | ||
) | ||
|
||
type TokenBucket struct { | ||
tokens atomic.Uint64 | ||
maxTokens uint64 | ||
refillAmount uint64 | ||
refillPeriod time.Duration | ||
} | ||
|
||
func NewTokenBucket(ctx context.Context, maxTokens, refillAmount uint64, refillPeriod time.Duration) *TokenBucket { | ||
tb := &TokenBucket{ | ||
maxTokens: maxTokens, | ||
refillAmount: refillAmount, | ||
refillPeriod: refillPeriod, | ||
} | ||
tb.tokens.Store(maxTokens) | ||
go tb.refiller(ctx) | ||
return tb | ||
} | ||
|
||
func (tb *TokenBucket) refiller(ctx context.Context) { | ||
ticker := time.NewTicker(tb.refillPeriod) | ||
defer ticker.Stop() | ||
|
||
for { | ||
select { | ||
case <-ctx.Done(): | ||
return | ||
case <-ticker.C: | ||
currentTokens := tb.tokens.Load() | ||
newTokens := currentTokens + tb.refillAmount | ||
if newTokens > tb.maxTokens { | ||
newTokens = tb.maxTokens | ||
} | ||
tb.tokens.Store(newTokens) | ||
} | ||
} | ||
} | ||
|
||
func (tb *TokenBucket) TryConsume(tokens uint64) bool { | ||
for { | ||
currentTokens := tb.tokens.Load() | ||
if currentTokens < tokens { | ||
return false | ||
} | ||
|
||
if tb.tokens.CompareAndSwap(currentTokens, currentTokens-tokens) { | ||
return true | ||
} | ||
} | ||
} |