tempest_fastapi_sdk.alerts¶
Alertas por e-mail de falha crítica: 5xx da API e crash do app, com deduplicação, teto por janela e redação.
AlertNotifier
¶
AlertNotifier(
channel: AlertChannel,
recipients: AlertRecipientsProvider,
*,
enabled: bool = True,
window_seconds: int = DEFAULT_ALERT_WINDOW_SECONDS,
max_per_window: int = DEFAULT_ALERT_MAX_PER_WINDOW,
environment: str | None = None,
backend: ThrottleBackend | None = None,
namespace: str = "alerts",
)
Admit, deduplicate and deliver critical-failure alerts.
Two counters decide whether an alert goes out:
- Per fingerprint — the first occurrence inside
window_secondsis delivered; the rest are counted and reported as :attr:AlertSchema.suppressedon the next delivery of the same fingerprint. - Per source — at most
max_per_windowdeliveries per window across every fingerprint of the same :class:AlertSourceEnum, so an incident that fails a hundred different routes sends twenty e-mails, not a hundred. The ceiling is counted per source on purpose: the app-error endpoint is public, and a shared ceiling would let anyone postingfatalreports with varied codes spend the window and silence the next real API5xx.
The counters live in backend. The default is an in-memory store,
which counts per process: with several workers each one delivers
its own first occurrence. Pass redis.asyncio.Redis (or any
:class:~tempest_fastapi_sdk.utils.throttle.ThrottleBackend) to share
them. When that backend raises, the notifier falls back to its own
in-memory counters instead of either dropping the alert or sending one
e-mail per error: the moment Redis is down is the moment every request
fails.
Nothing here raises. A channel or recipient-source failure is logged
on tempest_fastapi_sdk.alerts and the alert is dropped — the alert
is the side effect of an error and must not become a second one.
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
bool
|
When |
window_seconds |
int
|
Silence window per fingerprint. |
max_per_window |
int
|
Delivery ceiling per window, per source. |
environment |
str | None
|
Stamped on alerts that carry none. |
Initialize the notifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
AlertChannel
|
Delivers the admitted alerts. |
required |
recipients
|
AlertRecipientsProvider
|
Resolves who receives them, once per delivery. |
required |
enabled
|
bool
|
Master switch ( |
True
|
window_seconds
|
int
|
Silence window per fingerprint
( |
DEFAULT_ALERT_WINDOW_SECONDS
|
max_per_window
|
int
|
Ceiling per window, per source
( |
DEFAULT_ALERT_MAX_PER_WINDOW
|
environment
|
str | None
|
Stamped on alerts without one. |
None
|
backend
|
ThrottleBackend | None
|
Shared counter store;
|
None
|
namespace
|
str
|
Key prefix inside |
'alerts'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
notify
async
¶
notify(alert: AlertSchema) -> bool
Deliver alert if deduplication admits it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alert
|
AlertSchema
|
The alert, already redacted. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
was disabled, deduplicated, had no recipients, or failed. |
dispatch
¶
dispatch(alert: AlertSchema) -> None
Schedule :meth:notify without waiting for it.
For a request path that must answer before the e-mail goes out.
The task is kept referenced until it finishes, so the event loop
cannot collect it half-way; :meth:drain waits for the pending
ones (a test, a shutdown hook).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alert
|
AlertSchema
|
The alert, already redacted. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When called outside a running event loop. |
SUPPRESSED_COUNT_TTL_SECONDS
module-attribute
¶
Floor for how long an undelivered count waits for the next delivery.
EmailAlertChannel
¶
EmailAlertChannel(
mailer: AdminMailer, *, subject_prefix: str = DEFAULT_ALERT_SUBJECT_PREFIX
)
Send each alert as one plain-text e-mail.
Plain text on purpose: the body carries an exception message, and rendering it as HTML would turn an attacker-shaped message into markup in an admin's inbox.
Attributes:
| Name | Type | Description |
|---|---|---|
subject_prefix |
str
|
Prepended to every subject. |
Initialize the channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mailer
|
AdminMailer
|
Sends the message —
:class: |
required |
subject_prefix
|
str
|
Prepended to every subject
( |
DEFAULT_ALERT_SUBJECT_PREFIX
|
subject
¶
subject(alert: AlertSchema) -> str
Build the subject line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alert
|
AlertSchema
|
The alert. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
body
¶
body(alert: AlertSchema) -> str
Build the plain-text body.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alert
|
AlertSchema
|
The alert. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Summary, labelled details, held-back count and frames. |
send
async
¶
send(alert: AlertSchema, recipients: Sequence[str]) -> None
E-mail alert to recipients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alert
|
AlertSchema
|
The alert. |
required |
recipients
|
Sequence[str]
|
Addresses. |
required |
AdminMailer
¶
Bases: Protocol
What an SDK component needs from a mailer to write to an admin.
:class:~tempest_fastapi_sdk.EmailUtils satisfies it as is, and so does
:class:~tempest_fastapi_sdk.testing.fakes.FakeEmailUtils. Parameters
are positional-only so an implementation may name them anything.
send
¶
Send one plain-text message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
to
|
list[str]
|
Recipients. |
required |
subject
|
str
|
Subject line. |
required |
body
|
str
|
Plain-text body. |
required |
Returns:
| Type | Description |
|---|---|
Awaitable[None]
|
Awaitable[None]: Completes once the message is handed over. |
AlertChannel
¶
Bases: Protocol
Delivers one alert to a list of recipients.
:class:~tempest_fastapi_sdk.alerts.EmailAlertChannel is the SDK's
implementation. A failure raised here is logged and swallowed by
:class:~tempest_fastapi_sdk.alerts.AlertNotifier: the alert is the
side effect of an error, and must never become a second one.
send
¶
send(alert: AlertSchema, recipients: Sequence[str]) -> Awaitable[None]
Deliver alert.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alert
|
AlertSchema
|
What happened, already redacted. |
required |
recipients
|
Sequence[str]
|
Who to tell. Never empty — the notifier skips the call when nobody is configured. |
required |
Returns:
| Type | Description |
|---|---|
Awaitable[None]
|
Awaitable[None]: Completes once the alert is handed over. |
AlertRecipientsProvider
¶
Bases: Protocol
Resolves who receives an alert, at the moment one is sent.
Called only after deduplication admitted the alert, so a source that
reads the database is queried once per e-mail, not once per error.
See :func:~tempest_fastapi_sdk.alerts.static_recipients and
:func:~tempest_fastapi_sdk.alerts.admin_recipients.
static_recipients
¶
static_recipients(emails: Sequence[str]) -> AlertRecipientsProvider
Recipients fixed at boot, typically ALERT_EMAILS.
Blank entries are dropped and duplicates collapse, keeping the first
spelling, so a trailing comma in the .env costs nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
emails
|
Sequence[str]
|
The addresses. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
AlertRecipientsProvider |
AlertRecipientsProvider
|
A provider that always answers them. |
admin_recipients
¶
admin_recipients(
session_factory: async_sessionmaker[AsyncSession],
user_model: type[BaseUserModel],
*,
extra: Sequence[str] = (),
) -> AlertRecipientsProvider
Recipients read from the user table: every active admin.
Queried once per delivery, after deduplication, so a burst of
errors costs one SELECT per e-mail and a newly promoted admin
starts receiving without a restart. Opens its own session: the alert
runs after the response, when the request's session is gone — or
rolled back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_factory
|
async_sessionmaker[AsyncSession]
|
Opens the session the query runs in. |
required |
user_model
|
type[BaseUserModel]
|
The project's concrete user model. |
required |
extra
|
Sequence[str]
|
Addresses added to the admins, typically
|
()
|
Returns:
| Name | Type | Description |
|---|---|---|
AlertRecipientsProvider |
AlertRecipientsProvider
|
A provider answering the active admins' |
AlertRecipientsProvider
|
e-mails plus |
make_server_error_alert
¶
make_server_error_alert(
notifier: AlertNotifier,
*,
statuses: Collection[int] | None = None,
policy: RedactionPolicy | None = None,
redact_exception: Callable[[BaseException], BaseException] = redact_database_errors,
) -> ServerErrorCallback
Build the on_server_error callback that alerts on a 5xx.
Pass the result to
:func:~tempest_fastapi_sdk.register_exception_handlers as
on_server_error. It runs after the response was sent, and a
failure inside it is logged, never raised — the client's 500 is
already on the wire.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
notifier
|
AlertNotifier
|
Deduplicates and delivers. |
required |
statuses
|
Collection[int] | None
|
Statuses that alert; |
None
|
policy
|
RedactionPolicy | None
|
Scrubs the message. |
None
|
redact_exception
|
Callable[[BaseException], BaseException]
|
Replaces a database error's text before it is read. |
redact_database_errors
|
Returns:
| Name | Type | Description |
|---|---|---|
ServerErrorCallback |
ServerErrorCallback
|
The callback. |
server_error_alert
¶
server_error_alert(
request: Request,
exc: Exception,
*,
policy: RedactionPolicy | None = None,
redact_exception: Callable[[BaseException], BaseException] = redact_database_errors,
) -> AlertSchema
Build the alert for a 5xx the API answered.
The fingerprint is exception type + method + route template, so the same bug on the same route deduplicates, while the same exception on a different route is a different alert.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The failed request. |
required |
exc
|
Exception
|
What the handler received. |
required |
policy
|
RedactionPolicy | None
|
Scrubs the message; |
None
|
redact_exception
|
Callable[[BaseException], BaseException]
|
Replaces a database error's text before it is read. Defaults to
:func: |
redact_database_errors
|
Returns:
| Name | Type | Description |
|---|---|---|
AlertSchema |
AlertSchema
|
The alert. |
app_error_alert
¶
app_error_alert(
report: AppErrorResponseSchema, *, policy: RedactionPolicy | None = None
) -> AlertSchema
Build the alert for a crash report the client application sent.
The fingerprint is platform + code + app version: one defect in one
build. user_id and device_id stay out — the report's id is in
the alert, and the admin listing has the rest behind its own gate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
report
|
AppErrorResponseSchema
|
The stored report. |
required |
policy
|
RedactionPolicy | None
|
Scrubs the message. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
AlertSchema |
AlertSchema
|
The alert. |
fingerprint_of
¶
Hash parts into a short, stable deduplication key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*parts
|
str
|
What identifies "the same failure". |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The first 16 hex digits of the parts' SHA-256. |
frames_of
¶
frames_of(exc: BaseException, limit: int = ALERT_TRACEBACK_MAX_FRAMES) -> list[str]
Summarize a traceback as file:line in function frames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exc
|
BaseException
|
The exception. |
required |
limit
|
int
|
Frames kept, counted from the innermost. |
ALERT_TRACEBACK_MAX_FRAMES
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The frames, innermost last. No source line, no locals. |
route_of
¶
Return the matched route's template, never the concrete path.
/users/{user_id} rather than /users/42: the concrete path holds
identifiers (and sometimes a token), and it would split one defect
into one fingerprint per id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The failed request. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The template, or :data: |
status_of
¶
Read the HTTP status an exception was answered with.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exc
|
Exception
|
What the 5xx handler received. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
|
int
|
|
ALERT_SUMMARY_MAX_LENGTH
module-attribute
¶
Longest summary an alert carries; a stack trace sent as message is cut.
ALERT_TRACEBACK_MAX_FRAMES
module-attribute
¶
Frames kept from the innermost end of a traceback.
UNMATCHED_ROUTE
module-attribute
¶
Route label when the request matched no route (a middleware failed).
AlertSchema
¶
Bases: BaseSchema
One critical failure, already redacted, ready for a channel.
Built by :func:~tempest_fastapi_sdk.alerts.server_error_alert and
:func:~tempest_fastapi_sdk.alerts.app_error_alert; a service may build
its own for a failure the SDK does not see (a task, a consumer).
Nothing here is redacted by the schema itself — whoever builds one
decides what goes in, and the SDK's builders leave out headers, query
string, body, client address and user_id.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
AlertSourceEnum
|
Where it came from. |
fingerprint |
str
|
Deduplication key. Two alerts with the same fingerprint inside one window produce one delivery. |
title |
str
|
One line, used as the e-mail subject. |
summary |
str
|
The redacted error message. |
details |
dict[str, str]
|
Labelled context lines (route, status, request id, report id...). |
traceback |
list[str]
|
|
environment |
str | None
|
The deployment the failure happened in;
filled from the notifier when |
occurred_at |
datetime
|
When the alert was built, UTC. |
suppressed |
int
|
Occurrences of the same fingerprint that were not delivered since the previous delivery. Set by the notifier. |
AlertSourceEnum
¶
Bases: BaseStrEnum
Where a critical failure came from.
Attributes:
| Name | Type | Description |
|---|---|---|
API_SERVER_ERROR |
str
|
A |
APP_ERROR |
str
|
A report the client application sent to
:func: |