MCPcopy
hub / github.com/HisMax/RedInk / ImageRateLimiter

Class ImageRateLimiter

backend/services/image_rate_limiter.py:7–29  ·  view source on GitHub ↗

限制同一进程内图片上游请求的并发数和启动间隔。

Source from the content-addressed store, hash-verified

5
6
7class ImageRateLimiter:
8 """限制同一进程内图片上游请求的并发数和启动间隔。"""
9
10 def __init__(self, max_concurrent: int = 1, interval_seconds: float = 3.0):
11 self.max_concurrent = max(1, int(max_concurrent or 1))
12 self.interval_seconds = max(0.0, float(interval_seconds or 0))
13 self._semaphore = threading.Semaphore(self.max_concurrent)
14 self._lock = threading.Lock()
15 self._last_start_at = 0.0
16
17 @contextmanager
18 def acquire(self):
19 self._semaphore.acquire()
20 try:
21 with self._lock:
22 now = time.monotonic()
23 wait_for = self._last_start_at + self.interval_seconds - now
24 if wait_for > 0:
25 time.sleep(wait_for)
26 self._last_start_at = time.monotonic()
27 yield
28 finally:
29 self._semaphore.release()

Calls

no outgoing calls