Utils Package
# Submodules section with toctree removed as automodule below will cover them. # ———- # .. toctree:: # :maxdepth: 1 # # utils.cache # utils.helpers # utils.logging # utils.period_parser # utils.ratelimiter # utils.retry_decorators # utils.sentry_integration
- class utils.cache.SheetCache[исходный код]
Базовые классы:
object
A simple in-memory cache with Time-To-Live (TTL) for sheet data.
- __init__()[исходный код]
Initializes the cache store.
- utils.cache.cached_sheet_method(key_fn)[исходный код]
Decorator to cache the result of a method reading from Sheets.
The decorated method must have user_id as its first or second argument (after self). The key_fn is a lambda that receives the method’s arguments (excluding self and user_id) and should return a string that, combined with user_id and the method name, forms a unique cache key.
- utils.cache.invalidate_sheet_cache(user_id)[исходный код]
Invalidates all cache entries for a specific user.
This should be called after any operation that modifies a user’s spreadsheet to ensure cache consistency.
General helper functions used across the application.
- utils.helpers.escape_markdown_v2(text)[исходный код]
Escapes special characters for MarkdownV2.
- utils.helpers.format_date(date_obj, tz=None)[исходный код]
Formats a datetime object to DD.MM.YYYY string in the specified timezone.
- utils.helpers.get_day_of_week(date_obj, tz=None)[исходный код]
Gets the localized (Russian) name of the day of the week for a datetime object.
Logging setup for the application using structlog and standard logging.
- utils.logging.setup_logging(log_level='INFO')[исходный код]
Sets up standard logging and structlog with JSON output.
- utils.period_parser.parse_period(text)[исходный код]
Returns the number of days. Raises ValueError on failure.
Rate limiting utilities using the Token Bucket algorithm.
This module provides:
RateLimitException: Custom exception raised when a rate limit is exceeded.
TokenBucket: Core implementation of the token bucket algorithm, managing token replenishment and consumption for a single resource.
UserRateLimiter: Manages multiple TokenBucket instances, typically one per user, to enforce user-specific rate limits for operations like LLM calls.
The UserRateLimiter is intended to be instantiated once per limited resource type (e.g., one for LLM calls) and then used by calling its check_limit method, passing the user identifier.
- exception utils.ratelimiter.RateLimitException(message, retry_after_seconds=None)[исходный код]
Базовые классы:
Exception
Exception raised when an operation exceeds the defined rate limit.
- class utils.ratelimiter.TokenBucket(tokens_per_second, max_tokens)[исходный код]
Базовые классы:
object
Implements the Token Bucket algorithm for a single rate-limited resource.
- tokens_per_second
The rate at which tokens are added to the bucket.
- max_tokens
The maximum capacity of the bucket.
- current_tokens
The current number of available tokens.
- last_update_time
The timestamp of the last token refill.
- __init__(tokens_per_second, max_tokens)[исходный код]
Initializes a TokenBucket.
- consume(tokens_to_consume=1)[исходный код]
Attempts to consume a number of tokens.
- get_retry_after(tokens_to_consume=1)[исходный код]
Calculates how long to wait before tokens_to_consume can be met.
- class utils.ratelimiter.UserRateLimiter(default_tokens_per_second, default_max_tokens)[исходный код]
Базовые классы:
object
Manages a collection of TokenBuckets, typically one per user ID.
This allows enforcing rate limits on a per-user basis for shared resources.
- __init__(default_tokens_per_second, default_max_tokens)[исходный код]
Initializes the UserRateLimiter with default bucket parameters.
- check_limit(user_id, tokens_to_consume=1)[исходный код]
Checks if the specified user can consume the given number of tokens.
- Параметры:
- Исключение:
RateLimitException – If the user’s bucket does not have enough tokens.
- Тип результата:
Standardized Tenacity retry decorators for external API calls.
This module provides pre-configured tenacity.retry decorators for common API interaction patterns within the application, such as calls to Google Sheets and OpenAI LLM. It includes a shared logging callback (_log_retry) to report retry attempts.
Key decorators: - retry_google_sheets: For gspread API calls. - retry_openai_llm: For OpenAI API calls, reraises exceptions. - retry_openai_llm_no_reraise: For OpenAI calls where returning None on failure is preferred.
Sentry integration setup for error tracking and performance monitoring.
- utils.sentry_integration.setup_sentry()[исходный код]
Initializes Sentry if the SENTRY_DSN environment variable is set.
- Тип результата: