Skip to content

Core API

Error Handling

Configuration for error handling middleware.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/errors.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@dataclass
class ErrorConfig:
    """Configuration for error handling middleware."""

    use_friendly_messages: bool = True
    domain_classifier: Callable[[Exception], str | None] | None = None
    message_resolver: Callable[[str, str], str] | None = None
    locale_resolver: Callable[[TelegramObject, dict[str, Any]], str] | None = None
    on_error: (
        Callable[[TelegramObject, Exception, dict[str, Any]], Awaitable[None]] | None
    ) = None
    sync_retry_after: bool = True
    respond_strategy: str = "answer"  # "answer", "reply", "none"
    show_alert_for_callbacks: bool = False
    send_strategy: (
        Callable[[TelegramObject, dict[str, Any], str], Awaitable[None]] | None
    ) = None
    reraise_exceptions: tuple[type[Exception], ...] = ()

    def __post_init__(self) -> None:
        if not isinstance(cast(object, self.reraise_exceptions), tuple) or any(
            not isinstance(cast(object, value), type)
            or not issubclass(cast(type[object], value), Exception)
            for value in self.reraise_exceptions
        ):
            raise ValueError("reraise_exceptions must be a tuple of Exception types")

use_friendly_messages = True class-attribute instance-attribute

domain_classifier = None class-attribute instance-attribute

message_resolver = None class-attribute instance-attribute

locale_resolver = None class-attribute instance-attribute

on_error = None class-attribute instance-attribute

sync_retry_after = True class-attribute instance-attribute

respond_strategy = 'answer' class-attribute instance-attribute

show_alert_for_callbacks = False class-attribute instance-attribute

send_strategy = None class-attribute instance-attribute

Bases: BaseEvent

Event emitted when an error occurs.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/events.py
21
22
23
24
25
26
27
28
29
30
31
@dataclass
class ErrorEvent(BaseEvent):
    """Event emitted when an error occurs."""

    error_type: str
    error_message: str
    event_type: str
    user_id: int | None
    chat_id: int | None
    locale: str
    retry_after: float | None = None

error_type instance-attribute

error_message instance-attribute

event_type instance-attribute

user_id instance-attribute

chat_id instance-attribute

locale instance-attribute

retry_after = None class-attribute instance-attribute

Bases: BaseMiddleware

Middleware for centralized error handling.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/errors.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
class ErrorHandlingMiddleware(BaseMiddleware):
    """Middleware for centralized error handling."""

    def __init__(
        self,
        cfg: ErrorConfig,
        key_builder: KeyBuilder,
        rate_limiter: RateLimiterBackend | None = None,
    ) -> None:
        """Initialize the error handling middleware.

        Args:
            cfg: Error configuration
            key_builder: KeyBuilder instance for key generation
            rate_limiter: Optional rate limiter for RetryAfter sync
        """
        super().__init__()
        self._cfg = cfg
        self._key_builder = key_builder
        self._rate_limiter = rate_limiter

    async def __call__(
        self,
        handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
        event: TelegramObject,
        data: dict[str, Any],
    ) -> Any:
        """Process the event through error handling middleware."""
        try:
            return await handler(event, data)
        except Exception as exc:
            if isinstance(exc, self._cfg.reraise_exceptions):
                raise
            await self._handle_error(exc, event, data)
            # Don't re-raise - error has been handled
            return None

    async def _handle_error(
        self,
        exc: Exception,
        event: TelegramObject,
        data: dict[str, Any],
    ) -> None:
        """Handle an exception that occurred during processing.

        Args:
            exc: The exception that occurred
            event: Telegram event object
            data: Middleware data dictionary
        """
        # Classify the exception
        error_key = self._classify_exception(exc)

        # Resolve locale
        locale = self._resolve_locale(event, data)

        # Build context
        user_id, chat_id = extract_group_ids(event, data)
        event_type = extract_event_type(event, data)

        # Extract retry_after if applicable
        retry_after = None
        if isinstance(exc, TelegramRetryAfter):
            retry_after = exc.retry_after

        # Publish error event
        error_event = ErrorEvent(
            error_type=error_key,
            error_message=str(exc),
            event_type=event_type,
            user_id=user_id,
            chat_id=chat_id,
            locale=locale,
            retry_after=retry_after,
        )
        events.publish(error_event)

        # Handle RetryAfter sync
        if (
            isinstance(exc, TelegramRetryAfter)
            and self._cfg.sync_retry_after
            and self._rate_limiter
        ):
            await self._sync_retry_after(exc, user_id, chat_id)

        # Send friendly message
        if self._cfg.use_friendly_messages:
            await self._send_friendly_message(error_key, locale, event, data)

        # Call on_error hook
        if self._cfg.on_error:
            try:
                await self._cfg.on_error(event, exc, data)
            except Exception as hook_exc:
                logger.exception("on_error hook failed: %s", hook_exc)

    def _classify_exception(self, exc: Exception) -> str:
        """Classify an exception to an i18n key.

        Args:
            exc: Exception to classify

        Returns:
            i18n key for the exception
        """
        # Check for Telegram API exceptions first
        if isinstance(exc, TelegramBadRequest):
            return "error_telegram_badrequest"
        elif isinstance(exc, TelegramForbiddenError):
            return "error_telegram_forbidden"
        elif isinstance(exc, TelegramConflictError):
            return "error_telegram_conflict"
        elif isinstance(exc, TelegramRetryAfter):
            return "error_telegram_retry_after"
        elif isinstance(exc, TelegramServerError):
            return "error_telegram_server"
        elif isinstance(exc, TelegramUnauthorizedError):
            return "error_telegram_unauthorized"
        elif isinstance(exc, TelegramAPIError):
            return "error_telegram_generic"

        # Check for aiogram-sentinel exceptions
        elif isinstance(exc, SentinelError):
            return "error_sentinel_generic"

        # Try domain classifier
        elif self._cfg.domain_classifier:
            try:
                domain_key = self._cfg.domain_classifier(exc)
                if domain_key:
                    return domain_key
            except Exception as e:
                logger.exception("Domain classifier failed: %s", e)

        # Fallback to system error
        return "error_unexpected_system"

    def _resolve_locale(
        self,
        event: TelegramObject,
        data: dict[str, Any],
    ) -> str:
        """Resolve locale for the event.

        Args:
            event: Telegram event object
            data: Middleware data dictionary

        Returns:
            Locale string
        """
        if self._cfg.locale_resolver:
            try:
                return self._cfg.locale_resolver(event, data)
            except Exception as e:
                logger.exception("Locale resolver failed: %s", e)

        # Default fallback
        return "en"

    async def _sync_retry_after(
        self,
        exc: TelegramRetryAfter,
        user_id: int | None,
        chat_id: int | None,
    ) -> None:
        """Sync RetryAfter with internal cooldown.

        Args:
            exc: RetryAfter exception
            user_id: User ID
            chat_id: Chat ID
        """
        if not self._rate_limiter:
            return

        try:
            # Resolve scope for retry after key
            resolved_scope = resolve_scope(user_id, chat_id, None)
            if resolved_scope is None:
                resolved_scope = Scope.GLOBAL

            # Generate key
            if resolved_scope == Scope.GROUP and user_id and chat_id:
                key = self._key_builder.group("retryafter", user_id, chat_id)
            elif resolved_scope == Scope.USER and user_id:
                key = self._key_builder.user("retryafter", user_id)
            elif resolved_scope == Scope.CHAT and chat_id:
                key = self._key_builder.chat("retryafter", chat_id)
            else:
                key = self._key_builder.global_("retryafter")

            # Set TTL (ceil to ensure we don't under-estimate)
            ttl = math.ceil(exc.retry_after)

            # Use rate limiter to set the cooldown
            # We'll use a simple approach: set limit=1, window=ttl, and check if allowed
            # This effectively creates a cooldown
            await self._rate_limiter.allow(key, 1, ttl)

        except Exception as e:
            logger.exception("Failed to sync RetryAfter: %s", e)

    async def _send_friendly_message(
        self,
        error_key: str,
        locale: str,
        event: TelegramObject,
        data: dict[str, Any],
    ) -> None:
        """Send a friendly error message to the user.

        Args:
            error_key: i18n key for the error
            locale: Locale for message resolution
            event: Telegram event object
            data: Middleware data dictionary
        """
        # Resolve message
        message_text = self._resolve_message(error_key, locale)

        # Use custom send strategy if provided
        if self._cfg.send_strategy:
            try:
                await self._cfg.send_strategy(event, data, message_text)
                return
            except Exception as e:
                logger.exception("Custom send strategy failed: %s", e)

        # Use default send strategy
        try:
            await self._default_send_strategy(event, data, message_text)
        except Exception as e:
            logger.exception("Failed to send friendly error message: %s", e)

    def _resolve_message(self, error_key: str, locale: str) -> str:
        """Resolve an error key to a localized message.

        Args:
            error_key: i18n key
            locale: Locale

        Returns:
            Localized message
        """
        if self._cfg.message_resolver:
            try:
                return self._cfg.message_resolver(error_key, locale)
            except Exception as e:
                logger.exception("Message resolver failed: %s", e)

        # Default fallback - return the key itself
        return error_key

    async def _default_send_strategy(
        self,
        event: TelegramObject,
        data: dict[str, Any],
        text: str,
    ) -> None:
        """Default message sending strategy.

        Args:
            event: Telegram event object
            data: Middleware data dictionary
            text: Message text to send
        """
        try:
            # Check if this is a callback query
            if isinstance(event, CallbackQuery):
                await event.answer(text, show_alert=self._cfg.show_alert_for_callbacks)
                return

            # Check if we have a message in data
            message = data.get("message")
            if isinstance(message, Message):
                await message.reply(text, disable_notification=True)
                return

            # Check if event itself is a message
            if isinstance(event, Message):
                await event.reply(text, disable_notification=True)
                return

            # No suitable target found
            logger.debug("No suitable target found for error message")

        except Exception as e:
            # Check if it's a known Telegram exception that we should ignore
            if (
                "message not modified" in str(e).lower()
                or "can't initiate conversation" in str(e).lower()
            ):
                logger.debug("Could not send error message: %s", text)
            else:
                logger.exception("Failed to send friendly error message: %s", e)

__call__(handler, event, data) async

Process the event through error handling middleware.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/errors.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
async def __call__(
    self,
    handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
    event: TelegramObject,
    data: dict[str, Any],
) -> Any:
    """Process the event through error handling middleware."""
    try:
        return await handler(event, data)
    except Exception as exc:
        if isinstance(exc, self._cfg.reraise_exceptions):
            raise
        await self._handle_error(exc, event, data)
        # Don't re-raise - error has been handled
        return None

__init__(cfg, key_builder, rate_limiter=None)

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 packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/errors.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def __init__(
    self,
    cfg: ErrorConfig,
    key_builder: KeyBuilder,
    rate_limiter: RateLimiterBackend | None = None,
) -> None:
    """Initialize the error handling middleware.

    Args:
        cfg: Error configuration
        key_builder: KeyBuilder instance for key generation
        rate_limiter: Optional rate limiter for RetryAfter sync
    """
    super().__init__()
    self._cfg = cfg
    self._key_builder = key_builder
    self._rate_limiter = rate_limiter

Policy Registry

Registry for managing named policies.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class PolicyRegistry:
    """Registry for managing named policies."""

    def __init__(self) -> None:
        """Initialize empty registry."""
        self._policies: OrderedDict[str, Policy] = OrderedDict()

    def register(self, policy: Policy) -> None:
        """Register a new policy.

        Args:
            policy: Policy to register

        Raises:
            ValueError: If policy name already exists
        """
        if policy.name in self._policies:
            raise ValueError(f"Policy '{policy.name}' already registered")

        self._policies[policy.name] = policy

    def get(self, name: str) -> Policy:
        """Get policy by name.

        Args:
            name: Policy name

        Returns:
            Policy instance

        Raises:
            ValueError: If policy not found, with suggestions
        """
        if name in self._policies:
            return self._policies[name]

        # Generate suggestions
        suggestions = difflib.get_close_matches(
            name, self._policies.keys(), n=3, cutoff=0.6
        )

        if suggestions:
            suggestion_text = f" Did you mean: {', '.join(suggestions)}?"
        else:
            suggestion_text = ""

        raise ValueError(f"Policy '{name}' not found.{suggestion_text}")

    def all(self) -> list[Policy]:
        """Get all registered policies in registration order.

        Returns:
            List of all policies
        """
        return list(self._policies.values())

    def clear(self) -> None:
        """Clear all registered policies."""
        self._policies.clear()

register(policy)

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
78
79
80
81
82
83
84
85
86
87
88
89
90
def register(self, policy: Policy) -> None:
    """Register a new policy.

    Args:
        policy: Policy to register

    Raises:
        ValueError: If policy name already exists
    """
    if policy.name in self._policies:
        raise ValueError(f"Policy '{policy.name}' already registered")

    self._policies[policy.name] = policy

get(name)

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def get(self, name: str) -> Policy:
    """Get policy by name.

    Args:
        name: Policy name

    Returns:
        Policy instance

    Raises:
        ValueError: If policy not found, with suggestions
    """
    if name in self._policies:
        return self._policies[name]

    # Generate suggestions
    suggestions = difflib.get_close_matches(
        name, self._policies.keys(), n=3, cutoff=0.6
    )

    if suggestions:
        suggestion_text = f" Did you mean: {', '.join(suggestions)}?"
    else:
        suggestion_text = ""

    raise ValueError(f"Policy '{name}' not found.{suggestion_text}")

all()

Get all registered policies in registration order.

Returns:

Type Description
list[Policy]

List of all policies

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
119
120
121
122
123
124
125
def all(self) -> list[Policy]:
    """Get all registered policies in registration order.

    Returns:
        List of all policies
    """
    return list(self._policies.values())

clear()

Clear all registered policies.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
127
128
129
def clear(self) -> None:
    """Clear all registered policies."""
    self._policies.clear()

A named policy configuration.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@dataclass(frozen=True)
class Policy:
    """A named policy configuration."""

    name: str
    kind: PolicyKind
    cfg: ThrottleCfg | DebounceCfg
    description: str = ""

    def __post_init__(self) -> None:
        """Validate policy after initialization."""
        if not self.name:
            raise ValueError("policy name cannot be empty")

        # Validate cfg matches kind
        if self.kind == "throttle" and not isinstance(self.cfg, ThrottleCfg):
            raise ValueError("throttle policy must use ThrottleCfg")
        elif self.kind == "debounce" and not isinstance(self.cfg, DebounceCfg):
            raise ValueError("debounce policy must use DebounceCfg")

name instance-attribute

kind instance-attribute

cfg instance-attribute

description = '' class-attribute instance-attribute

Configuration for throttling policy.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@dataclass(frozen=True)
class ThrottleCfg:
    """Configuration for throttling policy."""

    rate: int
    per: int
    scope: Scope | None = None
    method: str | None = None
    bucket: str | None = None

    def __post_init__(self) -> None:
        """Validate configuration after initialization."""
        if self.rate <= 0:
            raise ValueError("rate must be positive")
        if self.per <= 0:
            raise ValueError("per must be positive")

rate instance-attribute

per instance-attribute

scope = None class-attribute instance-attribute

method = None class-attribute instance-attribute

bucket = None class-attribute instance-attribute

Configuration for debouncing policy.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
35
36
37
38
39
40
41
42
43
44
45
46
47
@dataclass(frozen=True)
class DebounceCfg:
    """Configuration for debouncing policy."""

    window: int
    scope: Scope | None = None
    method: str | None = None
    bucket: str | None = None

    def __post_init__(self) -> None:
        """Validate configuration after initialization."""
        if self.window <= 0:
            raise ValueError("window must be positive")

window instance-attribute

scope = None class-attribute instance-attribute

method = None class-attribute instance-attribute

bucket = None class-attribute instance-attribute

Policy registry and configuration for aiogram-sentinel.

DebounceCfg dataclass

Configuration for debouncing policy.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
35
36
37
38
39
40
41
42
43
44
45
46
47
@dataclass(frozen=True)
class DebounceCfg:
    """Configuration for debouncing policy."""

    window: int
    scope: Scope | None = None
    method: str | None = None
    bucket: str | None = None

    def __post_init__(self) -> None:
        """Validate configuration after initialization."""
        if self.window <= 0:
            raise ValueError("window must be positive")

__post_init__()

Validate configuration after initialization.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
44
45
46
47
def __post_init__(self) -> None:
    """Validate configuration after initialization."""
    if self.window <= 0:
        raise ValueError("window must be positive")

Policy dataclass

A named policy configuration.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@dataclass(frozen=True)
class Policy:
    """A named policy configuration."""

    name: str
    kind: PolicyKind
    cfg: ThrottleCfg | DebounceCfg
    description: str = ""

    def __post_init__(self) -> None:
        """Validate policy after initialization."""
        if not self.name:
            raise ValueError("policy name cannot be empty")

        # Validate cfg matches kind
        if self.kind == "throttle" and not isinstance(self.cfg, ThrottleCfg):
            raise ValueError("throttle policy must use ThrottleCfg")
        elif self.kind == "debounce" and not isinstance(self.cfg, DebounceCfg):
            raise ValueError("debounce policy must use DebounceCfg")

__post_init__()

Validate policy after initialization.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
59
60
61
62
63
64
65
66
67
68
def __post_init__(self) -> None:
    """Validate policy after initialization."""
    if not self.name:
        raise ValueError("policy name cannot be empty")

    # Validate cfg matches kind
    if self.kind == "throttle" and not isinstance(self.cfg, ThrottleCfg):
        raise ValueError("throttle policy must use ThrottleCfg")
    elif self.kind == "debounce" and not isinstance(self.cfg, DebounceCfg):
        raise ValueError("debounce policy must use DebounceCfg")

PolicyRegistry

Registry for managing named policies.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class PolicyRegistry:
    """Registry for managing named policies."""

    def __init__(self) -> None:
        """Initialize empty registry."""
        self._policies: OrderedDict[str, Policy] = OrderedDict()

    def register(self, policy: Policy) -> None:
        """Register a new policy.

        Args:
            policy: Policy to register

        Raises:
            ValueError: If policy name already exists
        """
        if policy.name in self._policies:
            raise ValueError(f"Policy '{policy.name}' already registered")

        self._policies[policy.name] = policy

    def get(self, name: str) -> Policy:
        """Get policy by name.

        Args:
            name: Policy name

        Returns:
            Policy instance

        Raises:
            ValueError: If policy not found, with suggestions
        """
        if name in self._policies:
            return self._policies[name]

        # Generate suggestions
        suggestions = difflib.get_close_matches(
            name, self._policies.keys(), n=3, cutoff=0.6
        )

        if suggestions:
            suggestion_text = f" Did you mean: {', '.join(suggestions)}?"
        else:
            suggestion_text = ""

        raise ValueError(f"Policy '{name}' not found.{suggestion_text}")

    def all(self) -> list[Policy]:
        """Get all registered policies in registration order.

        Returns:
            List of all policies
        """
        return list(self._policies.values())

    def clear(self) -> None:
        """Clear all registered policies."""
        self._policies.clear()

__init__()

Initialize empty registry.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
74
75
76
def __init__(self) -> None:
    """Initialize empty registry."""
    self._policies: OrderedDict[str, Policy] = OrderedDict()

all()

Get all registered policies in registration order.

Returns:

Type Description
list[Policy]

List of all policies

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
119
120
121
122
123
124
125
def all(self) -> list[Policy]:
    """Get all registered policies in registration order.

    Returns:
        List of all policies
    """
    return list(self._policies.values())

clear()

Clear all registered policies.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
127
128
129
def clear(self) -> None:
    """Clear all registered policies."""
    self._policies.clear()

get(name)

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def get(self, name: str) -> Policy:
    """Get policy by name.

    Args:
        name: Policy name

    Returns:
        Policy instance

    Raises:
        ValueError: If policy not found, with suggestions
    """
    if name in self._policies:
        return self._policies[name]

    # Generate suggestions
    suggestions = difflib.get_close_matches(
        name, self._policies.keys(), n=3, cutoff=0.6
    )

    if suggestions:
        suggestion_text = f" Did you mean: {', '.join(suggestions)}?"
    else:
        suggestion_text = ""

    raise ValueError(f"Policy '{name}' not found.{suggestion_text}")

register(policy)

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
78
79
80
81
82
83
84
85
86
87
88
89
90
def register(self, policy: Policy) -> None:
    """Register a new policy.

    Args:
        policy: Policy to register

    Raises:
        ValueError: If policy name already exists
    """
    if policy.name in self._policies:
        raise ValueError(f"Policy '{policy.name}' already registered")

    self._policies[policy.name] = policy

ThrottleCfg dataclass

Configuration for throttling policy.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@dataclass(frozen=True)
class ThrottleCfg:
    """Configuration for throttling policy."""

    rate: int
    per: int
    scope: Scope | None = None
    method: str | None = None
    bucket: str | None = None

    def __post_init__(self) -> None:
        """Validate configuration after initialization."""
        if self.rate <= 0:
            raise ValueError("rate must be positive")
        if self.per <= 0:
            raise ValueError("per must be positive")

__post_init__()

Validate configuration after initialization.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
27
28
29
30
31
32
def __post_init__(self) -> None:
    """Validate configuration after initialization."""
    if self.rate <= 0:
        raise ValueError("rate must be positive")
    if self.per <= 0:
        raise ValueError("per must be positive")

coerce_scope(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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def coerce_scope(scope: str | Scope | None) -> Scope | None:
    """Coerce string scope to Scope enum with deprecation warning.

    Args:
        scope: String, Scope enum, or None

    Returns:
        Scope enum or None

    Raises:
        ValueError: If string scope is invalid
    """
    if isinstance(scope, str):
        warnings.warn(
            "String scope is deprecated, use Scope enum",
            DeprecationWarning,
            stacklevel=3,
        )
        try:
            return Scope[scope.upper()]
        except KeyError:
            raise ValueError(f"Invalid scope: {scope}") from None

    return scope

convert_from_legacy_debounce(config)

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def convert_from_legacy_debounce(
    config: tuple[Any, ...] | dict[str, Any],
) -> DebounceCfg:
    """Convert legacy debouncing config to DebounceCfg.

    Args:
        config: Legacy config tuple or dict

    Returns:
        DebounceCfg instance
    """
    if isinstance(config, (tuple, list)) and len(config) >= 1:
        window = config[0]
        scope_str = config[1] if len(config) > 1 else None
        scope = coerce_scope(scope_str) if scope_str else None
        return DebounceCfg(window=window, scope=scope)
    elif isinstance(config, dict):
        window = config.get("delay", config.get("window", 2))
        scope_str = config.get("scope")
        scope = coerce_scope(scope_str) if scope_str else None
        method = config.get("method")
        bucket = config.get("bucket")
        return DebounceCfg(window=window, scope=scope, method=method, bucket=bucket)
    else:
        raise ValueError(f"Invalid legacy debouncing config: {config}")

convert_from_legacy_throttle(config)

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def convert_from_legacy_throttle(
    config: tuple[Any, ...] | dict[str, Any],
) -> ThrottleCfg:
    """Convert legacy throttling config to ThrottleCfg.

    Args:
        config: Legacy config tuple or dict

    Returns:
        ThrottleCfg instance
    """
    if isinstance(config, (tuple, list)) and len(config) >= 2:
        rate, per = config[0], config[1]
        scope_str = config[2] if len(config) > 2 else None
        scope = coerce_scope(scope_str) if scope_str else None
        return ThrottleCfg(rate=rate, per=per, scope=scope)
    elif isinstance(config, dict):
        rate = config.get("limit", config.get("rate", 5))
        per = config.get("window", config.get("per", 10))
        scope_str = config.get("scope")
        scope = coerce_scope(scope_str) if scope_str else None
        method = config.get("method")
        bucket = config.get("bucket")
        return ThrottleCfg(
            rate=rate, per=per, scope=scope, method=method, bucket=bucket
        )
    else:
        raise ValueError(f"Invalid legacy throttling config: {config}")

policy(*names)

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def policy(*names: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
    """Decorator to attach policies to handlers.

    Args:
        *names: Policy names to attach

    Returns:
        Decorator function

    Raises:
        ValueError: If no policy names provided
    """
    if not names:
        raise ValueError("At least one policy name must be provided")

    def decorator(handler: Callable[..., Any]) -> Callable[..., Any]:
        """Attach policies to handler."""
        handler.__sentinel_policies__ = names  # type: ignore
        return handler

    return decorator

resolve_scope(user_id, chat_id, cap)

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def resolve_scope(
    user_id: int | None, chat_id: int | None, cap: Scope | None
) -> Scope | None:
    """Resolve scope with cap constraint.

    Args:
        user_id: User identifier
        chat_id: Chat identifier
        cap: Maximum scope allowed (cap constraint)

    Returns:
        Resolved scope or None if cannot satisfy cap
    """
    # Preserve the historical USER/CHAT/GROUP/GLOBAL specificity order,
    # including invalid-cap errors, without allocating a set and two lists.
    if cap and cap not in (Scope.USER, Scope.CHAT, Scope.GROUP, Scope.GLOBAL):
        raise ValueError(f"{cap!r} is not in list")
    if user_id:
        return Scope.USER
    if chat_id:
        return None if cap == Scope.USER else Scope.CHAT
    return Scope.GLOBAL if not cap or cap == Scope.GLOBAL else None

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def coerce_scope(scope: str | Scope | None) -> Scope | None:
    """Coerce string scope to Scope enum with deprecation warning.

    Args:
        scope: String, Scope enum, or None

    Returns:
        Scope enum or None

    Raises:
        ValueError: If string scope is invalid
    """
    if isinstance(scope, str):
        warnings.warn(
            "String scope is deprecated, use Scope enum",
            DeprecationWarning,
            stacklevel=3,
        )
        try:
            return Scope[scope.upper()]
        except KeyError:
            raise ValueError(f"Invalid scope: {scope}") from None

    return 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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def resolve_scope(
    user_id: int | None, chat_id: int | None, cap: Scope | None
) -> Scope | None:
    """Resolve scope with cap constraint.

    Args:
        user_id: User identifier
        chat_id: Chat identifier
        cap: Maximum scope allowed (cap constraint)

    Returns:
        Resolved scope or None if cannot satisfy cap
    """
    # Preserve the historical USER/CHAT/GROUP/GLOBAL specificity order,
    # including invalid-cap errors, without allocating a set and two lists.
    if cap and cap not in (Scope.USER, Scope.CHAT, Scope.GROUP, Scope.GLOBAL):
        raise ValueError(f"{cap!r} is not in list")
    if user_id:
        return Scope.USER
    if chat_id:
        return None if cap == Scope.USER else Scope.CHAT
    return Scope.GLOBAL if not cap or cap == Scope.GLOBAL else None

Main Classes

Main setup class for aiogram-sentinel.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/sentinel.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
class Sentinel:
    """Main setup class for aiogram-sentinel."""

    _error_config: ErrorConfig | None = None

    @staticmethod
    async def setup(
        dp: Dispatcher,
        cfg: SentinelConfig,
        router: Router | None = None,
        *,
        infra: InfraBundle | None = None,
        error_config: ErrorConfig | None = None,
    ) -> tuple[Router, InfraBundle]:
        """Setup aiogram-sentinel middlewares.

        Args:
            dp: Dispatcher instance
            cfg: Configuration
            router: Optional router to use (creates new one if not provided)
            infra: Optional infrastructure bundle (builds from config if not provided)
            error_config: Optional error handling configuration

        Returns:
            Tuple of (router, infra_bundle)
        """
        if router is not None and (
            router in _installations or router.parent_router is not None
        ):
            raise ConfigurationError("Router is already installed or attached")

        # Build infrastructure if not provided
        if infra is None:
            infra = build_infra(cfg)

        # Create KeyBuilder instance
        key_builder = KeyBuilder(app=cfg.redis_prefix)

        # Create or use provided router
        if router is None:
            router = Router(name="sentinel")

        # Create middlewares in correct order with KeyBuilder
        policy_resolver = PolicyResolverMiddleware(registry, cfg)
        debounce_middleware = DebounceMiddleware(infra.debounce, cfg, key_builder)
        hook = _Hook()
        throttling_middleware = ThrottlingMiddleware(
            infra.rate_limiter, cfg, key_builder, on_rate_limited=hook
        )

        # Create error handling middleware if configured
        error_middleware = None
        effective_error_config = error_config or Sentinel._error_config
        if effective_error_config:
            error_middleware = ErrorHandlingMiddleware(
                effective_error_config, key_builder, infra.rate_limiter
            )

        # Add middlewares to router in correct order
        for reg in (router.message, router.callback_query):
            if error_middleware:
                reg.middleware(error_middleware)  # FIRST (outermost)
            reg.middleware(policy_resolver)
            reg.middleware(debounce_middleware)
            reg.middleware(throttling_middleware)

        # Include router in dispatcher
        dp.include_router(router)
        _installations[router] = _Installation(infra, cfg, hook)
        Sentinel._error_config = None
        attachment_warned = False

        async def check_attachment() -> None:
            nonlocal attachment_warned
            if (
                not any(
                    child.message.handlers or child.callback_query.handlers
                    for child in router.chain_tail
                )
                and not attachment_warned
            ):
                attachment_warned = True
                logger.warning(
                    "Sentinel protected router has no message/callback handlers; "
                    "attach Sentinel to an ancestor of application handlers, "
                    "not a sibling router"
                )

        dp.startup.register(check_attachment)

        return router, infra

    @staticmethod
    def use_errors(error_config: ErrorConfig) -> None:
        """Configure error handling for the next setup call.

        Args:
            error_config: Error handling configuration
        """
        # This is a convenience method that can be used to configure
        # error handling before calling setup()
        Sentinel._error_config = error_config

    @staticmethod
    def add_hooks(
        router: Router,
        infra: InfraBundle,
        cfg: SentinelConfig,
        *,
        on_rate_limited: RateLimitHook | None = None,
    ) -> None:
        """Update this router's owned hook without replacing any middleware.

        The router, infrastructure and configuration must come from the same
        successful ``setup`` call. Passing ``None`` removes the hook.
        """
        installation = _installations.get(router)
        if installation is None:
            raise ConfigurationError("Router was not installed by Sentinel.setup")
        if installation.infra is not infra or installation.cfg is not cfg:
            raise ConfigurationError(
                "Hook configuration does not match router installation"
            )
        installation.hook.callback = on_rate_limited

setup(dp, cfg, router=None, *, infra=None, error_config=None) 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 packages/aiogram-sentinel/src/aiogram_sentinel/sentinel.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@staticmethod
async def setup(
    dp: Dispatcher,
    cfg: SentinelConfig,
    router: Router | None = None,
    *,
    infra: InfraBundle | None = None,
    error_config: ErrorConfig | None = None,
) -> tuple[Router, InfraBundle]:
    """Setup aiogram-sentinel middlewares.

    Args:
        dp: Dispatcher instance
        cfg: Configuration
        router: Optional router to use (creates new one if not provided)
        infra: Optional infrastructure bundle (builds from config if not provided)
        error_config: Optional error handling configuration

    Returns:
        Tuple of (router, infra_bundle)
    """
    if router is not None and (
        router in _installations or router.parent_router is not None
    ):
        raise ConfigurationError("Router is already installed or attached")

    # Build infrastructure if not provided
    if infra is None:
        infra = build_infra(cfg)

    # Create KeyBuilder instance
    key_builder = KeyBuilder(app=cfg.redis_prefix)

    # Create or use provided router
    if router is None:
        router = Router(name="sentinel")

    # Create middlewares in correct order with KeyBuilder
    policy_resolver = PolicyResolverMiddleware(registry, cfg)
    debounce_middleware = DebounceMiddleware(infra.debounce, cfg, key_builder)
    hook = _Hook()
    throttling_middleware = ThrottlingMiddleware(
        infra.rate_limiter, cfg, key_builder, on_rate_limited=hook
    )

    # Create error handling middleware if configured
    error_middleware = None
    effective_error_config = error_config or Sentinel._error_config
    if effective_error_config:
        error_middleware = ErrorHandlingMiddleware(
            effective_error_config, key_builder, infra.rate_limiter
        )

    # Add middlewares to router in correct order
    for reg in (router.message, router.callback_query):
        if error_middleware:
            reg.middleware(error_middleware)  # FIRST (outermost)
        reg.middleware(policy_resolver)
        reg.middleware(debounce_middleware)
        reg.middleware(throttling_middleware)

    # Include router in dispatcher
    dp.include_router(router)
    _installations[router] = _Installation(infra, cfg, hook)
    Sentinel._error_config = None
    attachment_warned = False

    async def check_attachment() -> None:
        nonlocal attachment_warned
        if (
            not any(
                child.message.handlers or child.callback_query.handlers
                for child in router.chain_tail
            )
            and not attachment_warned
        ):
            attachment_warned = True
            logger.warning(
                "Sentinel protected router has no message/callback handlers; "
                "attach Sentinel to an ancestor of application handlers, "
                "not a sibling router"
            )

    dp.startup.register(check_attachment)

    return router, infra

add_hooks(router, infra, cfg, *, on_rate_limited=None) staticmethod

Update this router's owned hook without replacing any middleware.

The router, infrastructure and configuration must come from the same successful setup call. Passing None removes the hook.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/sentinel.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
@staticmethod
def add_hooks(
    router: Router,
    infra: InfraBundle,
    cfg: SentinelConfig,
    *,
    on_rate_limited: RateLimitHook | None = None,
) -> None:
    """Update this router's owned hook without replacing any middleware.

    The router, infrastructure and configuration must come from the same
    successful ``setup`` call. Passing ``None`` removes the hook.
    """
    installation = _installations.get(router)
    if installation is None:
        raise ConfigurationError("Router was not installed by Sentinel.setup")
    if installation.infra is not infra or installation.cfg is not cfg:
        raise ConfigurationError(
            "Hook configuration does not match router installation"
        )
    installation.hook.callback = on_rate_limited

Configuration for aiogram-sentinel.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/config.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
@dataclass
class SentinelConfig:
    """Configuration for aiogram-sentinel."""

    # Backend selection
    backend: Literal["memory", "redis"] = "memory"

    # Redis configuration (used when backend="redis")
    redis_url: str = "redis://localhost:6379"
    redis_prefix: str = "sentinel"

    # Rate limiting defaults
    throttling_default_max: int = 5
    throttling_default_per_seconds: int = 10

    # Debouncing defaults
    debounce_default_window: int = 2

    # Auth configuration
    require_registration: bool = False

    # Explicit opt-ins: existing shared/default behavior stays unchanged.
    action_policies: Mapping[ActionKind, ActionPolicy] = field(
        default_factory=lambda: dict[ActionKind, ActionPolicy]()
    )
    bucket_mode: Literal["shared", "action_kind"] = "shared"
    exemptions: SentinelExemptions = field(default_factory=SentinelExemptions)

    engine: Literal["python", "rust"] = "python"

    # Internal settings
    _validated: bool = field(default=False, init=False)

    def __post_init__(self) -> None:
        """Validate configuration after initialization."""
        self._validate()
        self._validated = True

    def _validate(self) -> None:
        """Validate configuration values."""
        if self.backend not in ("memory", "redis"):
            raise ConfigurationError(f"Invalid backend: {self.backend}")

        if self.backend == "redis" and not self.redis_url:
            raise ConfigurationError("redis_url is required when backend='redis'")

        if self.throttling_default_max <= 0:
            raise ConfigurationError("throttling_default_max must be positive")

        if self.throttling_default_per_seconds <= 0:
            raise ConfigurationError("throttling_default_per_seconds must be positive")

        if self.debounce_default_window <= 0:
            raise ConfigurationError("debounce_default_window must be positive")

        validate_engine(self.engine)

        if self.bucket_mode not in ("shared", "action_kind"):
            raise ConfigurationError("bucket_mode must be shared or action_kind")
        if not isinstance(cast(object, self.exemptions), SentinelExemptions):
            raise ConfigurationError("exemptions must be SentinelExemptions")
        if not isinstance(cast(object, self.action_policies), Mapping):
            raise ConfigurationError("action_policies must be a mapping")
        if any(
            kind not in ("message", "command", "callback_query")
            or not isinstance(cast(object, policy), ActionPolicy)
            for kind, policy in self.action_policies.items()
        ):
            raise ConfigurationError("Invalid action policy mapping")
        self.action_policies = MappingProxyType(dict(self.action_policies))

    def is_redis_backend(self) -> bool:
        """Check if Redis backend is configured."""
        return self.backend == "redis"

    def is_memory_backend(self) -> bool:
        """Check if memory backend is configured."""
        return self.backend == "memory"

throttling_default_max = 5 class-attribute instance-attribute

throttling_default_per_seconds = 10 class-attribute instance-attribute

debounce_default_window = 2 class-attribute instance-attribute

backend = 'memory' class-attribute instance-attribute

redis_url = 'redis://localhost:6379' class-attribute instance-attribute

redis_prefix = 'sentinel' class-attribute instance-attribute

__init__(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, action_policies=(lambda: dict[ActionKind, ActionPolicy]())(), bucket_mode='shared', exemptions=SentinelExemptions(), engine='python')

Bundle of infrastructure backends managed by the library.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/types.py
13
14
15
16
17
18
19
20
21
22
23
24
25
@dataclass
class InfraBundle:
    """Bundle of infrastructure backends managed by the library."""

    rate_limiter: RateLimiterBackend
    debounce: DebounceBackend

    def __post_init__(self) -> None:
        """Validate that all infrastructure backends are provided."""
        if not self.rate_limiter:
            raise ValueError("rate_limiter backend is required")
        if not self.debounce:
            raise ValueError("debounce backend is required")

Bases: Protocol

Protocol for rate limiting storage backend.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/storage/base.py
10
11
12
13
14
15
16
17
18
19
20
@runtime_checkable
class RateLimiterBackend(Protocol):
    """Protocol for rate limiting storage backend."""

    async def allow(self, key: str, max_events: int, per_seconds: int) -> bool:
        """Check if request is allowed and increment counter."""
        ...

    async def get_remaining(self, key: str, max_events: int, per_seconds: int) -> int:
        """Get remaining requests in current window."""
        ...

allow(key, max_events, per_seconds) async

Check if request is allowed and increment counter.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/storage/base.py
14
15
16
async def allow(self, key: str, max_events: int, per_seconds: int) -> bool:
    """Check if request is allowed and increment counter."""
    ...

Composite key builder with collision-proof scheme.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/scopes.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
class KeyBuilder:
    """Composite key builder with collision-proof scheme."""

    def __init__(self, app: str, sep: str = ":") -> None:
        """Initialize KeyBuilder.

        Args:
            app: Application prefix (typically from redis_prefix config)
            sep: Key separator character
        """
        if not app:
            raise ValueError("app cannot be empty")
        if sep in app:
            raise ValueError(f"app cannot contain separator '{sep}': {app}")

        self.app = app
        self.sep = sep

    def for_update(
        self,
        parts: KeyParts,
        *,
        method: str | None = None,
        bucket: str | None = None,
    ) -> str:
        """Build canonical key for storage/metrics with stable ordering.

        Args:
            parts: Key parts containing namespace, scope, and identifiers
            method: Optional method name (e.g., "sendMessage")
            bucket: Optional bucket identifier

        Returns:
            Canonical key string

        Raises:
            ValueError: If method or bucket contain separator characters
        """
        # Validate optional parameters
        if method is not None and self.sep in method:
            raise ValueError(f"method cannot contain separator '{self.sep}': {method}")
        if bucket is not None and self.sep in bucket:
            raise ValueError(f"bucket cannot contain separator '{self.sep}': {bucket}")

        # Build key components
        key_parts = [self.app, parts.namespace, parts.scope.name]

        # Add identifiers
        key_parts.extend(parts.identifiers)

        # Add optional method parameter
        if method is not None:
            key_parts.append(f"m={method}")

        # Add optional bucket parameter
        if bucket is not None:
            key_parts.append(f"b={bucket}")

        return self.sep.join(key_parts)

    def _convenience(
        self, namespace: str, scope: Scope, identifiers: tuple[str, ...], **kwargs: Any
    ) -> str:
        # Preserve subclass for_update overrides. The common concrete builder
        # avoids allocating a temporary frozen dataclass on every update.
        if type(self) is not KeyBuilder:
            return self.for_update(KeyParts(namespace, scope, identifiers), **kwargs)
        if not namespace:
            raise ValueError("namespace cannot be empty")
        for identifier in identifiers:
            if not identifier:
                raise ValueError("identifier cannot be empty")
            if ":" in identifier:
                raise ValueError(
                    f"identifier cannot contain separator ':': {identifier}"
                )
        return self._join(namespace, scope, identifiers, **kwargs)

    def _join(
        self,
        namespace: str,
        scope: Scope,
        identifiers: tuple[str, ...],
        *,
        method: str | None = None,
        bucket: str | None = None,
    ) -> str:
        if method is not None and self.sep in method:
            raise ValueError(f"method cannot contain separator '{self.sep}': {method}")
        if bucket is not None and self.sep in bucket:
            raise ValueError(f"bucket cannot contain separator '{self.sep}': {bucket}")
        components = [self.app, namespace, scope.name, *identifiers]
        if method is not None:
            components.append(f"m={method}")
        if bucket is not None:
            components.append(f"b={bucket}")
        return self.sep.join(components)

    def user(self, namespace: str, user_id: int, **kwargs: Any) -> str:
        """Build key for user scope.

        Args:
            namespace: Key namespace (e.g., "throttle", "debounce")
            user_id: User identifier
            **kwargs: Additional parameters (method, bucket)

        Returns:
            User-scoped key
        """
        return self._convenience(namespace, Scope.USER, (str(user_id),), **kwargs)

    def chat(self, namespace: str, chat_id: int, **kwargs: Any) -> str:
        """Build key for chat scope.

        Args:
            namespace: Key namespace (e.g., "throttle", "debounce")
            chat_id: Chat identifier
            **kwargs: Additional parameters (method, bucket)

        Returns:
            Chat-scoped key
        """
        return self._convenience(namespace, Scope.CHAT, (str(chat_id),), **kwargs)

    def group(self, namespace: str, user_id: int, chat_id: int, **kwargs: Any) -> str:
        """Build key for group scope (user+chat composite).

        Args:
            namespace: Key namespace (e.g., "throttle", "debounce")
            user_id: User identifier
            chat_id: Chat identifier
            **kwargs: Additional parameters (method, bucket)

        Returns:
            Group-scoped key
        """
        return self._convenience(
            namespace, Scope.GROUP, (str(user_id), str(chat_id)), **kwargs
        )

    def global_(self, namespace: str, **kwargs: Any) -> str:
        """Build key for global scope.

        Args:
            namespace: Key namespace (e.g., "throttle", "debounce")
            **kwargs: Additional parameters (method, bucket)

        Returns:
            Global-scoped key
        """
        return self._convenience(namespace, Scope.GLOBAL, ("global",), **kwargs)

__init__(app, sep=':')

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 packages/aiogram-sentinel/src/aiogram_sentinel/scopes.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def __init__(self, app: str, sep: str = ":") -> None:
    """Initialize KeyBuilder.

    Args:
        app: Application prefix (typically from redis_prefix config)
        sep: Key separator character
    """
    if not app:
        raise ValueError("app cannot be empty")
    if sep in app:
        raise ValueError(f"app cannot contain separator '{sep}': {app}")

    self.app = app
    self.sep = sep

for_update(parts, *, method=None, bucket=None)

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 packages/aiogram-sentinel/src/aiogram_sentinel/scopes.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def for_update(
    self,
    parts: KeyParts,
    *,
    method: str | None = None,
    bucket: str | None = None,
) -> str:
    """Build canonical key for storage/metrics with stable ordering.

    Args:
        parts: Key parts containing namespace, scope, and identifiers
        method: Optional method name (e.g., "sendMessage")
        bucket: Optional bucket identifier

    Returns:
        Canonical key string

    Raises:
        ValueError: If method or bucket contain separator characters
    """
    # Validate optional parameters
    if method is not None and self.sep in method:
        raise ValueError(f"method cannot contain separator '{self.sep}': {method}")
    if bucket is not None and self.sep in bucket:
        raise ValueError(f"bucket cannot contain separator '{self.sep}': {bucket}")

    # Build key components
    key_parts = [self.app, parts.namespace, parts.scope.name]

    # Add identifiers
    key_parts.extend(parts.identifiers)

    # Add optional method parameter
    if method is not None:
        key_parts.append(f"m={method}")

    # Add optional bucket parameter
    if bucket is not None:
        key_parts.append(f"b={bucket}")

    return self.sep.join(key_parts)

user(namespace, user_id, **kwargs)

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 packages/aiogram-sentinel/src/aiogram_sentinel/scopes.py
145
146
147
148
149
150
151
152
153
154
155
156
def user(self, namespace: str, user_id: int, **kwargs: Any) -> str:
    """Build key for user scope.

    Args:
        namespace: Key namespace (e.g., "throttle", "debounce")
        user_id: User identifier
        **kwargs: Additional parameters (method, bucket)

    Returns:
        User-scoped key
    """
    return self._convenience(namespace, Scope.USER, (str(user_id),), **kwargs)

chat(namespace, chat_id, **kwargs)

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 packages/aiogram-sentinel/src/aiogram_sentinel/scopes.py
158
159
160
161
162
163
164
165
166
167
168
169
def chat(self, namespace: str, chat_id: int, **kwargs: Any) -> str:
    """Build key for chat scope.

    Args:
        namespace: Key namespace (e.g., "throttle", "debounce")
        chat_id: Chat identifier
        **kwargs: Additional parameters (method, bucket)

    Returns:
        Chat-scoped key
    """
    return self._convenience(namespace, Scope.CHAT, (str(chat_id),), **kwargs)

group(namespace, user_id, chat_id, **kwargs)

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 packages/aiogram-sentinel/src/aiogram_sentinel/scopes.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def group(self, namespace: str, user_id: int, chat_id: int, **kwargs: Any) -> str:
    """Build key for group scope (user+chat composite).

    Args:
        namespace: Key namespace (e.g., "throttle", "debounce")
        user_id: User identifier
        chat_id: Chat identifier
        **kwargs: Additional parameters (method, bucket)

    Returns:
        Group-scoped key
    """
    return self._convenience(
        namespace, Scope.GROUP, (str(user_id), str(chat_id)), **kwargs
    )

global_(namespace, **kwargs)

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 packages/aiogram-sentinel/src/aiogram_sentinel/scopes.py
187
188
189
190
191
192
193
194
195
196
197
def global_(self, namespace: str, **kwargs: Any) -> str:
    """Build key for global scope.

    Args:
        namespace: Key namespace (e.g., "throttle", "debounce")
        **kwargs: Additional parameters (method, bucket)

    Returns:
        Global-scoped key
    """
    return self._convenience(namespace, Scope.GLOBAL, ("global",), **kwargs)

Immutable key parts for consistent key generation.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/scopes.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@dataclass(frozen=True)
class KeyParts:
    """Immutable key parts for consistent key generation."""

    namespace: str
    scope: Scope
    identifiers: tuple[str, ...]

    def __post_init__(self) -> None:
        """Validate key parts after initialization."""
        if not self.namespace:
            raise ValueError("namespace cannot be empty")
        if not self.identifiers:
            raise ValueError("identifiers cannot be empty")

        # Validate identifiers don't contain separator characters
        for identifier in self.identifiers:
            if not identifier:
                raise ValueError("identifier cannot be empty")
            if ":" in identifier:
                raise ValueError(
                    f"identifier cannot contain separator ':': {identifier}"
                )

namespace instance-attribute

scope instance-attribute

identifiers instance-attribute

Bases: Enum

Scope enumeration for key generation.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/scopes.py
13
14
15
16
17
18
19
class Scope(Enum):
    """Scope enumeration for key generation."""

    USER = "user"
    CHAT = "chat"
    GROUP = "group"  # user+chat composite
    GLOBAL = "global"

USER = 'user' class-attribute instance-attribute

CHAT = 'chat' class-attribute instance-attribute

GROUP = 'group' class-attribute instance-attribute

GLOBAL = 'global' class-attribute instance-attribute

Context Extractors

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 packages/aiogram-sentinel/src/aiogram_sentinel/context.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def extract_user_id(event: TelegramObject, data: dict[str, Any]) -> int | None:
    """Extract user ID from event with fallbacks.

    Args:
        event: Telegram event object
        data: Middleware data dictionary

    Returns:
        User ID if found, None otherwise
    """
    # Try from_user attribute (most common)
    if hasattr(event, "from_user") and getattr(event, "from_user", None):  # type: ignore[attr-defined]
        return getattr(event.from_user, "id", None)  # type: ignore[attr-defined]

    # Try user attribute (some event types)
    if hasattr(event, "user") and getattr(event, "user", None):  # type: ignore[attr-defined]
        return getattr(event.user, "id", None)  # type: ignore[attr-defined]

    # Try chat attribute as fallback (for anonymous events)
    if hasattr(event, "chat") and getattr(event, "chat", None):  # type: ignore[attr-defined]
        chat_id = getattr(event.chat, "id", None)  # type: ignore[attr-defined]
        # Only return chat ID if it's a private chat (user ID == chat ID)
        # and it's positive (not a group/supergroup)
        if chat_id and chat_id > 0 and getattr(event.chat, "type", None) == "private":  # type: ignore[attr-defined]
            return chat_id

    return None

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 packages/aiogram-sentinel/src/aiogram_sentinel/context.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def extract_chat_id(event: TelegramObject, data: dict[str, Any]) -> int | None:
    """Extract chat ID from event.

    Args:
        event: Telegram event object
        data: Middleware data dictionary

    Returns:
        Chat ID if found, None otherwise
    """
    # Try chat attribute
    if hasattr(event, "chat") and getattr(event, "chat", None):  # type: ignore[attr-defined]
        return getattr(event.chat, "id", None)  # type: ignore[attr-defined]

    # Try message attribute (for some event types)
    if hasattr(event, "message") and getattr(event, "message", None):
        message = getattr(event, "message", None)
        if message and hasattr(message, "chat") and getattr(message, "chat", None):
            return getattr(message.chat, "id", None)

    return None

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 packages/aiogram-sentinel/src/aiogram_sentinel/context.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def extract_group_ids(
    event: TelegramObject, data: dict[str, Any]
) -> tuple[int | None, int | None]:
    """Extract both user and chat IDs for group scope.

    Args:
        event: Telegram event object
        data: Middleware data dictionary

    Returns:
        Tuple of (user_id, chat_id)
    """
    user_id = extract_user_id(event, data)
    chat_id = extract_chat_id(event, data)
    return user_id, chat_id

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 packages/aiogram-sentinel/src/aiogram_sentinel/context.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def extract_event_type(event: TelegramObject, data: dict[str, Any]) -> str:
    """Extract event type for classification.

    Args:
        event: Telegram event object
        data: Middleware data dictionary

    Returns:
        Event type string
    """
    # Get class name and convert to lowercase
    event_type = event.__class__.__name__.lower()

    # Map specific event types to more readable names

    return _EVENT_TYPES.get(event_type, event_type)

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 packages/aiogram-sentinel/src/aiogram_sentinel/context.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def extract_handler_bucket(event: TelegramObject, data: dict[str, Any]) -> str | None:
    """Extract handler bucket from event and data.

    Args:
        event: Telegram event object
        data: Middleware data dictionary

    Returns:
        Handler bucket string if found, None otherwise
    """
    # Try to get handler name from data
    if "handler" in data:
        handler = data["handler"]
        if hasattr(handler, "__name__"):
            return handler.__name__

    # Try to get handler from event attributes
    if hasattr(event, "handler") and getattr(event, "handler", None):
        handler = getattr(event, "handler", None)
        if handler and hasattr(handler, "__name__"):
            return handler.__name__

    return None

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 packages/aiogram-sentinel/src/aiogram_sentinel/context.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def extract_callback_bucket(event: TelegramObject, data: dict[str, Any]) -> str | None:
    """Extract callback bucket from callback query events.

    Args:
        event: Telegram event object
        data: Middleware data dictionary

    Returns:
        Callback bucket string if found, None otherwise
    """
    # Only process callback query events
    if not hasattr(event, "data"):
        return None

    callback_data = getattr(event, "data", None)
    if callback_data is None:
        return None

    # Convert to string if not already
    callback_data = str(callback_data)

    # Handle empty string case
    if not callback_data:
        return ""

    # Parse callback data to extract action
    # Common patterns: "action:param", "action_param", "action"
    if ":" in callback_data:
        return callback_data.split(":", 1)[0]
    elif "_" in callback_data and len(callback_data.split("_")) > 2:
        # Only split on underscore if there are multiple parts
        return callback_data.split("_", 1)[0]
    else:
        return callback_data

Middleware

Bases: BaseMiddleware

Middleware for rate limiting with optional notifier hook.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/throttling.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
class ThrottlingMiddleware(BaseMiddleware):
    """Middleware for rate limiting with optional notifier hook."""

    def __init__(
        self,
        rate_limiter: RateLimiterBackend,
        cfg: SentinelConfig,
        key_builder: KeyBuilder,
        on_rate_limited: (
            Callable[[TelegramObject, dict[str, Any], float], Awaitable[None]] | None
        ) = None,
    ) -> None:
        """Initialize the throttling middleware.

        Args:
            rate_limiter: Rate limiter backend instance
            cfg: SentinelConfig configuration
            key_builder: KeyBuilder instance for key generation
            on_rate_limited: Optional hook called when rate limit is exceeded
        """
        super().__init__()
        self._rate_limiter = rate_limiter
        self._cfg = cfg
        self._key_builder = key_builder
        self._on_rate_limited = on_rate_limited
        self._default_limit = cfg.throttling_default_max
        self._default_window = cfg.throttling_default_per_seconds

    async def __call__(
        self,
        handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
        event: TelegramObject,
        data: dict[str, Any],
    ) -> Any:
        """Process the event through throttling middleware."""
        if data.get("sentinel_exempt") is True or self._cfg.exemptions.matches(event):
            return await handler(event, data)
        # Get rate limit configuration from handler or use defaults
        max_events, per_seconds = self._get_rate_limit_config(handler, data, event)

        # Generate rate limit key
        key = self._generate_rate_limit_key(event, handler, data)

        # Check if request is allowed
        allowed = await self._rate_limiter.allow(key, max_events, per_seconds)

        if not allowed:
            # Rate limit exceeded
            data["sentinel_rate_limited"] = True

            # Calculate retry after time using actual remaining TTL
            retry_after = await self._calculate_retry_after(key, per_seconds)

            # Call optional hook
            if self._on_rate_limited:
                try:
                    await self._on_rate_limited(event, data, retry_after)
                except Exception as e:
                    logger.exception("on_rate_limited hook failed: %s", e)

            # Stop processing
            return

        # Continue to next middleware/handler
        return await handler(event, data)

    def _get_rate_limit_config(
        self,
        handler: Callable[..., Any],
        data: dict[str, Any],
        event: TelegramObject | None = None,
    ) -> tuple[int, int]:
        """Get rate limit configuration from handler or use defaults."""
        # Check for policy-based configuration first
        if "sentinel_throttle_cfg" in data:
            cfg = data["sentinel_throttle_cfg"]
            if isinstance(cfg, ThrottleCfg):
                # Check if scope cap can be satisfied
                from ..context import extract_group_ids

                # Use event parameter or fallback to data event, but ensure it's not None
                event_obj = event or data.get("event")
                if event_obj is None:
                    # No event available, skip policy config
                    logger.debug(
                        "Policy skipped: no event available for scope resolution",
                        extra={
                            "cap": cfg.scope.value if cfg.scope else None,
                            "handler": getattr(handler, "__name__", "unknown"),
                        },
                    )
                    # Fall through to check other config sources
                else:
                    user_id, chat_id = extract_group_ids(event_obj, data)
                    resolved_scope = resolve_scope(user_id, chat_id, cfg.scope)

                    if resolved_scope is None:
                        # Scope cap cannot be satisfied, skip policy config
                        logger.debug(
                            "Policy skipped: required scope identifiers missing",
                            extra={
                                "cap": cfg.scope.value if cfg.scope else None,
                                "user_id": user_id,
                                "chat_id": chat_id,
                                "handler": getattr(handler, "__name__", "unknown"),
                            },
                        )
                        # Fall through to check other config sources
                    else:
                        return cfg.rate, cfg.per

        # Check if handler has rate limit configuration
        if hasattr(handler, "sentinel_rate_limit"):  # type: ignore
            config = handler.sentinel_rate_limit  # type: ignore
            if isinstance(config, (tuple, list)) and len(config) >= 2:  # type: ignore
                return int(config[0]), int(config[1])  # type: ignore
            elif isinstance(config, dict):
                limit = config.get("limit", self._cfg.throttling_default_max)  # type: ignore
                window = config.get("window", self._cfg.throttling_default_per_seconds)  # type: ignore
                return int(limit), int(window)  # type: ignore

        # Check data for rate limit configuration
        if "sentinel_rate_limit" in data:
            config = data["sentinel_rate_limit"]
            if isinstance(config, tuple) and len(config) >= 2:  # type: ignore
                return int(config[0]), int(config[1])  # type: ignore

        # Use defaults
        return (
            self._cfg.throttling_default_max,
            self._cfg.throttling_default_per_seconds,
        )

    def _generate_rate_limit_key(
        self, event: TelegramObject, handler: Callable[..., Any], data: dict[str, Any]
    ) -> str:
        """Generate rate limit key for the event using KeyBuilder."""
        # Extract user and chat IDs using context extractors
        user_id, chat_id = extract_group_ids(event, data)

        # Auto-extract bucket from handler
        bucket: str | None = extract_handler_bucket(event, data)

        # Get handler name as fallback bucket
        if bucket is None:
            bucket = str(getattr(handler, "__name__", "unknown"))

        # Get additional parameters from policy config, handler config, or data
        method: str | None = None
        explicit_bucket: str | None = None
        scope_cap: Scope | None = None

        # Check policy-based configuration first
        if "sentinel_throttle_cfg" in data:
            cfg = data["sentinel_throttle_cfg"]
            if isinstance(cfg, ThrottleCfg):
                method = cfg.method
                explicit_bucket = cfg.bucket
                scope_cap = cfg.scope

        # Check handler configuration for overrides (if no policy config)
        if method is None and explicit_bucket is None and scope_cap is None:
            if hasattr(handler, "sentinel_rate_limit"):
                config = getattr(handler, "sentinel_rate_limit", None)
                if isinstance(config, dict):
                    # Legacy handler metadata is an untyped application boundary.
                    metadata = cast(dict[str, Any], config)
                    method = metadata.get("method")
                    explicit_bucket = metadata.get("bucket")

        # Check data for overrides
        if "sentinel_method" in data:
            method = data["sentinel_method"]
        if "sentinel_bucket" in data:
            explicit_bucket = data["sentinel_bucket"]

        # Use explicit bucket if provided, otherwise use auto-extracted
        final_bucket: str | None = (
            explicit_bucket if explicit_bucket is not None else bucket
        )
        namespace = "throttle"
        if self._cfg.bucket_mode == "action_kind":
            namespace = f"throttle.{classify_action(event)}"

        # Resolve scope with cap constraint
        resolved_scope = resolve_scope(user_id, chat_id, scope_cap)

        if resolved_scope is None:
            # Cannot satisfy scope cap - log debug and skip throttling
            logger.debug(
                "Policy skipped: required scope identifiers missing",
                extra={
                    "cap": scope_cap.value if scope_cap else None,
                    "user_id": user_id,
                    "chat_id": chat_id,
                    "handler": getattr(handler, "__name__", "unknown"),
                },
            )
            # Return a dummy key that will pass throttling
            return self._key_builder.global_(
                namespace, method=method, bucket=final_bucket
            )

        # Build key based on resolved scope
        if (
            resolved_scope == Scope.GROUP
            and user_id is not None
            and chat_id is not None
        ):
            return self._key_builder.group(
                namespace, user_id, chat_id, method=method, bucket=final_bucket
            )
        elif resolved_scope == Scope.USER and user_id is not None:
            return self._key_builder.user(
                namespace, user_id, method=method, bucket=final_bucket
            )
        elif resolved_scope == Scope.CHAT and chat_id is not None:
            return self._key_builder.chat(
                namespace, chat_id, method=method, bucket=final_bucket
            )
        else:  # Scope.GLOBAL
            return self._key_builder.global_(
                namespace, method=method, bucket=final_bucket
            )

    async def _calculate_retry_after(self, key: str, window: int) -> float:
        """Calculate retry after time in seconds using actual remaining TTL."""
        # Get remaining requests to calculate when the window will reset
        remaining = await self._rate_limiter.get_remaining(key, 1, window)

        # If no remaining requests, calculate time until oldest request expires
        if remaining == 0:
            # For memory backend, we need to check the actual timestamps
            # For Redis backend, we can use TTL
            if hasattr(self._rate_limiter, "_redis"):
                # Redis backend - use TTL
                try:
                    ttl = await self._rate_limiter._redis.ttl(key)  # type: ignore
                    return max(0, float(ttl)) if ttl > 0 else float(window)  # type: ignore
                except Exception:
                    return float(window)
            else:
                # Memory backend - estimate based on window
                return float(window)

        # If there are remaining requests, the window is not full
        return 0.0

__call__(handler, event, data) async

Process the event through throttling middleware.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/throttling.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
async def __call__(
    self,
    handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
    event: TelegramObject,
    data: dict[str, Any],
) -> Any:
    """Process the event through throttling middleware."""
    if data.get("sentinel_exempt") is True or self._cfg.exemptions.matches(event):
        return await handler(event, data)
    # Get rate limit configuration from handler or use defaults
    max_events, per_seconds = self._get_rate_limit_config(handler, data, event)

    # Generate rate limit key
    key = self._generate_rate_limit_key(event, handler, data)

    # Check if request is allowed
    allowed = await self._rate_limiter.allow(key, max_events, per_seconds)

    if not allowed:
        # Rate limit exceeded
        data["sentinel_rate_limited"] = True

        # Calculate retry after time using actual remaining TTL
        retry_after = await self._calculate_retry_after(key, per_seconds)

        # Call optional hook
        if self._on_rate_limited:
            try:
                await self._on_rate_limited(event, data, retry_after)
            except Exception as e:
                logger.exception("on_rate_limited hook failed: %s", e)

        # Stop processing
        return

    # Continue to next middleware/handler
    return await handler(event, data)

__init__(rate_limiter, cfg, key_builder, on_rate_limited=None)

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 packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/throttling.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def __init__(
    self,
    rate_limiter: RateLimiterBackend,
    cfg: SentinelConfig,
    key_builder: KeyBuilder,
    on_rate_limited: (
        Callable[[TelegramObject, dict[str, Any], float], Awaitable[None]] | None
    ) = None,
) -> None:
    """Initialize the throttling middleware.

    Args:
        rate_limiter: Rate limiter backend instance
        cfg: SentinelConfig configuration
        key_builder: KeyBuilder instance for key generation
        on_rate_limited: Optional hook called when rate limit is exceeded
    """
    super().__init__()
    self._rate_limiter = rate_limiter
    self._cfg = cfg
    self._key_builder = key_builder
    self._on_rate_limited = on_rate_limited
    self._default_limit = cfg.throttling_default_max
    self._default_window = cfg.throttling_default_per_seconds

Bases: BaseMiddleware

Middleware for debouncing duplicate messages with fingerprinting.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/debouncing.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
class DebounceMiddleware(BaseMiddleware):
    """Middleware for debouncing duplicate messages with fingerprinting."""

    def __init__(
        self,
        debounce_backend: DebounceBackend,
        cfg: SentinelConfig,
        key_builder: KeyBuilder,
    ) -> None:
        """Initialize the debouncing middleware.

        Args:
            debounce_backend: Debounce backend instance
            cfg: SentinelConfig configuration
            key_builder: KeyBuilder instance for key generation
        """
        super().__init__()
        self._debounce_backend = debounce_backend
        self._cfg = cfg
        self._key_builder = key_builder
        self._default_delay = cfg.debounce_default_window

    async def __call__(
        self,
        handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
        event: TelegramObject,
        data: dict[str, Any],
    ) -> Any:
        """Process the event through debouncing middleware."""
        if data.get("sentinel_exempt") is True or self._cfg.exemptions.matches(event):
            return await handler(event, data)
        # Get debounce configuration
        window_seconds = self._get_debounce_window(handler, data, event)

        # Generate fingerprint for the event
        fp = self._generate_fingerprint(event)

        # Generate debounce key
        key = self._generate_debounce_key(event, handler, data)

        # Check if already seen within window
        if await self._debounce_backend.seen(key, window_seconds, fp):
            # Duplicate detected within window
            data["sentinel_debounced"] = True
            return  # Stop processing

        # Continue to next middleware/handler
        return await handler(event, data)

    def _get_debounce_window(
        self,
        handler: Callable[..., Any],
        data: dict[str, Any],
        event: TelegramObject | None = None,
    ) -> int:
        """Get debounce window from handler or use default."""
        # Check for policy-based configuration first
        if "sentinel_debounce_cfg" in data:
            cfg = data["sentinel_debounce_cfg"]
            if isinstance(cfg, DebounceCfg):
                # Check if scope cap can be satisfied
                from ..context import extract_group_ids

                # Use event parameter or fallback to data event, but ensure it's not None
                event_obj = event or data.get("event")
                if event_obj is None:
                    # No event available, skip policy config
                    logger.debug(
                        "Policy skipped: no event available for scope resolution",
                        extra={
                            "cap": cfg.scope.value if cfg.scope else None,
                            "handler": getattr(handler, "__name__", "unknown"),
                        },
                    )
                    # Fall through to check other config sources
                else:
                    user_id, chat_id = extract_group_ids(event_obj, data)
                    resolved_scope = resolve_scope(user_id, chat_id, cfg.scope)

                    if resolved_scope is None:
                        # Scope cap cannot be satisfied, skip policy config
                        logger.debug(
                            "Policy skipped: required scope identifiers missing",
                            extra={
                                "cap": cfg.scope.value if cfg.scope else None,
                                "user_id": user_id,
                                "chat_id": chat_id,
                                "handler": getattr(handler, "__name__", "unknown"),
                            },
                        )
                        # Fall through to check other config sources
                    else:
                        return cfg.window

        # Check if handler has debounce configuration
        if hasattr(handler, "sentinel_debounce"):  # type: ignore
            config = handler.sentinel_debounce  # type: ignore
            if isinstance(config, (tuple, list)) and len(config) >= 1:  # type: ignore
                return int(config[0])  # type: ignore
            elif isinstance(config, dict):
                delay = config.get("delay", self._cfg.debounce_default_window)  # type: ignore
                return int(delay)  # type: ignore

        # Check data for debounce configuration
        if "sentinel_debounce" in data:
            config = data["sentinel_debounce"]
            if isinstance(config, tuple) and len(config) >= 1:  # type: ignore
                return int(config[0])  # type: ignore

        # Use default
        return self._cfg.debounce_default_window

    def _generate_fingerprint(self, event: TelegramObject) -> str:
        """Generate SHA256 fingerprint for event content."""
        content = self._extract_content(event)

        if not content:
            # Fallback to hashed representation of the entire event
            content = str(event)

        return fingerprint(content)

    def _extract_content(self, event: TelegramObject) -> str:
        """Extract content from event for fingerprinting."""
        # Try to get text from message
        if hasattr(event, "text") and getattr(event, "text", None):  # type: ignore
            return event.text  # type: ignore

        # Try to get caption from message
        if hasattr(event, "caption") and getattr(event, "caption", None):  # type: ignore
            return event.caption  # type: ignore

        # Try to get data from callback query
        if hasattr(event, "data") and getattr(event, "data", None):  # type: ignore
            return event.data  # type: ignore

        # Try to get query from inline query
        if hasattr(event, "query") and getattr(event, "query", None):  # type: ignore
            return event.query  # type: ignore

        # Return empty string if no content found
        return ""

    def _generate_debounce_key(
        self,
        event: TelegramObject,
        handler: Callable[..., Any],
        data: dict[str, Any],
    ) -> str:
        """Generate debounce key for the event using KeyBuilder."""
        # Extract user and chat IDs using context extractors
        user_id, chat_id = extract_group_ids(event, data)

        # Auto-extract bucket from handler
        bucket: str | None = extract_handler_bucket(event, data)

        # Get handler name as fallback bucket
        if bucket is None:
            bucket = str(getattr(handler, "__name__", "unknown"))

        # Get additional parameters from policy config, handler config, or data
        method: str | None = None
        explicit_bucket: str | None = None
        scope_cap: Scope | None = None

        # Check policy-based configuration first
        if "sentinel_debounce_cfg" in data:
            cfg = data["sentinel_debounce_cfg"]
            if isinstance(cfg, DebounceCfg):
                method = cfg.method
                explicit_bucket = cfg.bucket
                scope_cap = cfg.scope

        # Check handler configuration for overrides (if no policy config)
        if method is None and explicit_bucket is None and scope_cap is None:
            if hasattr(handler, "sentinel_debounce"):
                config = getattr(handler, "sentinel_debounce", None)
                if isinstance(config, dict):
                    # Legacy handler metadata is an untyped application boundary.
                    metadata = cast(dict[str, Any], config)
                    method = metadata.get("method")
                    explicit_bucket = metadata.get("bucket")

        # Check data for overrides
        if "sentinel_method" in data:
            method = data["sentinel_method"]
        if "sentinel_bucket" in data:
            explicit_bucket = data["sentinel_bucket"]

        # Use explicit bucket if provided, otherwise use auto-extracted
        final_bucket: str | None = (
            explicit_bucket if explicit_bucket is not None else bucket
        )
        namespace = "debounce"
        if self._cfg.bucket_mode == "action_kind":
            namespace = f"debounce.{classify_action(event)}"

        # Resolve scope with cap constraint
        resolved_scope = resolve_scope(user_id, chat_id, scope_cap)
        if resolved_scope is None:
            # Cannot satisfy scope cap - log debug and skip debouncing
            import logging

            logger = logging.getLogger(__name__)
            logger.debug(
                "Policy skipped: required scope identifiers missing",
                extra={
                    "cap": scope_cap.value if scope_cap else None,
                    "user_id": user_id,
                    "chat_id": chat_id,
                    "handler": getattr(handler, "__name__", "unknown"),
                },
            )
            # Return a dummy key that will pass debouncing
            return self._key_builder.global_(
                namespace, method=method, bucket=final_bucket
            )

        # Build key based on resolved scope
        if (
            resolved_scope == Scope.GROUP
            and user_id is not None
            and chat_id is not None
        ):
            return self._key_builder.group(
                namespace, user_id, chat_id, method=method, bucket=final_bucket
            )
        elif resolved_scope == Scope.USER and user_id is not None:
            return self._key_builder.user(
                namespace, user_id, method=method, bucket=final_bucket
            )
        elif resolved_scope == Scope.CHAT and chat_id is not None:
            return self._key_builder.chat(
                namespace, chat_id, method=method, bucket=final_bucket
            )
        else:  # Scope.GLOBAL
            return self._key_builder.global_(
                namespace, method=method, bucket=final_bucket
            )

__call__(handler, event, data) async

Process the event through debouncing middleware.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/debouncing.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
async def __call__(
    self,
    handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
    event: TelegramObject,
    data: dict[str, Any],
) -> Any:
    """Process the event through debouncing middleware."""
    if data.get("sentinel_exempt") is True or self._cfg.exemptions.matches(event):
        return await handler(event, data)
    # Get debounce configuration
    window_seconds = self._get_debounce_window(handler, data, event)

    # Generate fingerprint for the event
    fp = self._generate_fingerprint(event)

    # Generate debounce key
    key = self._generate_debounce_key(event, handler, data)

    # Check if already seen within window
    if await self._debounce_backend.seen(key, window_seconds, fp):
        # Duplicate detected within window
        data["sentinel_debounced"] = True
        return  # Stop processing

    # Continue to next middleware/handler
    return await handler(event, data)

__init__(debounce_backend, cfg, key_builder)

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 packages/aiogram-sentinel/src/aiogram_sentinel/middlewares/debouncing.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def __init__(
    self,
    debounce_backend: DebounceBackend,
    cfg: SentinelConfig,
    key_builder: KeyBuilder,
) -> None:
    """Initialize the debouncing middleware.

    Args:
        debounce_backend: Debounce backend instance
        cfg: SentinelConfig configuration
        key_builder: KeyBuilder instance for key generation
    """
    super().__init__()
    self._debounce_backend = debounce_backend
    self._cfg = cfg
    self._key_builder = key_builder
    self._default_delay = cfg.debounce_default_window

Decorators

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 packages/aiogram-sentinel/src/aiogram_sentinel/decorators.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def rate_limit(
    max_events: int, per_seconds: int, *, scope: str | None = None
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
    """Decorator to set rate limit configuration on handlers.

    Args:
        max_events: Maximum number of events per time window
        per_seconds: Time window in seconds
        scope: Optional scope for rate limiting

    Deprecated:
        Use @policy() with PolicyRegistry instead. Will be removed in v2.0.0.
    """

    def decorator(handler: Callable[..., Any]) -> Callable[..., Any]:
        warnings.warn(
            "@rate_limit is deprecated, use @policy() with PolicyRegistry instead. "
            "Will be removed in v2.0.0",
            DeprecationWarning,
            stacklevel=2,
        )
        # Store rate limit configuration on the handler
        handler.sentinel_rate_limit = (max_events, per_seconds, scope)  # type: ignore
        return handler

    return decorator

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 packages/aiogram-sentinel/src/aiogram_sentinel/decorators.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def debounce(
    window_seconds: int, *, scope: str | None = None
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
    """Decorator to set debounce configuration on handlers.

    Args:
        window_seconds: Debounce window in seconds
        scope: Optional scope for debouncing

    Deprecated:
        Use @policy() with PolicyRegistry instead. Will be removed in v2.0.0.
    """

    def decorator(handler: Callable[..., Any]) -> Callable[..., Any]:
        warnings.warn(
            "@debounce is deprecated, use @policy() with PolicyRegistry instead. "
            "Will be removed in v2.0.0",
            DeprecationWarning,
            stacklevel=2,
        )
        # Store debounce configuration on the handler
        handler.sentinel_debounce = (window_seconds, scope)  # type: ignore
        return handler

    return decorator

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 packages/aiogram-sentinel/src/aiogram_sentinel/policy.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def policy(*names: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
    """Decorator to attach policies to handlers.

    Args:
        *names: Policy names to attach

    Returns:
        Decorator function

    Raises:
        ValueError: If no policy names provided
    """
    if not names:
        raise ValueError("At least one policy name must be provided")

    def decorator(handler: Callable[..., Any]) -> Callable[..., Any]:
        """Attach policies to handler."""
        handler.__sentinel_policies__ = names  # type: ignore
        return handler

    return decorator

Utilities

Key Generation

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 packages/aiogram-sentinel/src/aiogram_sentinel/utils/keys.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def rate_key(user_id: int, handler_name: str, **kwargs: Any) -> str:
    """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)
    """
    # Emit deprecation warning
    warnings.warn(
        "rate_key() is deprecated and will be removed in v2.0.0. "
        "Use KeyBuilder instead.",
        DeprecationWarning,
        stacklevel=2,
    )

    # Log deprecation warning once
    logger.warning(
        "rate_key() is deprecated and will be removed in v2.0.0. "
        "Use KeyBuilder instead."
    )

    # Create a stable key from user_id and handler_name (original implementation)
    key_parts = [str(user_id), handler_name]

    # Add any additional scope parameters
    for key, value in sorted(kwargs.items()):
        key_parts.append(f"{key}:{value}")

    return ":".join(key_parts)

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 packages/aiogram-sentinel/src/aiogram_sentinel/utils/keys.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def debounce_key(user_id: int, handler_name: str, **kwargs: Any) -> str:
    """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)
    """
    # Emit deprecation warning
    warnings.warn(
        "debounce_key() is deprecated and will be removed in v2.0.0. "
        "Use KeyBuilder instead.",
        DeprecationWarning,
        stacklevel=2,
    )

    # Log deprecation warning once
    logger.warning(
        "debounce_key() is deprecated and will be removed in v2.0.0. "
        "Use KeyBuilder instead."
    )

    # Create a stable key from user_id and handler_name (original implementation)
    key_parts = [str(user_id), handler_name]

    # Add any additional scope parameters
    for key, value in sorted(kwargs.items()):
        key_parts.append(f"{key}:{value}")

    return ":".join(key_parts)

Create a stable fingerprint for text content.

Source code in packages/aiogram-sentinel/src/aiogram_sentinel/utils/keys.py
111
112
113
114
115
116
117
118
119
def fingerprint(text: str | None) -> str:
    """Create a stable fingerprint for text content."""
    # Handle None, empty strings, and non-string types
    if not text:
        text = ""
    else:
        text = str(text)

    return hashlib.sha256(text.encode()).hexdigest()[:16]