Skip to content

Commit

Permalink
save some calls to time by only updating _tokens when needed
Browse files Browse the repository at this point in the history
The old behaviour would increase _tokens on every call to drain; now we
will do it only if there are not enough to service the request. As a
side-effect, we now have .peek(), which is cheap, non-blocking and
non-destructive.
  • Loading branch information
bucko909 committed Aug 21, 2024
1 parent 52b40b2 commit 13a820a
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions lib/carbon/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ def drain(self, cost, blocking=False):
'''Given a number of tokens (or fractions) drain will return True and
drain the number of tokens from the bucket if the capacity allows,
otherwise we return false and leave the contents of the bucket.'''
if cost <= self.tokens:
if self.peek(cost):
self._tokens -= cost
return True

Expand All @@ -310,16 +310,16 @@ def setCapacityAndFillRate(self, new_capacity, new_fill_rate):
self.fill_rate = float(new_fill_rate)
self._tokens = delta + self._tokens

@property
def tokens(self):
'''The tokens property will return the current number of tokens in the
bucket.'''
if self._tokens < self.capacity:
def peek(self, cost):
'''Return true if the bucket can drain cost without blocking.'''
if self._tokens >= cost:
return True
else:
now = time()
delta = self.fill_rate * (now - self.timestamp)
self._tokens = min(self.capacity, self._tokens + delta)
self.timestamp = now
return self._tokens
return self._tokens >= cost


class PluginRegistrar(type):
Expand Down

0 comments on commit 13a820a

Please sign in to comment.