Ir para o conteúdo

tempest_fastapi_sdk.app_errors

Erros que o app cliente reporta de volta ao serviço: schema, model e router.

« Integrações e pagamentos


BaseAppErrorModel

Bases: BaseModel

Abstract table for an error reported by a client application.

user_id is declared here so the service and the listing can read it, and re-declared by the concrete subclass with the foreign key: the user table's name belongs to the application, not to the SDK.

Attributes:

Name Type Description
code str

The error code the app emits — a stable identifier, indexed because grouping by it is the first thing anyone does.

message str

The message or stack trace.

severity str | None

An :class:AppErrorSeverityEnum value, indexed so the listing can isolate the crashes. Nullable with a server_default of "error": adding the column to a table that already has rows fills them in the migration itself.

platform str

An :class:AppPlatformEnum value, indexed so the listing can isolate one platform.

os_version str | None

The device's operating system version.

app_version str | None

The application version or build, indexed: code + app_version is the cut that resolves most investigations.

device_model str | None

The device model.

device_id str | None

An anonymous device identifier, used to group reports from the same device.

user_id UUID | None

The user authenticated at the moment of the error. Nullable, and the concrete subclass re-declares it with the FK to the project's user table.

make_app_error_model

make_app_error_model(
    *,
    user_table: str = "users",
    tablename: str = "app_errors",
    class_name: str = "AppErrorModel",
) -> type[BaseAppErrorModel]

Build a concrete app-error model bound to the project's user table.

Parameters:

Name Type Description Default
user_table str

Table name of the concrete user model the user_id FK references.

'users'
tablename str

__tablename__ for the generated class.

'app_errors'
class_name str

Python class name.

'AppErrorModel'

Returns:

Type Description
type[BaseAppErrorModel]

type[BaseAppErrorModel]: A concrete mapped class.

Two column decisions are made here rather than left to the caller, because getting either wrong is silent:

user_id is nullable. An error in the login or signup flow happens before an authenticated user exists, and that is precisely the error hardest to debug from the app — refusing the report for lack of a user would drop the most valuable case.

The FK uses ON DELETE SET NULL rather than the CASCADE the rest of the schema uses: the report describes a defect of the application, not of the user, so deleting the account must not delete the evidence of the bug.

created_at gets its own index because the standard read is "newest first", paginated, and this is the table that grows with no natural bound — without it every page costs a sort of the whole table.

AppErrorService

AppErrorService(
    repository: BaseRepository[Any],
    *,
    notifier: AlertNotifier | None = None,
    alert_min_severity: AppErrorSeverityEnum = FATAL,
)

Store and read the errors a client application reports.

Attributes:

Name Type Description
repository BaseRepository[Any]

Repository for the concrete app-error table.

notifier AlertNotifier | None

Alerts the admins about reports at or above :attr:alert_min_severity; None alerts nobody.

alert_min_severity AppErrorSeverityEnum

The lowest severity that alerts.

Initialize the service.

Parameters:

Name Type Description Default
repository BaseRepository[Any]

Repository for the concrete app-error table.

required
notifier AlertNotifier | None

Alerts the admins about a stored report at or above alert_min_severity. The alert is scheduled with :meth:AlertNotifier.dispatch, so the client gets its 201 without waiting for the e-mail.

None
alert_min_severity AppErrorSeverityEnum

The lowest severity that alerts (ALERT_APP_MIN_SEVERITY). Defaults to FATAL.

FATAL

truncate staticmethod

truncate(value: str | None, limit: int) -> str | None

Shorten value to fit limit, marking where it was cut.

Parameters:

Name Type Description Default
value str | None

Text sent by the client.

required
limit int

Maximum size of the destination column.

required

Returns:

Type Description
str | None

str | None: The original text when it already fits, the cut

str | None

version with a suffix when it does not, or None when there

str | None

is no value.

A report over the limit is shortened rather than refused: the sender is an app that has just crashed and cannot handle a 422, so refusing would throw the whole report away. The suffix tells whoever reads the listing that content is missing.

report_error async

report_error(
    data: AppErrorReportSchema, *, user_id: UUID | None = None
) -> AppErrorResponseSchema

Persist a report sent by the client application.

Parameters:

Name Type Description Default
data AppErrorReportSchema

The body the client sent.

required
user_id UUID | None

The authenticated user, when there was one. It comes from the token, never from the request body — which is why this is an argument and not a field the client can set.

None

Returns:

Name Type Description
AppErrorResponseSchema AppErrorResponseSchema

The persisted report.

The alert, when a notifier is set, is built from the stored report — truncated, and after the row has its id — and never carries user_id.

list_errors async

list_errors(
    filters: AppErrorFilterSchema, *, page: int = 1, page_size: int = 20
) -> BasePaginationSchema[AppErrorResponseSchema]

Page through the reports matching filters, newest first.

Parameters:

Name Type Description Default
filters AppErrorFilterSchema

Filters from the query string.

required
page int

The page, 1-indexed.

1
page_size int

Items per page.

20

Returns:

Type Description
BasePaginationSchema[AppErrorResponseSchema]

BasePaginationSchema[AppErrorResponseSchema]: One page of

BasePaginationSchema[AppErrorResponseSchema]

reports. Empty when nothing matches — a filtered query with no

BasePaginationSchema[AppErrorResponseSchema]

results is a success, not a 404.

make_app_error_router

make_app_error_router(
    *,
    service_factory: Callable[..., AppErrorService],
    session_factory: Callable[..., AsyncIterator[Any]],
    current_user_id_optional: Callable[..., Any] | None = None,
    admin_dependency: Callable[..., Any] | None = None,
    prefix: str = "/api/app-errors",
    tags: list[str | Enum] | None = None,
    docs_locale: str | None = None,
) -> APIRouter

Build the app-error router.

Endpoints:

  • POST {prefix} — record a report. Public.
  • GET {prefix} — page through the reports. Mounted only when admin_dependency is given.

Parameters:

Name Type Description Default
service_factory Callable[..., AppErrorService]

Builds a request-scoped :class:AppErrorService from the session.

required
session_factory Callable[..., AsyncIterator[Any]]

Yields a request-scoped database session.

required
current_user_id_optional Callable[..., Any] | None

Dependency resolving the caller's id, or None when the request carries no valid token. Without it every report is stored anonymous.

None
admin_dependency Callable[..., Any] | None

Dependency gating the listing. None leaves the GET unmounted — a service that reads its reports through AdminSite does not need the endpoint, and an ungated listing would expose stack traces and device identifiers to anyone.

None
prefix str

Path prefix for both routes.

'/api/app-errors'
tags list[str | Enum] | None

OpenAPI tags, in the shape APIRouter accepts.

None
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

The router, ready to include.

Note

The hourly ceiling is not here. The write endpoint is public and does need one, but it belongs to RateLimitMiddleware configured for this prefix, not to a counter this module reimplements.

What must not be lost in that move is the rule that made the original implementation correct: fail open. Losing an error report is worse than accepting traffic above the ceiling, because the moment the counter store is unwell is the moment errors spike.

Measured: RateLimitMiddleware does not fail open on its own — a store whose hit raises propagates the exception and the caller gets an error. Wrap the store in :class:~tempest_fastapi_sdk.api.middlewares.rate_limit.FailOpenRateLimitStore for this prefix.

AppPlatformEnum

Bases: BaseStrEnum

The client platform an error was reported from.

A closed set on purpose: filtering the listing by platform is the reason the column exists at all, because an error that only shows up on iOS is not the same bug as one that only shows up on Android.

Attributes:

Name Type Description
IOS str

The iOS application.

ANDROID str

The Android application.

WEB str

A web client.

UNKNOWN str

The client did not state a platform.

AppErrorSeverityEnum

Bases: BaseStrEnum

How bad the client says an error is.

Ordered: :meth:at_least compares by position, so FATAL is at least ERROR. The value comes from the client and the write endpoint is public, so it is a hint for triage and for alerting, never a trust boundary — an attacker can send fatal as easily as info, which is why every alert it drives goes through the notifier's throttle.

Attributes:

Name Type Description
INFO str

Diagnostic; nothing failed for the user.

WARNING str

Degraded, the user could go on.

ERROR str

An operation failed. The default.

FATAL str

The app crashed or became unusable.

at_least

at_least(minimum: AppErrorSeverityEnum) -> bool

Return whether this severity is minimum or worse.

Parameters:

Name Type Description Default
minimum AppErrorSeverityEnum

The threshold.

required

Returns:

Name Type Description
bool bool

True when this member is not below minimum.

AppErrorReportSchema

Bases: AppErrorDeviceSchema

The body a client sends when reporting an error.

code and message are the only required fields. Values above the column limit are truncated on the way in, never refused — see :meth:~tempest_fastapi_sdk.app_errors.service.AppErrorService.truncate.

Attributes:

Name Type Description
code str

The error code the app emits.

message str

The message or stack trace.

severity AppErrorSeverityEnum

How bad the client says it is. Defaults to ERROR, so an app that predates the field keeps working.

AppErrorCreateSchema

Bases: AppErrorReportSchema

A report already resolved for persistence.

Differs from :class:AppErrorReportSchema by carrying user_id, which comes from the token and never from the body. Letting the client say whose error it is would allow attributing a report to another user, and this split is what makes that impossible rather than merely discouraged.

Attributes:

Name Type Description
user_id UUID | None

The user authenticated at the moment of the error, when there was one.

AppErrorResponseSchema

Bases: AppErrorDeviceSchema

A persisted report, as the API returns it.

Attributes:

Name Type Description
id UUID

The report's primary key.

code str

The error code.

message str

The message or stack trace, already truncated if it was over the limit.

severity AppErrorSeverityEnum | None

How bad the client said it was; None only for a row written without it.

user_id UUID | None

The associated user, when there was one.

created_at datetime

When the report was stored.

AppErrorDeviceSchema

Bases: BaseSchema

Device data travelling with a report.

Every field is optional: the app sends whatever it managed to collect at the moment of the failure, and requiring any of them would turn an incomplete collection into a lost report.

Attributes:

Name Type Description
platform AppPlatformEnum

The reporting client's platform.

os_version str | None

The operating system version.

app_version str | None

The application version or build.

device_model str | None

The device model.

device_id str | None

An anonymous device identifier, used to group reports coming from the same device.

AppErrorFilterSchema

Bases: BaseSchema

Filters for the administrative listing.

All optional, combined with AND. The cut that resolves most investigations is code + app_version: it isolates one defect in one build.

The range check does not live in a validator. A ValueError raised by a schema resolved through Depends() escapes as a 500, and the API would blame the server for the client's input — so the router answers 422 for an inverted range instead.

Attributes:

Name Type Description
code str | None

Filters by exact code.

platform AppPlatformEnum | None

Filters by platform.

app_version str | None

Filters by application version.

severity AppErrorSeverityEnum | None

Filters by severity.

user_id UUID | None

Filters by one user's reports.

start_date date | None

Start of the creation range, inclusive. Read as a UTC day, because that is the boundary the filter cuts on: created_at is written by utcnow, so a report stored at 02:30 UTC belongs to that UTC day even where the local calendar still shows the previous one.

end_date date | None

End of the creation range, inclusive, and a UTC day for the same reason. A caller who builds these from a local "today" gets the wrong window during the hours the two calendars disagree — three a day in BRT.

as_filters

as_filters() -> dict[str, Any]

Build the equality filters this schema carries.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Only the fields that were set, ready for

dict[str, Any]

BaseRepository. The date range is not here — it is a range,

dict[str, Any]

not an equality, and it is applied separately.