Skip to content

Commit

Permalink
fix: use a monotonic clock in memory storage
Browse files Browse the repository at this point in the history
That should be more robust against system time update, e.g.
ntp or DST change.
  • Loading branch information
xrmx committed Apr 5, 2017
1 parent 61f4e63 commit c1d0227
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
url='https://github.com/falconry/token-bucket',
license='Apache 2.0',
packages=find_packages(exclude=['tests']),
install_requires=[],
install_requires=['monotonic'],
setup_requires=['pytest-runner'],
tests_require=['pytest'],
)
6 changes: 3 additions & 3 deletions token_bucket/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import time
import monotonic

from .storage_base import StorageBase

Expand Down Expand Up @@ -96,7 +96,7 @@ def replenish(self, key, rate, capacity):

tokens_in_bucket, last_replenished_at = self._buckets[key]

now = time.time()
now = monotonic.monotonic()

# NOTE(kgriffs): This will detect many, but not all,
# manifestations of the race condition. If a later
Expand All @@ -123,7 +123,7 @@ def replenish(self, key, rate, capacity):
]

except KeyError:
self._buckets[key] = [capacity, time.time()]
self._buckets[key] = [capacity, monotonic.monotonic()]

def consume(self, key, num_tokens):
"""Attempt to take one or more tokens from a bucket.
Expand Down

0 comments on commit c1d0227

Please sign in to comment.