@@ -56,40 +56,30 @@ def __init__(self, rate: int, per: float, bucket: Bucket):
5656 self ._per = per
5757 self .bucket = bucket
5858
59- self ._window = time .time () + self ._per
60- self ._tokens = 0
61-
6259 self ._cache = {}
6360
64- def get_tokens (self , now = None ):
65- now = now or time .time ()
66- tokens = self ._tokens
67-
68- if now > self ._window + self ._per :
69- tokens = 0
70-
71- return tokens
72-
7361 def update_bucket (self , ctx ):
7462 now = time .time ()
7563
76- self ._tokens = self .get_tokens (now )
64+ bucket_keys = self ._bucket_keys (ctx )
65+ buckets = []
7766
78- if self . _tokens == 0 :
79- self . _window = now
67+ for bucket in bucket_keys :
68+ ( tokens , window ) = self . _cache [ bucket ]
8069
81- if self . _tokens == self ._rate :
82- retry = self ._per - (now - self . _window )
83- raise CommandOnCooldown (command = ctx .command , retry_after = retry )
70+ if tokens == self ._rate :
71+ retry = self ._per - (now - window )
72+ raise CommandOnCooldown (command = ctx .command , retry_after = retry )
8473
85- self . _tokens += 1
74+ tokens += 1
8675
87- if self ._tokens == self ._rate :
88- self ._window = now
76+ if tokens == self ._rate :
77+ window = now
78+
79+ self ._cache [bucket ] = (tokens , window )
8980
9081 def reset (self ):
91- self ._tokens = 0
92- self ._window = time .time ()
82+ self ._cache = {}
9383
9484 def _bucket_keys (self , ctx ):
9585 buckets = []
@@ -115,7 +105,7 @@ def _bucket_keys(self, ctx):
115105
116106 def _update_cache (self , now = None ):
117107 now = now or time .time ()
118- dead = [key for key , cooldown in self ._cache .items () if now > cooldown . _window + cooldown ._per ]
108+ dead = [key for key , cooldown in self ._cache .items () if now > cooldown [ 1 ] + self ._per ]
119109
120110 for bucket in dead :
121111 del self ._cache [bucket ]
@@ -129,10 +119,8 @@ def get_buckets(self, ctx):
129119 buckets = []
130120
131121 for index , bucket in enumerate (bucket_keys ):
122+ buckets .append (ctx .command ._cooldowns [index ])
132123 if bucket not in self ._cache :
133- buckets .append (ctx .command ._cooldowns [index ])
134- self ._cache [bucket ] = ctx .command ._cooldowns [index ]
135- else :
136- buckets .append (self ._cache [bucket ])
124+ self ._cache [bucket ] = (0 , now )
137125
138126 return buckets
0 commit comments