Skip to content

Commit

Permalink
Bug fix: the sequel
Browse files Browse the repository at this point in the history
  • Loading branch information
yunginnanet committed Sep 28, 2021
1 parent 1b86097 commit 64db6c5
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
6 changes: 3 additions & 3 deletions models.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ type Identity interface {
}

type rated struct {
seen atomic.Value
locker *uint32
seen *atomic.Value
locker uint32
}

// Limiter implements an Enforcer to create an arbitrary ratelimiter.
Expand All @@ -42,7 +42,7 @@ type Limiter struct {
Debug bool

count atomic.Value
known map[interface{}]*rated
known map[interface{}]rated
}

// Policy defines the mechanics of our ratelimiter.
Expand Down
15 changes: 9 additions & 6 deletions ratelimiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ func newLimiter(policy Policy) *Limiter {
q := new(Limiter)
q.Ruleset = policy
q.Patrons = cache.New(time.Duration(q.Ruleset.Window)*time.Second, 5*time.Second)
q.known = make(map[interface{}]*rated)
q.known = make(map[interface{}]rated)

return q
}

Expand All @@ -68,11 +69,11 @@ func (q *Limiter) DebugChannel() chan string {
return debugChannel
}

func (s *rated) inc() {
for !atomic.CompareAndSwapUint32(s.locker, stateUnlocked, stateLocked) {
func (s rated) inc() {
for !atomic.CompareAndSwapUint32(&s.locker, stateUnlocked, stateLocked) {
time.Sleep(10 * time.Millisecond)
}
defer atomic.StoreUint32(s.locker, stateUnlocked)
defer atomic.StoreUint32(&s.locker, stateUnlocked)

if s.seen.Load() == nil {
s.seen.Store(1)
Expand All @@ -83,8 +84,10 @@ func (s *rated) inc() {

func (q *Limiter) strictLogic(src string, count int) {
if _, ok := q.known[src]; !ok {
atomic.StoreUint32(q.known[src].locker, stateUnlocked)
q.known[src]=&rated{seen: atomic.Value{}}
q.known[src]=rated{
seen: &atomic.Value{},
locker: stateUnlocked,
}
}
q.known[src].inc()
extwindow := q.Ruleset.Window + q.known[src].seen.Load().(int)
Expand Down

0 comments on commit 64db6c5

Please sign in to comment.