github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/libkb/ratelimit.go (about) 1 // Copyright 2015 Keybase, Inc. All rights reserved. Use of 2 // this source code is governed by the included BSD license. 3 4 package libkb 5 6 import ( 7 "sync" 8 "time" 9 ) 10 11 type RateLimitCategory string 12 13 const ( 14 CheckTrackingRateLimit RateLimitCategory = "CheckTrackingRateLimit" 15 TestEventRateLimit RateLimitCategory = "TestEventRateLimit" 16 ) 17 18 type RateLimits struct { 19 Contextified 20 sync.Mutex 21 lastActionTimes map[RateLimitCategory]time.Time 22 } 23 24 func NewRateLimits(g *GlobalContext) *RateLimits { 25 return &RateLimits{ 26 lastActionTimes: make(map[RateLimitCategory]time.Time), 27 Contextified: NewContextified(g), 28 } 29 } 30 31 func (r *RateLimits) GetPermission(category RateLimitCategory, interval time.Duration) bool { 32 r.Lock() 33 defer r.Unlock() 34 now := time.Now() 35 last, exists := r.lastActionTimes[category] 36 if !exists { 37 r.G().Log.Debug("Rate limit %s checked for the first time.", category) 38 r.lastActionTimes[category] = now 39 return true 40 } 41 timeSince := now.Sub(last) 42 if timeSince >= interval { 43 r.G().Log.Debug("Rate limit %s passed.", category) 44 r.lastActionTimes[category] = now 45 return true 46 } 47 r.G().Log.Debug("Rate limit %s too recent.", category) 48 return false 49 }