diff --git a/lib/tfw/components/directory_monitor.py b/lib/tfw/components/directory_monitor.py index 5db6d6f..5dae10e 100644 --- a/lib/tfw/components/directory_monitor.py +++ b/lib/tfw/components/directory_monitor.py @@ -1,33 +1,13 @@ -from time import time, sleep from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler -from functools import wraps from tfw.networking.event_handlers.server_connector import ServerUplinkConnector +from tfw.util import RateLimiter from tfw.config.logs import logging log = logging.getLogger(__name__) -class RateLimiter: - def __init__(self, rate_per_second): - self.min_interval = 1 / float(rate_per_second) - self.last_call = time() - - def __call__(self, fun): - @wraps(fun) - def wrapper(*args, **kwargs): - self._limit_rate() - fun(*args, **kwargs) - return wrapper - - def _limit_rate(self): #TODO: pls review me :3 - since_last_call = time() - self.last_call - to_next_call = self.min_interval - since_last_call - self.last_call = time() - if to_next_call > 0: - sleep(to_next_call) - class WebideReloadEventHandler(FileSystemEventHandler): def __init__(self): diff --git a/lib/tfw/util.py b/lib/tfw/util.py index 4194953..ab9ab83 100644 --- a/lib/tfw/util.py +++ b/lib/tfw/util.py @@ -1,6 +1,8 @@ import xmlrpc.client, zmq from contextlib import suppress from xmlrpc.client import Fault as SupervisorFault +from time import time, sleep +from functools import wraps from tfw.config import tfwenv @@ -31,3 +33,23 @@ class SupervisorMixin: class ZMQConnectorBase: def __init__(self, zmq_context=None): self._zmq_context = zmq_context or zmq.Context.instance() + + +class RateLimiter: + def __init__(self, rate_per_second): + self.min_interval = 1 / float(rate_per_second) + self.last_call = time() + + def __call__(self, fun): + @wraps(fun) + def wrapper(*args, **kwargs): + self._limit_rate() + fun(*args, **kwargs) + return wrapper + + def _limit_rate(self): #TODO: pls review me :3 + since_last_call = time() - self.last_call + to_next_call = self.min_interval - since_last_call + self.last_call = time() + if to_next_call > 0: + sleep(to_next_call) \ No newline at end of file