Core API¶
Error Handling¶
aiogram_sentinel.ErrorConfig
dataclass
¶
ErrorConfig(use_friendly_messages=True, domain_classifier=None, message_resolver=None, locale_resolver=None, on_error=None, sync_retry_after=True, respond_strategy='answer', show_alert_for_callbacks=False, send_strategy=None)
Configuration for error handling middleware.
aiogram_sentinel.ErrorEvent
dataclass
¶
Bases: BaseEvent
Event emitted when an error occurs.
aiogram_sentinel.ErrorHandlingMiddleware ¶
Bases: BaseMiddleware
Middleware for centralized error handling.
Initialize the error handling middleware.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
ErrorConfig
|
Error configuration |
required |
key_builder
|
KeyBuilder
|
KeyBuilder instance for key generation |
required |
rate_limiter
|
RateLimiterBackend | None
|
Optional rate limiter for RetryAfter sync |
None
|
Source code in src/aiogram_sentinel/middlewares/errors.py
__call__
async
¶
Process the event through error handling middleware.
Source code in src/aiogram_sentinel/middlewares/errors.py
Policy Registry¶
aiogram_sentinel.PolicyRegistry ¶
Registry for managing named policies.
Initialize empty registry.
Source code in src/aiogram_sentinel/policy.py
register ¶
Register a new policy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
policy
|
Policy
|
Policy to register |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If policy name already exists |
Source code in src/aiogram_sentinel/policy.py
get ¶
Get policy by name.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Policy name |
required |
Returns:
Type | Description |
---|---|
Policy
|
Policy instance |
Raises:
Type | Description |
---|---|
ValueError
|
If policy not found, with suggestions |
Source code in src/aiogram_sentinel/policy.py
aiogram_sentinel.Policy
dataclass
¶
aiogram_sentinel.ThrottleCfg
dataclass
¶
aiogram_sentinel.DebounceCfg
dataclass
¶
aiogram_sentinel.policy ¶
Policy registry and configuration for aiogram-sentinel.
DebounceCfg
dataclass
¶
Configuration for debouncing policy.
Policy
dataclass
¶
A named policy configuration.
__post_init__ ¶
Validate policy after initialization.
Source code in src/aiogram_sentinel/policy.py
PolicyRegistry ¶
Registry for managing named policies.
Initialize empty registry.
Source code in src/aiogram_sentinel/policy.py
all ¶
Get all registered policies in registration order.
Returns:
Type | Description |
---|---|
list[Policy]
|
List of all policies |
clear ¶
get ¶
Get policy by name.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Policy name |
required |
Returns:
Type | Description |
---|---|
Policy
|
Policy instance |
Raises:
Type | Description |
---|---|
ValueError
|
If policy not found, with suggestions |
Source code in src/aiogram_sentinel/policy.py
ThrottleCfg
dataclass
¶
Configuration for throttling policy.
__post_init__ ¶
Validate configuration after initialization.
coerce_scope ¶
Coerce string scope to Scope enum with deprecation warning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scope
|
str | Scope | None
|
String, Scope enum, or None |
required |
Returns:
Type | Description |
---|---|
Scope | None
|
Scope enum or None |
Raises:
Type | Description |
---|---|
ValueError
|
If string scope is invalid |
Source code in src/aiogram_sentinel/policy.py
convert_from_legacy_debounce ¶
Convert legacy debouncing config to DebounceCfg.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
tuple[Any, ...] | dict[str, Any]
|
Legacy config tuple or dict |
required |
Returns:
Type | Description |
---|---|
DebounceCfg
|
DebounceCfg instance |
Source code in src/aiogram_sentinel/policy.py
convert_from_legacy_throttle ¶
Convert legacy throttling config to ThrottleCfg.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
tuple[Any, ...] | dict[str, Any]
|
Legacy config tuple or dict |
required |
Returns:
Type | Description |
---|---|
ThrottleCfg
|
ThrottleCfg instance |
Source code in src/aiogram_sentinel/policy.py
policy ¶
Decorator to attach policies to handlers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*names
|
str
|
Policy names to attach |
()
|
Returns:
Type | Description |
---|---|
Callable[[Callable[..., Any]], Callable[..., Any]]
|
Decorator function |
Raises:
Type | Description |
---|---|
ValueError
|
If no policy names provided |
Source code in src/aiogram_sentinel/policy.py
resolve_scope ¶
Resolve scope with cap constraint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id
|
int | None
|
User identifier |
required |
chat_id
|
int | None
|
Chat identifier |
required |
cap
|
Scope | None
|
Maximum scope allowed (cap constraint) |
required |
Returns:
Type | Description |
---|---|
Scope | None
|
Resolved scope or None if cannot satisfy cap |
Source code in src/aiogram_sentinel/policy.py
aiogram_sentinel.coerce_scope ¶
Coerce string scope to Scope enum with deprecation warning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scope
|
str | Scope | None
|
String, Scope enum, or None |
required |
Returns:
Type | Description |
---|---|
Scope | None
|
Scope enum or None |
Raises:
Type | Description |
---|---|
ValueError
|
If string scope is invalid |
Source code in src/aiogram_sentinel/policy.py
aiogram_sentinel.resolve_scope ¶
Resolve scope with cap constraint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_id
|
int | None
|
User identifier |
required |
chat_id
|
int | None
|
Chat identifier |
required |
cap
|
Scope | None
|
Maximum scope allowed (cap constraint) |
required |
Returns:
Type | Description |
---|---|
Scope | None
|
Resolved scope or None if cannot satisfy cap |
Source code in src/aiogram_sentinel/policy.py
Main Classes¶
aiogram_sentinel.Sentinel ¶
Main setup class for aiogram-sentinel.
setup
async
staticmethod
¶
Setup aiogram-sentinel middlewares.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dp
|
Dispatcher
|
Dispatcher instance |
required |
cfg
|
SentinelConfig
|
Configuration |
required |
router
|
Router | None
|
Optional router to use (creates new one if not provided) |
None
|
infra
|
InfraBundle | None
|
Optional infrastructure bundle (builds from config if not provided) |
None
|
error_config
|
ErrorConfig | None
|
Optional error handling configuration |
None
|
Returns:
Type | Description |
---|---|
tuple[Router, InfraBundle]
|
Tuple of (router, infra_bundle) |
Source code in src/aiogram_sentinel/sentinel.py
add_hooks
staticmethod
¶
Add hooks to existing middlewares.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
router
|
Router
|
Router with middlewares |
required |
infra
|
InfraBundle
|
Infrastructure bundle (rate_limiter, debounce) |
required |
cfg
|
SentinelConfig
|
SentinelConfig configuration |
required |
on_rate_limited
|
Callable[[Any, dict[str, Any], float], Awaitable[Any]] | None
|
Optional hook for rate-limited events |
None
|
Source code in src/aiogram_sentinel/sentinel.py
aiogram_sentinel.SentinelConfig
dataclass
¶
SentinelConfig(backend='memory', redis_url='redis://localhost:6379', redis_prefix='sentinel', throttling_default_max=5, throttling_default_per_seconds=10, debounce_default_window=2, require_registration=False)
Configuration for aiogram-sentinel.
throttling_default_per_seconds
class-attribute
instance-attribute
¶
aiogram_sentinel.InfraBundle
dataclass
¶
Bundle of infrastructure backends managed by the library.
aiogram_sentinel.RateLimiterBackend ¶
Bases: Protocol
Protocol for rate limiting storage backend.
aiogram_sentinel.KeyBuilder ¶
Composite key builder with collision-proof scheme.
Initialize KeyBuilder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
str
|
Application prefix (typically from redis_prefix config) |
required |
sep
|
str
|
Key separator character |
':'
|
Source code in src/aiogram_sentinel/scopes.py
for_update ¶
Build canonical key for storage/metrics with stable ordering.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
KeyParts
|
Key parts containing namespace, scope, and identifiers |
required |
method
|
str | None
|
Optional method name (e.g., "sendMessage") |
None
|
bucket
|
str | None
|
Optional bucket identifier |
None
|
Returns:
Type | Description |
---|---|
str
|
Canonical key string |
Raises:
Type | Description |
---|---|
ValueError
|
If method or bucket contain separator characters |
Source code in src/aiogram_sentinel/scopes.py
user ¶
Build key for user scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
namespace
|
str
|
Key namespace (e.g., "throttle", "debounce") |
required |
user_id
|
int
|
User identifier |
required |
**kwargs
|
Any
|
Additional parameters (method, bucket) |
{}
|
Returns:
Type | Description |
---|---|
str
|
User-scoped key |
Source code in src/aiogram_sentinel/scopes.py
chat ¶
Build key for chat scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
namespace
|
str
|
Key namespace (e.g., "throttle", "debounce") |
required |
chat_id
|
int
|
Chat identifier |
required |
**kwargs
|
Any
|
Additional parameters (method, bucket) |
{}
|
Returns:
Type | Description |
---|---|
str
|
Chat-scoped key |
Source code in src/aiogram_sentinel/scopes.py
group ¶
Build key for group scope (user+chat composite).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
namespace
|
str
|
Key namespace (e.g., "throttle", "debounce") |
required |
user_id
|
int
|
User identifier |
required |
chat_id
|
int
|
Chat identifier |
required |
**kwargs
|
Any
|
Additional parameters (method, bucket) |
{}
|
Returns:
Type | Description |
---|---|
str
|
Group-scoped key |
Source code in src/aiogram_sentinel/scopes.py
global_ ¶
Build key for global scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
namespace
|
str
|
Key namespace (e.g., "throttle", "debounce") |
required |
**kwargs
|
Any
|
Additional parameters (method, bucket) |
{}
|
Returns:
Type | Description |
---|---|
str
|
Global-scoped key |
Source code in src/aiogram_sentinel/scopes.py
aiogram_sentinel.KeyParts
dataclass
¶
aiogram_sentinel.Scope ¶
Context Extractors¶
aiogram_sentinel.context.extract_user_id ¶
Extract user ID from event with fallbacks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TelegramObject
|
Telegram event object |
required |
data
|
dict[str, Any]
|
Middleware data dictionary |
required |
Returns:
Type | Description |
---|---|
int | None
|
User ID if found, None otherwise |
Source code in src/aiogram_sentinel/context.py
aiogram_sentinel.context.extract_chat_id ¶
Extract chat ID from event.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TelegramObject
|
Telegram event object |
required |
data
|
dict[str, Any]
|
Middleware data dictionary |
required |
Returns:
Type | Description |
---|---|
int | None
|
Chat ID if found, None otherwise |
Source code in src/aiogram_sentinel/context.py
aiogram_sentinel.context.extract_group_ids ¶
Extract both user and chat IDs for group scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TelegramObject
|
Telegram event object |
required |
data
|
dict[str, Any]
|
Middleware data dictionary |
required |
Returns:
Type | Description |
---|---|
tuple[int | None, int | None]
|
Tuple of (user_id, chat_id) |
Source code in src/aiogram_sentinel/context.py
aiogram_sentinel.context.extract_event_type ¶
Extract event type for classification.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TelegramObject
|
Telegram event object |
required |
data
|
dict[str, Any]
|
Middleware data dictionary |
required |
Returns:
Type | Description |
---|---|
str
|
Event type string |
Source code in src/aiogram_sentinel/context.py
aiogram_sentinel.context.extract_handler_bucket ¶
Extract handler bucket from event and data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TelegramObject
|
Telegram event object |
required |
data
|
dict[str, Any]
|
Middleware data dictionary |
required |
Returns:
Type | Description |
---|---|
str | None
|
Handler bucket string if found, None otherwise |
Source code in src/aiogram_sentinel/context.py
aiogram_sentinel.context.extract_callback_bucket ¶
Extract callback bucket from callback query events.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TelegramObject
|
Telegram event object |
required |
data
|
dict[str, Any]
|
Middleware data dictionary |
required |
Returns:
Type | Description |
---|---|
str | None
|
Callback bucket string if found, None otherwise |
Source code in src/aiogram_sentinel/context.py
Middleware¶
aiogram_sentinel.middlewares.ThrottlingMiddleware ¶
Bases: BaseMiddleware
Middleware for rate limiting with optional notifier hook.
Initialize the throttling middleware.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rate_limiter
|
RateLimiterBackend
|
Rate limiter backend instance |
required |
cfg
|
SentinelConfig
|
SentinelConfig configuration |
required |
key_builder
|
KeyBuilder
|
KeyBuilder instance for key generation |
required |
on_rate_limited
|
Callable[[TelegramObject, dict[str, Any], float], Awaitable[None]] | None
|
Optional hook called when rate limit is exceeded |
None
|
Source code in src/aiogram_sentinel/middlewares/throttling.py
__call__
async
¶
Process the event through throttling middleware.
Source code in src/aiogram_sentinel/middlewares/throttling.py
aiogram_sentinel.middlewares.DebounceMiddleware ¶
Bases: BaseMiddleware
Middleware for debouncing duplicate messages with fingerprinting.
Initialize the debouncing middleware.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
debounce_backend
|
DebounceBackend
|
Debounce backend instance |
required |
cfg
|
SentinelConfig
|
SentinelConfig configuration |
required |
key_builder
|
KeyBuilder
|
KeyBuilder instance for key generation |
required |
Source code in src/aiogram_sentinel/middlewares/debouncing.py
__call__
async
¶
Process the event through debouncing middleware.
Source code in src/aiogram_sentinel/middlewares/debouncing.py
Decorators¶
aiogram_sentinel.decorators.rate_limit ¶
Decorator to set rate limit configuration on handlers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_events
|
int
|
Maximum number of events per time window |
required |
per_seconds
|
int
|
Time window in seconds |
required |
scope
|
str | None
|
Optional scope for rate limiting |
None
|
Deprecated
Use @policy() with PolicyRegistry instead. Will be removed in v2.0.0.
Source code in src/aiogram_sentinel/decorators.py
aiogram_sentinel.decorators.debounce ¶
Decorator to set debounce configuration on handlers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
window_seconds
|
int
|
Debounce window in seconds |
required |
scope
|
str | None
|
Optional scope for debouncing |
None
|
Deprecated
Use @policy() with PolicyRegistry instead. Will be removed in v2.0.0.
Source code in src/aiogram_sentinel/decorators.py
aiogram_sentinel.policy.policy ¶
Decorator to attach policies to handlers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*names
|
str
|
Policy names to attach |
()
|
Returns:
Type | Description |
---|---|
Callable[[Callable[..., Any]], Callable[..., Any]]
|
Decorator function |
Raises:
Type | Description |
---|---|
ValueError
|
If no policy names provided |
Source code in src/aiogram_sentinel/policy.py
Utilities¶
Key Generation¶
aiogram_sentinel.utils.keys.rate_key ¶
Build rate limiting key from user ID and handler scope.
.. deprecated:: 1.1.0
Use :class:KeyBuilder
instead. This function will be removed in v2.0.0.
Migration:
.. code-block:: python
# Old
key = rate_key(user_id, handler_name, **kwargs)
# New
from aiogram_sentinel import KeyBuilder
kb = KeyBuilder(app="sentinel")
key = kb.user("throttle", user_id, bucket=handler_name, **kwargs)
Source code in src/aiogram_sentinel/utils/keys.py
aiogram_sentinel.utils.keys.debounce_key ¶
Build debounce key from user ID and handler scope.
.. deprecated:: 1.1.0
Use :class:KeyBuilder
instead. This function will be removed in v2.0.0.
Migration:
.. code-block:: python
# Old
key = debounce_key(user_id, handler_name, **kwargs)
# New
from aiogram_sentinel import KeyBuilder
kb = KeyBuilder(app="sentinel")
key = kb.user("debounce", user_id, bucket=handler_name, **kwargs)
Source code in src/aiogram_sentinel/utils/keys.py
aiogram_sentinel.utils.keys.fingerprint ¶
Create a stable fingerprint for text content.