From a85e06a19bbb62ef0de7a7d3801bbb7d8b4fb4a7 Mon Sep 17 00:00:00 2001 From: C <0xicl33n@gmail.com> Date: Sat, 11 Oct 2025 13:55:15 -0700 Subject: [PATCH] global throttler implementation --- src/throttler.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/throttler.py diff --git a/src/throttler.py b/src/throttler.py new file mode 100644 index 0000000..219e740 --- /dev/null +++ b/src/throttler.py @@ -0,0 +1,33 @@ +import asyncio +from asyncio_throttle import Throttler as AsyncThrottler + +class GlobalThrottler: + _instance = None + _lock = asyncio.Lock() + + def __init__(self, rate_limit: int = 500, period: int = 60) -> None: + if not hasattr(self, '_initialized'): + self.rate_limit = rate_limit + self.period = period + self.throttler = AsyncThrottler(rate_limit=self.rate_limit, period=self.period) + self._initialized = True + + @classmethod + async def get_instance(cls, rate_limit: int = 500, period: int = 60) -> 'GlobalThrottler': + async with cls._lock: + if not cls._instance: + cls._instance = cls(rate_limit, period) + return cls._instance + + async def acquire(self): + await self.throttler.acquire() + + def release(self): + self.throttler.release() + + async def __aenter__(self): + await self.acquire() + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + self.release()