From 73fca81641b1db6315fda89ff087485e47aece4f Mon Sep 17 00:00:00 2001 From: InfinityPacer <160988576+InfinityPacer@users.noreply.github.com> Date: Wed, 4 Sep 2024 20:00:53 +0800 Subject: [PATCH 1/5] feat(rate-limiter): add rate limiter --- app/schemas/exception.py | 19 +++++++- app/utils/common.py | 98 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 114 insertions(+), 3 deletions(-) diff --git a/app/schemas/exception.py b/app/schemas/exception.py index 63ef784ec..655104b74 100644 --- a/app/schemas/exception.py +++ b/app/schemas/exception.py @@ -6,9 +6,26 @@ class ImmediateException(Exception): pass -class APIRateLimitException(ImmediateException): +class LimitException(ImmediateException): + """ + 用于表示本地限流器或外部触发的限流异常的基类。 + 该异常类可用于本地限流逻辑或外部限流处理。 + """ + pass + + +class APIRateLimitException(LimitException): """ 用于表示API速率限制的异常类。 当API调用触发速率限制时,可以抛出此异常以立即终止操作并报告错误。 """ pass + + +class RateLimitExceededException(LimitException): + """ + 用于表示本地限流器触发的异常类。 + 当函数调用频率超过限流器的限制时,可以抛出此异常以停止当前操作并告知调用者限流情况。 + 这个异常通常用于本地限流逻辑(例如 RateLimiter),当系统检测到函数调用频率过高时,触发限流并抛出该异常。 + """ + pass diff --git a/app/utils/common.py b/app/utils/common.py index 4ba1aa7eb..5fb82e5c3 100644 --- a/app/utils/common.py +++ b/app/utils/common.py @@ -1,7 +1,10 @@ +import functools +import threading import time -from typing import Any +from typing import Any, Callable, Optional -from app.schemas import ImmediateException +from app.log import logger +from app.schemas import ImmediateException, APIRateLimitException, RateLimitExceededException def retry(ExceptionToCheck: Any, @@ -36,3 +39,94 @@ def retry(ExceptionToCheck: Any, return f_retry return deco_retry + + +class RateLimiter: + """ + 限流器类,用于处理调用的限流逻辑 + 通过增加等待时间逐步减少调用的频率,以避免触发限流 + """ + + def __init__(self, base_wait: int = 60, max_wait: int = 600, backoff_factor: int = 1): + """ + 初始化 RateLimiter 实例 + :param base_wait: 基础等待时间(秒),默认值为 60 秒(1 分钟) + :param max_wait: 最大等待时间(秒),默认值为 600 秒(10 分钟) + :param backoff_factor: 等待时间的递增倍数,默认值为 1 + """ + self.next_allowed_time = 0 + self.current_wait = base_wait + self.base_wait = base_wait + self.max_wait = max_wait + self.backoff_factor = backoff_factor + self.lock = threading.Lock() + + def can_call(self) -> bool: + """ + 检查是否可以进行下一次调用 + :return: 如果当前时间超过下一次允许调用的时间,返回 True;否则返回 False + """ + current_time = time.time() + with self.lock: + if current_time >= self.next_allowed_time: + return True + logger.warn(f"限流期间,跳过调用:将在 {self.next_allowed_time - current_time:.2f} 秒后允许继续调用") + return False + + def reset(self): + """ + 重置等待时间 + 当调用成功时调用此方法,重置当前等待时间为基础等待时间 + """ + with self.lock: + if self.next_allowed_time != 0 or self.current_wait > self.base_wait: + logger.info(f"调用成功,重置限流等待时长,并允许立即调用") + self.next_allowed_time = 0 + self.current_wait = self.base_wait + + def trigger_limit(self): + """ + 触发限流 + 当触发限流异常时调用此方法,增加下一次允许调用的时间并更新当前等待时间 + """ + current_time = time.time() + with self.lock: + self.next_allowed_time = current_time + self.current_wait + logger.warn(f"触发限流:将在 {self.current_wait} 秒后允许继续调用") + self.current_wait = min(self.current_wait * self.backoff_factor, self.max_wait) + + +def rate_limit_handler(base_wait: int = 60, max_wait: int = 600, backoff_factor: int = 1, + raise_on_limit: bool = True) -> Callable: + """ + 装饰器,用于处理限流逻辑 + :param base_wait: 基础等待时间(秒),默认值为 60 秒(1 分钟) + :param max_wait: 最大等待时间(秒),默认值为 600 秒(10 分钟) + :param backoff_factor: 等待时间的递增倍数,默认值为 1 + :param raise_on_limit: 是否在触发限流异常时抛出异常,默认为 True + :return: 装饰器函数 + """ + rate_limiter = RateLimiter(base_wait, max_wait, backoff_factor) + + def decorator(func: Callable) -> Callable: + @functools.wraps(func) + def wrapper(*args, **kwargs) -> Optional[Any]: + if not rate_limiter.can_call(): + if raise_on_limit: + raise RateLimitExceededException("调用因限流被跳过") + return None + + try: + result = func(*args, **kwargs) + rate_limiter.reset() # 调用成功,重置等待时间 + return result + except APIRateLimitException as e: + rate_limiter.trigger_limit() + logger.error(f"触发限流:{str(e)}") + if raise_on_limit: + raise e + return None + + return wrapper + + return decorator From eea6bd1ea3c4fdc29f92521c7b2ce52e6ecc2609 Mon Sep 17 00:00:00 2001 From: InfinityPacer <160988576+InfinityPacer@users.noreply.github.com> Date: Wed, 4 Sep 2024 20:10:11 +0800 Subject: [PATCH 2/5] feat(rate-limiter): add source context for enhanced logging --- app/utils/common.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/app/utils/common.py b/app/utils/common.py index 5fb82e5c3..837e51476 100644 --- a/app/utils/common.py +++ b/app/utils/common.py @@ -47,18 +47,20 @@ class RateLimiter: 通过增加等待时间逐步减少调用的频率,以避免触发限流 """ - def __init__(self, base_wait: int = 60, max_wait: int = 600, backoff_factor: int = 1): + def __init__(self, base_wait: int = 60, max_wait: int = 600, backoff_factor: int = 1, source: str = ""): """ 初始化 RateLimiter 实例 :param base_wait: 基础等待时间(秒),默认值为 60 秒(1 分钟) :param max_wait: 最大等待时间(秒),默认值为 600 秒(10 分钟) :param backoff_factor: 等待时间的递增倍数,默认值为 1 + :param source: 业务来源或上下文信息,默认值为 "" """ self.next_allowed_time = 0 self.current_wait = base_wait self.base_wait = base_wait self.max_wait = max_wait self.backoff_factor = backoff_factor + self.source = f"[{source}]" if source else "" self.lock = threading.Lock() def can_call(self) -> bool: @@ -70,7 +72,8 @@ class RateLimiter: with self.lock: if current_time >= self.next_allowed_time: return True - logger.warn(f"限流期间,跳过调用:将在 {self.next_allowed_time - current_time:.2f} 秒后允许继续调用") + wait_time = self.next_allowed_time - current_time + logger.warn(f"{self.source}限流期间,跳过调用,将在 {wait_time:.2f} 秒后允许继续调用") return False def reset(self): @@ -80,7 +83,7 @@ class RateLimiter: """ with self.lock: if self.next_allowed_time != 0 or self.current_wait > self.base_wait: - logger.info(f"调用成功,重置限流等待时长,并允许立即调用") + logger.info(f"{self.source}调用成功,重置限流等待时间为{self.base_wait}秒") self.next_allowed_time = 0 self.current_wait = self.base_wait @@ -92,18 +95,19 @@ class RateLimiter: current_time = time.time() with self.lock: self.next_allowed_time = current_time + self.current_wait - logger.warn(f"触发限流:将在 {self.current_wait} 秒后允许继续调用") + logger.warn(f"{self.source}触发限流,将在 {self.current_wait} 秒后允许继续调用") self.current_wait = min(self.current_wait * self.backoff_factor, self.max_wait) def rate_limit_handler(base_wait: int = 60, max_wait: int = 600, backoff_factor: int = 1, - raise_on_limit: bool = True) -> Callable: + raise_on_limit: bool = True, source: str = "") -> Callable: """ 装饰器,用于处理限流逻辑 :param base_wait: 基础等待时间(秒),默认值为 60 秒(1 分钟) :param max_wait: 最大等待时间(秒),默认值为 600 秒(10 分钟) :param backoff_factor: 等待时间的递增倍数,默认值为 1 :param raise_on_limit: 是否在触发限流异常时抛出异常,默认为 True + :param source: 业务来源或上下文信息,默认为 "" :return: 装饰器函数 """ rate_limiter = RateLimiter(base_wait, max_wait, backoff_factor) @@ -112,17 +116,20 @@ def rate_limit_handler(base_wait: int = 60, max_wait: int = 600, backoff_factor: @functools.wraps(func) def wrapper(*args, **kwargs) -> Optional[Any]: if not rate_limiter.can_call(): + message = f"{source}调用因限流被跳过,当前等待时间为 {rate_limiter.current_wait} 秒" if raise_on_limit: - raise RateLimitExceededException("调用因限流被跳过") + raise RateLimitExceededException(message) + logger.warn(message) return None try: result = func(*args, **kwargs) - rate_limiter.reset() # 调用成功,重置等待时间 + rate_limiter.reset() return result except APIRateLimitException as e: rate_limiter.trigger_limit() - logger.error(f"触发限流:{str(e)}") + message = f"{source}外部调用触发限流:{str(e)},本地等待时间增加到 {rate_limiter.current_wait} 秒" + logger.error(message) if raise_on_limit: raise e return None From b42a69f361b4f1ca9a6a056ad7f62a50126c9428 Mon Sep 17 00:00:00 2001 From: InfinityPacer <160988576+InfinityPacer@users.noreply.github.com> Date: Thu, 5 Sep 2024 00:41:56 +0800 Subject: [PATCH 3/5] feat(rate-limiter): support dynamic raise_exception --- app/utils/common.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/app/utils/common.py b/app/utils/common.py index 837e51476..f115109ca 100644 --- a/app/utils/common.py +++ b/app/utils/common.py @@ -47,12 +47,12 @@ class RateLimiter: 通过增加等待时间逐步减少调用的频率,以避免触发限流 """ - def __init__(self, base_wait: int = 60, max_wait: int = 600, backoff_factor: int = 1, source: str = ""): + def __init__(self, base_wait: int = 60, max_wait: int = 600, backoff_factor: float = 2.0, source: str = ""): """ 初始化 RateLimiter 实例 :param base_wait: 基础等待时间(秒),默认值为 60 秒(1 分钟) :param max_wait: 最大等待时间(秒),默认值为 600 秒(10 分钟) - :param backoff_factor: 等待时间的递增倍数,默认值为 1 + :param backoff_factor: 等待时间的递增倍数,默认值为 2.0,表示指数退避 :param source: 业务来源或上下文信息,默认值为 "" """ self.next_allowed_time = 0 @@ -60,7 +60,7 @@ class RateLimiter: self.base_wait = base_wait self.max_wait = max_wait self.backoff_factor = backoff_factor - self.source = f"[{source}]" if source else "" + self.source = source self.lock = threading.Lock() def can_call(self) -> bool: @@ -106,7 +106,8 @@ def rate_limit_handler(base_wait: int = 60, max_wait: int = 600, backoff_factor: :param base_wait: 基础等待时间(秒),默认值为 60 秒(1 分钟) :param max_wait: 最大等待时间(秒),默认值为 600 秒(10 分钟) :param backoff_factor: 等待时间的递增倍数,默认值为 1 - :param raise_on_limit: 是否在触发限流异常时抛出异常,默认为 True + :param raise_on_limit: 控制默认情况下是否在限流时抛出异常,默认为 True(限流时抛出异常)。 + 如果在函数调用时传入 `raise_exception` 参数,则以传入值为准。 :param source: 业务来源或上下文信息,默认为 "" :return: 装饰器函数 """ @@ -115,8 +116,10 @@ def rate_limit_handler(base_wait: int = 60, max_wait: int = 600, backoff_factor: def decorator(func: Callable) -> Callable: @functools.wraps(func) def wrapper(*args, **kwargs) -> Optional[Any]: + # 动态检查是否传入了 raise_exception,否则使用默认的 raise_on_limit + raise_exception = kwargs.get("raise_exception", raise_on_limit) + message = f"{source}调用因限流被跳过,当前等待时间为 {rate_limiter.current_wait} 秒" if not rate_limiter.can_call(): - message = f"{source}调用因限流被跳过,当前等待时间为 {rate_limiter.current_wait} 秒" if raise_on_limit: raise RateLimitExceededException(message) logger.warn(message) From 7a7225ba4568e99c1ceaa27daf6f6cd214c3977f Mon Sep 17 00:00:00 2001 From: InfinityPacer <160988576+InfinityPacer@users.noreply.github.com> Date: Thu, 5 Sep 2024 00:46:36 +0800 Subject: [PATCH 4/5] fix(rate-limiter): optimize log --- app/utils/common.py | 47 ++++++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/app/utils/common.py b/app/utils/common.py index f115109ca..6219dc8ef 100644 --- a/app/utils/common.py +++ b/app/utils/common.py @@ -1,10 +1,10 @@ import functools import threading import time -from typing import Any, Callable, Optional +from typing import Any, Callable, Optional, Tuple from app.log import logger -from app.schemas import ImmediateException, APIRateLimitException, RateLimitExceededException +from app.schemas import ImmediateException, RateLimitExceededException, LimitException def retry(ExceptionToCheck: Any, @@ -63,7 +63,7 @@ class RateLimiter: self.source = source self.lock = threading.Lock() - def can_call(self) -> bool: + def can_call(self) -> Tuple[bool, str]: """ 检查是否可以进行下一次调用 :return: 如果当前时间超过下一次允许调用的时间,返回 True;否则返回 False @@ -71,10 +71,11 @@ class RateLimiter: current_time = time.time() with self.lock: if current_time >= self.next_allowed_time: - return True + return True, "" wait_time = self.next_allowed_time - current_time - logger.warn(f"{self.source}限流期间,跳过调用,将在 {wait_time:.2f} 秒后允许继续调用") - return False + message = self.format_log(f"限流期间,跳过调用,将在 {wait_time:.2f} 秒后允许继续调用") + logger.info(message) + return False, message def reset(self): """ @@ -83,7 +84,7 @@ class RateLimiter: """ with self.lock: if self.next_allowed_time != 0 or self.current_wait > self.base_wait: - logger.info(f"{self.source}调用成功,重置限流等待时间为{self.base_wait}秒") + logger.info(self.format_log(f"调用成功,重置限流等待时间为{self.base_wait}秒")) self.next_allowed_time = 0 self.current_wait = self.base_wait @@ -95,45 +96,51 @@ class RateLimiter: current_time = time.time() with self.lock: self.next_allowed_time = current_time + self.current_wait - logger.warn(f"{self.source}触发限流,将在 {self.current_wait} 秒后允许继续调用") + logger.warn(self.format_log(f"触发限流,将在 {self.current_wait} 秒后允许继续调用")) self.current_wait = min(self.current_wait * self.backoff_factor, self.max_wait) + def format_log(self, message: str) -> str: + """ + 格式化日志消息 + :param message: 日志内容 + :return: 格式化后的日志消息 + """ + return f"[{self.source}] {message}" if self.source else message -def rate_limit_handler(base_wait: int = 60, max_wait: int = 600, backoff_factor: int = 1, + +def rate_limit_handler(base_wait: int = 60, max_wait: int = 600, backoff_factor: float = 2.0, raise_on_limit: bool = True, source: str = "") -> Callable: """ - 装饰器,用于处理限流逻辑 + 装饰器,用于处理限流逻辑,支持动态控制是否在限流时抛出异常 :param base_wait: 基础等待时间(秒),默认值为 60 秒(1 分钟) :param max_wait: 最大等待时间(秒),默认值为 600 秒(10 分钟) - :param backoff_factor: 等待时间的递增倍数,默认值为 1 + :param backoff_factor: 等待时间的递增倍数,默认值为 2.0 :param raise_on_limit: 控制默认情况下是否在限流时抛出异常,默认为 True(限流时抛出异常)。 如果在函数调用时传入 `raise_exception` 参数,则以传入值为准。 :param source: 业务来源或上下文信息,默认为 "" :return: 装饰器函数 """ - rate_limiter = RateLimiter(base_wait, max_wait, backoff_factor) + rate_limiter = RateLimiter(base_wait, max_wait, backoff_factor, source) def decorator(func: Callable) -> Callable: @functools.wraps(func) def wrapper(*args, **kwargs) -> Optional[Any]: # 动态检查是否传入了 raise_exception,否则使用默认的 raise_on_limit raise_exception = kwargs.get("raise_exception", raise_on_limit) - message = f"{source}调用因限流被跳过,当前等待时间为 {rate_limiter.current_wait} 秒" - if not rate_limiter.can_call(): - if raise_on_limit: + can_call, message = rate_limiter.can_call() + if not can_call: + if raise_exception: raise RateLimitExceededException(message) - logger.warn(message) return None try: result = func(*args, **kwargs) rate_limiter.reset() return result - except APIRateLimitException as e: + except LimitException as e: rate_limiter.trigger_limit() - message = f"{source}外部调用触发限流:{str(e)},本地等待时间增加到 {rate_limiter.current_wait} 秒" - logger.error(message) - if raise_on_limit: + logger.error(rate_limiter.format_log(f"触发限流:{str(e)}")) + if raise_exception: raise e return None From d9f6db18d452ff4b2265cb9deb3b2061a961801a Mon Sep 17 00:00:00 2001 From: InfinityPacer <160988576+InfinityPacer@users.noreply.github.com> Date: Thu, 5 Sep 2024 00:49:29 +0800 Subject: [PATCH 5/5] feat(Douban): add global rate-limiter --- app/modules/douban/__init__.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/app/modules/douban/__init__.py b/app/modules/douban/__init__.py index 733b1610a..801d4de66 100644 --- a/app/modules/douban/__init__.py +++ b/app/modules/douban/__init__.py @@ -15,7 +15,7 @@ from app.modules.douban.douban_cache import DoubanCache from app.modules.douban.scraper import DoubanScraper from app.schemas import MediaPerson, APIRateLimitException from app.schemas.types import MediaType -from app.utils.common import retry +from app.utils.common import retry, rate_limit_handler from app.utils.http import RequestUtils @@ -145,6 +145,7 @@ class DoubanModule(_ModuleBase): return None + @rate_limit_handler(backoff_factor=2, source="douban_info", raise_on_limit=False) def douban_info(self, doubanid: str, mtype: MediaType = None, raise_exception: bool = True) -> Optional[dict]: """ 获取豆瓣信息 @@ -428,9 +429,7 @@ class DoubanModule(_ModuleBase): if "subject_ip_rate_limit" in info.get("msg", ""): msg = f"触发豆瓣IP速率限制,错误信息:{info} ..." logger.warn(msg) - if raise_exception: - raise APIRateLimitException(msg) - return None + raise APIRateLimitException(msg) celebrities = self.doubanapi.tv_celebrities(doubanid) if celebrities: info["directors"] = celebrities.get("directors") @@ -446,9 +445,7 @@ class DoubanModule(_ModuleBase): if "subject_ip_rate_limit" in info.get("msg", ""): msg = f"触发豆瓣IP速率限制,错误信息:{info} ..." logger.warn(msg) - if raise_exception: - raise APIRateLimitException(msg) - return None + raise APIRateLimitException(msg) celebrities = self.doubanapi.movie_celebrities(doubanid) if celebrities: info["directors"] = celebrities.get("directors") @@ -605,6 +602,7 @@ class DoubanModule(_ModuleBase): return [] @retry(Exception, 5, 3, 3, logger=logger) + @rate_limit_handler(source="match_doubaninfo", raise_on_limit=False) def match_doubaninfo(self, name: str, imdbid: str = None, mtype: MediaType = None, year: str = None, season: int = None, raise_exception: bool = False) -> dict: @@ -638,9 +636,7 @@ class DoubanModule(_ModuleBase): if "search_access_rate_limit" in result.values(): msg = f"触发豆瓣API速率限制,错误信息:{result} ..." logger.warn(msg) - if raise_exception: - raise APIRateLimitException(msg) - return {} + raise APIRateLimitException(msg) if not result.get("items"): logger.warn(f"未找到 {name} 的豆瓣信息") return {}