2014-04-30 07:31:26 +08:00
|
|
|
package ratelimiter
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2016-12-22 11:02:41 +08:00
|
|
|
const (
|
|
|
|
GC_SIZE int = 100
|
|
|
|
GC_PERIOD time.Duration = 60 * time.Second
|
|
|
|
)
|
2014-04-30 07:31:26 +08:00
|
|
|
|
|
|
|
type Memory struct {
|
|
|
|
store map[string]LeakyBucket
|
|
|
|
lastGCCollected time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewMemory() *Memory {
|
|
|
|
m := new(Memory)
|
|
|
|
m.store = make(map[string]LeakyBucket)
|
|
|
|
m.lastGCCollected = time.Now()
|
|
|
|
return m
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Memory) GetBucketFor(key string) (*LeakyBucket, error) {
|
|
|
|
|
|
|
|
bucket, ok := m.store[key]
|
|
|
|
if !ok {
|
|
|
|
return nil, errors.New("miss")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &bucket, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Memory) SetBucketFor(key string, bucket LeakyBucket) error {
|
|
|
|
|
|
|
|
if len(m.store) > GC_SIZE {
|
|
|
|
m.GarbageCollect()
|
|
|
|
}
|
|
|
|
|
|
|
|
m.store[key] = bucket
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Memory) GarbageCollect() {
|
|
|
|
now := time.Now()
|
|
|
|
|
|
|
|
// rate limit GC to once per minute
|
2016-12-22 11:02:41 +08:00
|
|
|
if now.Unix() >= m.lastGCCollected.Add(GC_PERIOD).Unix() {
|
2014-04-30 07:31:26 +08:00
|
|
|
for key, bucket := range m.store {
|
|
|
|
// if the bucket is drained, then GC
|
2016-12-22 11:02:41 +08:00
|
|
|
if bucket.DrainedAt().Unix() < now.Unix() {
|
2014-04-30 07:31:26 +08:00
|
|
|
delete(m.store, key)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
m.lastGCCollected = now
|
|
|
|
}
|
|
|
|
}
|