Ir para o conteúdo

tempest_fastapi_sdk.utils

Utilitários: validação BR, senha, HTTP client, retry, upload, datas e formatação.

« Web, UI e utilitários


LocalUploadStorage

LocalUploadStorage(base_dir: Path | str)

Disk-backed :class:UploadStorage using aiofiles.

Writes chunks under base_dir and refuses keys that resolve outside the base — same path-traversal protection :class:UploadUtils already applied. The base_dir is created (with parents) on instantiation.

Initialize.

Parameters:

Name Type Description Default
base_dir Path | str

Root directory for all writes.

required

Raises:

Type Description
ImportError

When the [upload] extra is not installed.

local_path

local_path(key: str) -> Path

Return where key lives on disk, refusing a key that escapes.

What a download route serves the file from, since a local disk cannot mint a URL (:meth:presigned_url is always None).

Parameters:

Name Type Description Default
key str

Storage key.

required

Returns:

Name Type Description
Path Path

The resolved path under base_dir; it may not exist.

Raises:

Type Description
InvalidFileTypeException

When key resolves outside base_dir.

write_stream async

write_stream(
    key: str,
    chunks: AsyncIterator[bytes],
    *,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
    max_size_bytes: int | None = None,
    validator: ContentValidator | None = None,
) -> UploadResult

Persist chunks to base_dir / key.

content_type and metadata are accepted for protocol parity but ignored — the local filesystem has nowhere to store them.

Notes

content_type and metadata are accepted for interface parity and discarded: a local filesystem backend has nowhere to store them.

Raises:

Type Description
InvalidFileTypeException

When the sniffed MIME type is not in the allowed set.

FileTooLargeException

When the stream exceeds the configured maximum size.

delete async

delete(key: str) -> bool

Delete base_dir / key when present.

exists async

exists(key: str) -> bool

Return True when base_dir / key exists.

presigned_url async

presigned_url(key: str, *, expires: timedelta = timedelta(hours=1)) -> str | None

Local storage cannot mint URLs — always None.

MinIOUploadStorage

MinIOUploadStorage(client: AsyncMinIOClient, *, bucket: str | None = None)

:class:UploadStorage backed by :class:AsyncMinIOClient.

Reuses an existing client instance — typically the one wired on the FastAPI app — so the connection pool is shared. The bucket falls back to the client's default_bucket.

Initialize.

Parameters:

Name Type Description Default
client AsyncMinIOClient

A configured MinIO client.

required
bucket str | None

Target bucket. None uses the client's default_bucket.

None

write_stream async

write_stream(
    key: str,
    chunks: AsyncIterator[bytes],
    *,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
    max_size_bytes: int | None = None,
    validator: ContentValidator | None = None,
) -> UploadResult

Buffer chunks, validate, then put_object.

S3 needs the content length upfront, so the stream is materialized in memory before the upload starts. For very large objects, prefer presigned_put_url and let the client upload directly.

delete async

delete(key: str) -> bool

Delete the object — always returns True (S3 idempotent).

exists async

exists(key: str) -> bool

Stat-probe the object.

presigned_url async

presigned_url(key: str, *, expires: timedelta = timedelta(hours=1)) -> str | None

Return a presigned GET URL.

HTTPClient

HTTPClient(
    *,
    base_url: str = "",
    timeout: float = 10.0,
    retry_policy: RetryPolicy | None = None,
    failure_threshold: int = 5,
    recovery_seconds: float = 30.0,
    default_headers: Mapping[str, str] | None = None,
    verify_tls: bool = True,
    propagate_request_id: bool = True,
    request_id_header: str = REQUEST_ID_HEADER,
    transport: AsyncBaseTransport | None = None,
)

Async HTTP client with retries, circuit-breaker and request-id propagation.

Example:

>>> client = HTTPClient(base_url="https://api.example.com")
>>> async with client:
...     response = await client.get("/users/me")
...     payload: dict[str, Any] = response.json()

The client is safe to share across requests on the same event loop — internally each call uses the shared :class:httpx.AsyncClient connection pool.

Initialize.

Parameters:

Name Type Description Default
base_url str

Prepended to relative paths. Use empty string to require absolute URLs at the call site.

''
timeout float

Per-request timeout in seconds. Overridable per call.

10.0
retry_policy RetryPolicy | None

Retry configuration. None uses the defaults (3 attempts, ~0.5/½s backoff).

None
failure_threshold int

Consecutive 5xx/network errors that trip the circuit per host. 0 disables the breaker.

5
recovery_seconds float

Seconds the breaker stays open before allowing one half-open probe.

30.0
default_headers Mapping[str, str] | None

Headers attached to every request (e.g. Authorization).

None
verify_tls bool

Whether to verify TLS certificates. Default True — flip only for internal mTLS or dev with self-signed certs.

True
propagate_request_id bool

When True (default), attach the current request id (from the contextvar RequestIDMiddleware binds) to outbound requests.

True
request_id_header str

Header name the propagated id is sent under. Defaults to :data:REQUEST_ID_HEADER (X-Request-ID). Set it to the name the upstream expects; it is independent of the inbound RequestIDMiddleware(header_name=...), which only decides where the id is read from.

REQUEST_ID_HEADER
transport AsyncBaseTransport | None

Explicit transport for the underlying client — pass an httpx.MockTransport in tests to script responses without real network. None uses the default transport.

None

Raises:

Type Description
ImportError

When the [http] extra is missing.

ValueError

When request_id_header is empty or blank.

aclose async

aclose() -> None

Close the underlying connection pool. Safe to call twice.

request async

request(
    method: str,
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    json: object = None,
    data: HTTPRequestData | None = None,
    content: HTTPRequestContent | None = None,
    files: HTTPRequestFiles | None = None,
    headers: Mapping[str, str] | None = None,
    timeout: float | None = None,
) -> Response

Perform an HTTP request with retries and circuit-breaker.

Parameters:

Name Type Description Default
method str

HTTP verb ("GET", "POST", ...).

required
url str

Absolute URL or path relative to base_url.

required
params Mapping[str, Any] | None

Query-string params.

None
json object

JSON-serializable body. Mutually exclusive with data, content and files.

None
data HTTPRequestData | None

Form fields. Alone it is sent application/x-www-form-urlencoded; alongside files it becomes the scalar half of the multipart body.

None
content HTTPRequestContent | None

Raw body — bytes, str, or an iterable of chunks — for a media type that is neither JSON nor a form.

None
files HTTPRequestFiles | None

Multipart file parts, in any shape httpx accepts: {name: bytes}, {name: (filename, bytes)}, or {name: (filename, bytes, content_type)}.

None
headers Mapping[str, str] | None

Per-request headers merged on top of default_headers + propagated X-Request-ID.

None
timeout float | None

Override for this call.

None

Returns:

Type Description
Response

httpx.Response: The successful response. Caller checks

Response

response.status_code for 4xx outcomes (those are

Response

not retried).

Raises:

Type Description
CircuitOpenError

When the per-host breaker is open.

HTTPError

When all attempts failed (last exception is re-raised).

Notes

The trailing raise is defensive only: the retry loop either returns a response or raises, so it should never be reached.

A body that cannot be replayed is not retried. Retrying re-sends the same arguments, and a stream handed to content or files is already drained by then, so attempt two would upload a truncated body that the server has no way to tell from a short file. Pass bytes to keep the retries.

get async

get(url: str, **kwargs: Any) -> Response

Shortcut for request("GET", url, ...).

Parameters:

Name Type Description Default
url str

Absolute URL, or a path resolved against base_url.

required
**kwargs Any

Extra arguments forwarded to httpx.

{}

Returns:

Type Description
Response

httpx.Response: The server's response.

post async

post(url: str, **kwargs: Any) -> Response

Shortcut for request("POST", url, ...).

Parameters:

Name Type Description Default
url str

Absolute URL, or a path resolved against base_url.

required
**kwargs Any

Extra arguments forwarded to httpx.

{}

Returns:

Type Description
Response

httpx.Response: The server's response.

put async

put(url: str, **kwargs: Any) -> Response

Shortcut for request("PUT", url, ...).

Parameters:

Name Type Description Default
url str

Absolute URL, or a path resolved against base_url.

required
**kwargs Any

Extra arguments forwarded to httpx.

{}

Returns:

Type Description
Response

httpx.Response: The server's response.

patch async

patch(url: str, **kwargs: Any) -> Response

Shortcut for request("PATCH", url, ...).

Parameters:

Name Type Description Default
url str

Absolute URL, or a path resolved against base_url.

required
**kwargs Any

Extra arguments forwarded to httpx.

{}

Returns:

Type Description
Response

httpx.Response: The server's response.

delete async

delete(url: str, **kwargs: Any) -> Response

Shortcut for request("DELETE", url, ...).

Parameters:

Name Type Description Default
url str

Absolute URL, or a path resolved against base_url.

required
**kwargs Any

Extra arguments forwarded to httpx.

{}

Returns:

Type Description
Response

httpx.Response: The server's response.

stream async

stream(
    method: str,
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    json: object = None,
    data: HTTPRequestData | None = None,
    content: HTTPRequestContent | None = None,
    files: HTTPRequestFiles | None = None,
    headers: Mapping[str, str] | None = None,
    timeout: float | None = None,
) -> AsyncGenerator[str, None]

Stream a response body line by line (e.g. NDJSON).

Retries and the circuit-breaker cover only opening the stream — network errors and retryable statuses on the initial response are retried with the same backoff as :meth:request. Once the first line is yielded the connection is committed, so a mid-stream failure (including a ReadTimeout between two chunks) propagates to the caller instead of re-sending the request and replaying lines the caller already consumed. A non-success status that is not going to be retried raises httpx.HTTPStatusError before any line is yielded, so the caller never has to inspect status_code on a stream; its body is read first, so exc.response.content carries the server's message (a failure reading that body is swallowed, so it never turns the status error into a retry). Closing the generator early -- a break, a client that disconnects -- closes the connection right away rather than at garbage collection.

Parameters:

Name Type Description Default
method str

HTTP verb.

required
url str

Absolute URL or path relative to base_url.

required
params Mapping[str, Any] | None

Query-string params.

None
json object

JSON-serializable body.

None
data HTTPRequestData | None

Form body.

None
content HTTPRequestContent | None

Raw body.

None
files HTTPRequestFiles | None

Multipart files.

None
headers Mapping[str, str] | None

Per-request headers merged on top of the defaults + propagated X-Request-ID.

None
timeout float | None

Override for this call.

None

Yields:

Name Type Description
str AsyncGenerator[str, None]

Decoded response lines, in order (empty lines included — the

AsyncGenerator[str, None]

caller skips them).

Raises:

Type Description
CircuitOpenError

When the per-host breaker is open.

HTTPStatusError

When the (final) response status is not a success and is not retried.

HTTPError

When every open attempt failed with a network error (the last exception is re-raised).

stream_bytes async

stream_bytes(
    method: str,
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    json: object = None,
    data: HTTPRequestData | None = None,
    content: HTTPRequestContent | None = None,
    files: HTTPRequestFiles | None = None,
    headers: Mapping[str, str] | None = None,
    timeout: float | None = None,
) -> AsyncGenerator[bytes, None]

Stream a response body as raw byte chunks (audio, files).

The same retry, circuit-breaker and error contract as :meth:stream -- retries only while opening, the connection committed once the first chunk is yielded -- for a body that is not text: a WAV or PCM stream, a file download. Chunks arrive as the server flushes them.

Parameters:

Name Type Description Default
method str

HTTP verb.

required
url str

Absolute URL or path relative to base_url.

required
params Mapping[str, Any] | None

Query-string params.

None
json object

JSON-serializable body.

None
data HTTPRequestData | None

Form body.

None
content HTTPRequestContent | None

Raw body.

None
files HTTPRequestFiles | None

Multipart files.

None
headers Mapping[str, str] | None

Per-request headers.

None
timeout float | None

Override for this call.

None

Yields:

Name Type Description
bytes AsyncGenerator[bytes, None]

The body, chunk by chunk, in order.

Raises:

Type Description
CircuitOpenError

When the per-host breaker is open.

HTTPStatusError

When the (final) response status is not a success and is not retried; exc.response.content holds the error body.

HTTPError

When every open attempt failed with a network error.

HTTPFileContent module-attribute

HTTPFileContent = IO[bytes] | bytes | str

One file payload accepted inside :data:HTTPRequestFiles.

HTTPFilePart module-attribute

HTTPFilePart = (
    HTTPFileContent
    | tuple[str | None, HTTPFileContent]
    | tuple[str | None, HTTPFileContent, str | None]
    | tuple[str | None, HTTPFileContent, str | None, Mapping[str, str]]
)

One multipart file entry in any tuple shape httpx accepts.

HTTPRequestContent module-attribute

HTTPRequestContent = str | bytes | Iterable[bytes] | AsyncIterable[bytes]

Raw body accepted by :meth:HTTPClient.request and streaming helpers.

HTTPRequestData module-attribute

HTTPRequestData = Mapping[str, Any]

Form fields accepted by :meth:HTTPClient.request and streaming helpers.

HTTPRequestFiles module-attribute

HTTPRequestFiles = Mapping[str, HTTPFilePart] | Sequence[tuple[str, HTTPFilePart]]

Multipart file parts accepted by :meth:HTTPClient.request and streaming helpers.

CircuitOpenError

CircuitOpenError(host: str)

Bases: Exception

Raised when the circuit-breaker rejects a call.

Carries the host that tripped the breaker so callers can branch on it (e.g. fall back to a cache or a queue).

Initialize.

Parameters:

Name Type Description Default
host str

The host whose breaker is open.

required

RetryLogger

Bases: Protocol

The two calls :func:async_retry makes on whatever it logs to.

async_retry writes exactly one WARNING per retry and one ERROR when the budget runs out. Typing the parameter as logging.Logger named the implementation the SDK happens to use rather than that requirement — and excluded :class:~tempest_fastapi_sdk.LogUtils, which is the logger this same SDK hands the service. A module that opens with logger: LogUtils = LogUtils(__name__) could not pass that logger to a decorator shipped alongside it: the call worked at runtime, because the shapes match, and failed under mypy with Argument "logger" to "async_retry" has incompatible type "LogUtils". The workaround, logger=logger.logger, reaches past the facade to the object it wraps.

Both parameters are positional-only. A protocol member written def warning(self, msg: str) also demands the name msg from the implementer, and the two loggers disagree — logging.Logger calls it msg, LogUtils calls it message. mypy accepts either spelling; basedpyright rejects the mismatch outright, which is the checker the consumer runs.

runtime_checkable makes isinstance work, but it only checks that the two members exist — the signatures are the type checker's job, and the recipe carries a typed example so both checkers see it.

warning

warning(msg: str, /, *args: object) -> None

Emit a WARNING record.

Parameters:

Name Type Description Default
msg str

The %-style template.

required
*args object

Interpolation arguments, kept lazy.

()

error

error(msg: str, /, *args: object) -> None

Emit an ERROR record.

Parameters:

Name Type Description Default
msg str

The %-style template.

required
*args object

Interpolation arguments, kept lazy.

()

RetryPolicy dataclass

RetryPolicy(
    max_attempts: int = 3,
    backoff_initial_seconds: float = 0.5,
    backoff_max_seconds: float = 8.0,
    retry_statuses: frozenset[int] = (lambda: frozenset({429, 500, 502, 503, 504}))(),
    retry_on_read_timeout: bool = True,
)

Bounded exponential backoff for retried operations.

The first retry sleeps for backoff_initial_seconds; each subsequent retry doubles the wait, capped at backoff_max_seconds. Total retries are bounded by max_attempts (the first try counts).

Attributes:

Name Type Description
max_attempts int

Total tries including the first. 1 disables retries.

backoff_initial_seconds float

Sleep before the second attempt.

backoff_max_seconds float

Hard cap per sleep.

retry_statuses frozenset[int]

HTTP status codes worth retrying. Defaults to common 5xx; 429 is included because it usually means "back off and try again". Read by :class:~tempest_fastapi_sdk.HTTPClient only — :func:async_retry branches on exceptions instead.

retry_on_read_timeout bool

Whether :class:~tempest_fastapi_sdk.HTTPClient retries a request whose response did not arrive within the read timeout. True (default) suits a call the server answers quickly, where a slow read means a stalled connection. Set it to False for a call whose cost is the server's work — a model generation: the server aborts the request when the client gives up, so every retry starts the same work from zero and times out again, and the failure arrives after max_attempts x the timeout instead of once. The generators in :mod:tempest_fastapi_sdk.genai default to False. ConnectError is retried either way, since no work started. Read by :class:~tempest_fastapi_sdk.HTTPClient only.

sleep_for

sleep_for(attempt: int) -> float

Compute the sleep between attempt n and attempt n+1.

Parameters:

Name Type Description Default
attempt int

Zero-based retry attempt number.

required

Returns:

Name Type Description
float float

Seconds to wait before the next attempt.

async_retry

async_retry(
    policy: RetryPolicy | None = None,
    exceptions: tuple[type[BaseException], ...] = (Exception,),
    *,
    logger: RetryLogger | None = None,
) -> Callable[[Callable[P, Awaitable[T]]], Callable[P, Awaitable[T]]]

Retry an async callable with the bounded backoff of policy.

Example:

>>> from tempest_fastapi_sdk import RetryPolicy, async_retry
>>>
>>> @async_retry(RetryPolicy(max_attempts=5), (ConnectionError,))
... async def connect(url: str) -> None:
...     ...

When every attempt fails, the last exception propagates rather than a wrapper: a caller that could react to a permanent ConnectionError should still see a ConnectionError.

exceptions defaults to Exception, which deliberately excludes :class:asyncio.CancelledError — it derives from BaseException, and retrying a cancelled task fights the cancellation instead of honoring it. Narrow the tuple to the transient failures you actually mean; a TypeError retried three times is the same bug, later.

Parameters:

Name Type Description Default
policy RetryPolicy | None

Attempt budget and backoff curve. None (default) builds a fresh :class:RetryPolicy — a shared module-level instance would be mutable state every decorated function points at.

None
exceptions tuple[type[BaseException], ...]

Exception types that count as transient. Anything outside the tuple propagates immediately, without consuming an attempt.

(Exception,)
logger RetryLogger | None

Where the retry and give-up records go. Anything with warning and error fits — a logging.Logger, or the :class:~tempest_fastapi_sdk.LogUtils this SDK hands the service. None uses this module's logger.

None

Returns:

Name Type Description
Callable Callable[[Callable[P, Awaitable[T]]], Callable[P, Awaitable[T]]]

A decorator wrapping the target coroutine function.

Raises:

Type Description
ValueError

When policy.max_attempts is below 1, which would run the callable zero times and return None from something annotated to return T.

form_encode

form_encode(payload: Mapping[str, Any] | None) -> dict[str, str]

Flatten a nested payload into bracket-notation form fields.

Parameters:

Name Type Description Default
payload Mapping[str, Any] | None

The request body as a nested mapping. None yields an empty mapping, so a caller can forward an optional body without branching.

required

Returns:

Type Description
dict[str, str]

dict[str, str]: Flat field -> value pairs, ready to hand to

dict[str, str]

httpx' data=.

None values are dropped rather than sent empty: on these APIs an empty string is a real value (it clears a field), so serializing None as "" would silently erase data the caller never meant to touch. Empty mappings and lists disappear for the same reason — they have no bracket path to occupy.

Examples:

>>> form_encode({"amount": 1000, "metadata": {"user_id": 42}})
{'amount': '1000', 'metadata[user_id]': '42'}
>>> form_encode({"items": [{"price": "price_123", "quantity": 2}]})
{'items[0][price]': 'price_123', 'items[0][quantity]': '2'}
>>> form_encode({"paid": True, "note": None})
{'paid': 'true'}

PasswordUtils

PasswordUtils(*, rounds: int = 12, truncate_legacy_bcrypt: bool = True)

Hash and verify passwords using bcrypt.

Stateless utility — instantiate once and reuse across the application. The cost factor (rounds) controls how slow hashing is; 12 is a sensible 2026 default. Raise it when CPU budget allows to keep up with hardware.

Attributes:

Name Type Description
rounds int

The bcrypt cost factor.

truncate_legacy_bcrypt bool

Whether :meth:verify truncates UTF-8 password bytes to 72 bytes before calling bcrypt.checkpw so legacy hashes created under passlib or bcrypt < 5 keep verifying on bcrypt >= 5.0.0.

Initialize.

Parameters:

Name Type Description Default
rounds int

The bcrypt cost factor. Higher values make hashing slower and brute-force attacks harder. Defaults to 12.

12
truncate_legacy_bcrypt bool

Truncate plain to the first 72 UTF-8 bytes during :meth:verify so hashes produced by passlib or bcrypt < 5 from passwords longer than 72 bytes continue to verify under bcrypt >= 5.0.0. Set to False on greenfield services with no legacy hashes to reject any attempt over 72 bytes. Does not affect :meth:hash, which always refuses inputs over 72 bytes. Defaults to True.

True

Raises:

Type Description
ImportError

When the [auth] extra is not installed.

hash

hash(plain: str) -> str

Hash a plaintext password.

bcrypt refuses inputs over 72 UTF-8 bytes — note bytes, not characters, so an emoji costs four and an accented Latin letter two. Validate the length before calling this from a request handler, or the ValueError becomes an HTTP 500 instead of a 422; :class:~tempest_fastapi_sdk.UserAuthService does that via AUTH_PASSWORD_MAX_BYTES. This method never truncates, even when :attr:truncate_legacy_bcrypt is True.

Parameters:

Name Type Description Default
plain str

The plaintext password.

required

Returns:

Name Type Description
str str

The bcrypt hash encoded as a UTF-8 string, ready to

str

persist in a database column.

Raises:

Type Description
ValueError

When plain exceeds 72 UTF-8 bytes.

verify

verify(plain: str, hashed: str) -> bool

Verify a plaintext password against an existing hash.

Catches malformed hashes and returns False rather than raising, so callers can branch on the boolean without bcrypt-specific error handling.

When :attr:truncate_legacy_bcrypt is True (the default), plain is UTF-8 encoded and truncated to the first 72 bytes before calling bcrypt.checkpw. Versions of bcrypt prior to 5.0 (and passlib) truncated inputs silently at 72 bytes; starting with bcrypt 5.0.0, both hashpw and checkpw raise ValueError past 72 bytes instead. Truncating on verification keeps legacy hashes from long passphrases working without weakening them, because bcrypt never mixed bytes beyond the 72nd into the stored hash. :meth:hash never truncates.

Parameters:

Name Type Description Default
plain str

The plaintext password to verify.

required
hashed str

The previously stored bcrypt hash.

required

Returns:

Name Type Description
bool bool

True if the password matches.

dummy_verify

dummy_verify(plain: str) -> bool

Spend one :meth:verify against a throwaway hash, and fail.

Call it on the login branch where no stored hash exists (unknown account), so that branch pays the same bcrypt cost as a wrong password. Without it the refusal for a missing account returns before any hashing, and the response time alone tells a caller which addresses are registered.

The throwaway hash is built on first use with this instance's :attr:rounds, the cost the instance writes for real accounts, then cached; that first call pays one extra hash.

Parameters:

Name Type Description Default
plain str

The submitted plaintext password.

required

Returns:

Name Type Description
bool bool

Always False, so the call can stand where a

bool

meth:verify result is expected.

PasswordPolicy dataclass

PasswordPolicy(
    min_length: int = 8, max_bytes: int = 72, require_complexity: bool = False
)

The length + complexity rules a plaintext password must satisfy.

The same three numbers AuthSettings declares (AUTH_PASSWORD_MIN_LENGTH, AUTH_PASSWORD_MAX_BYTES, AUTH_PASSWORD_REQUIRE_COMPLEXITY), in a value object any caller can build — so a surface that takes a password but has no settings object of its own (the admin panel's password field) enforces the project's real rules instead of inventing its own.

Build it from your settings with :meth:from_settings; the defaults here mirror the AuthSettings field defaults.

Attributes:

Name Type Description
min_length int

Minimum length in characters.

max_bytes int

Maximum length in UTF-8 bytes — the unit bcrypt counts.

require_complexity bool

Require one lowercase, one uppercase, one digit and one non-alphanumeric character, and raise the effective length floor to at least 8.

from_settings classmethod

from_settings(settings: PasswordSettingsLike) -> PasswordPolicy

Read the policy off an AuthSettings-shaped object.

Parameters:

Name Type Description Default
settings PasswordSettingsLike

Any object carrying the three AUTH_PASSWORD_* attributes — typically the service's own Settings composed from AuthSettings.

required

Returns:

Name Type Description
PasswordPolicy PasswordPolicy

The policy those settings describe.

PasswordSettingsLike

Bases: Protocol

The three settings fields :meth:PasswordPolicy.from_settings reads.

Declared as read-only properties so frozen :class:~tempest_fastapi_sdk.settings.AuthSettings subclasses and plain objects with ordinary attributes are both accepted.

AUTH_PASSWORD_MIN_LENGTH property

AUTH_PASSWORD_MIN_LENGTH: int

Return the minimum password length in characters.

AUTH_PASSWORD_MAX_BYTES property

AUTH_PASSWORD_MAX_BYTES: int

Return the maximum password length in UTF-8 bytes.

AUTH_PASSWORD_REQUIRE_COMPLEXITY property

AUTH_PASSWORD_REQUIRE_COMPLEXITY: bool

Return whether character-class complexity is required.

PasswordPolicyViolation dataclass

PasswordPolicyViolation(
    message: str, details: dict[str, Any], code: PasswordViolationCodeEnum
)

Why a password was rejected, in a form both callers can render.

Attributes:

Name Type Description
message str

Human-readable reason.

details dict[str, Any]

Structured context — the bound that was crossed, or the character classes that were missing.

code PasswordViolationCodeEnum

Which rule was broken, stable across releases and locales.

PasswordViolationCodeEnum

Bases: BaseStrEnum

Which rule of a :class:PasswordPolicy a password broke.

Stable identifiers a client can branch on and a message catalog can translate: UserAuthService raises with the value as message_key, and the default catalog carries all three in pt-BR and en-US.

Attributes:

Name Type Description
PASSWORD_TOO_SHORT

Below the effective minimum length.

PASSWORD_TOO_LONG

Above max_bytes UTF-8 bytes (bcrypt's limit).

PASSWORD_TOO_WEAK

Missing a required character class under complexity mode.

check_password_policy

check_password_policy(
    password: str, policy: PasswordPolicy | None = None
) -> PasswordPolicyViolation | None

Check a plaintext password against a policy.

Returns the violation instead of raising, so a form can put the message next to the field while a service turns the same value into a ValidationException. That split is the reason this lives here and not inside the auth service: the rule was private to UserAuthService, so every other surface that accepts a password — the admin panel's create form, a provisioning script — either skipped it or wrote its own.

Parameters:

Name Type Description Default
password str

The plaintext to check.

required
policy PasswordPolicy | None

The rules to apply. None uses the AuthSettings defaults.

None

Returns:

Type Description
PasswordPolicyViolation | None

PasswordPolicyViolation | None: The first violation found, or

PasswordPolicyViolation | None

None when the password is acceptable.

generate_password

generate_password(
    *, min_length: int = 8, max_bytes: int = 72, require_complexity: bool = True
) -> str

Mint a random password that satisfies the configured policy.

For flows where nobody types a password — the OAuth callback that creates an account, an admin provisioning a user — but the column is still NOT NULL. The account owner reaches a password of their own through the ordinary reset flow; this one only has to be unguessable and accepted.

Compliance is by construction, not by retry. Drawing from one flat alphabet and hoping is the defect this function exists to avoid: fed to UserAuthService._enforce_password_policy with complexity on and a 12-character floor, 200 000 samples each, secrets.token_urlsafe(16) was rejected 53.01% of the time, secrets.token_urlsafe(32) 26.54%, and secrets.token_hex(32) 100% (it has neither uppercase nor a special character, on every single draw). A generator that passes three times in four fails intermittently, in production, inside a callback, about a password the user never typed. So one character is drawn from each required class first, the rest fills from their union, and the result is shuffled with secrets.SystemRandom.

Every character is ASCII, so the returned length is also the UTF-8 byte count bcrypt measures — max_bytes needs no separate encoding check.

Parameters:

Name Type Description Default
min_length int

The policy's AUTH_PASSWORD_MIN_LENGTH. Raised to 8 internally when require_complexity is set, mirroring the floor the policy itself applies.

8
max_bytes int

The policy's AUTH_PASSWORD_MAX_BYTES (72 by default — the bcrypt limit).

72
require_complexity bool

The policy's AUTH_PASSWORD_REQUIRE_COMPLEXITY. Only affects the length floor: all four classes are always represented when the target length has room for them, since a stronger password is never rejected by a laxer policy.

True

Returns:

Name Type Description
str str

A fresh random password of at least min_length

str

characters and at most max_bytes bytes.

Raises:

Type Description
ValueError

When the policy cannot be satisfied at all — max_bytes below the effective length floor. That is a misconfiguration no password could survive, so it surfaces here rather than as a validation error later.

DEFAULT_GENERATED_PASSWORD_LENGTH module-attribute

DEFAULT_GENERATED_PASSWORD_LENGTH: int = 24

Length :func:generate_password targets when the policy allows it.

Well above every default floor, and well under the 72-byte bcrypt ceiling, so the common case needs no clamping in either direction.

JWTUtils

JWTUtils(
    secret: str,
    *,
    algorithm: str = "HS256",
    default_ttl: timedelta = timedelta(hours=1),
    issuer: str | None = None,
)

Encode and decode JWTs using a shared secret.

Every token gets an iat (issued-at) and exp (expiry) claim populated automatically; the caller is responsible for the rest (sub, custom claims, etc.). When the helper is created with issuer=, the iss claim is also added on encode and verified on decode.

Attributes:

Name Type Description
algorithm str

The JWT signing algorithm.

default_ttl timedelta

Default expiration applied on :meth:encode when ttl is not provided.

Initialize.

Parameters:

Name Type Description Default
secret str

The signing key (HMAC) or private key (RSA/EC).

required
algorithm str

JWT algorithm. Defaults to "HS256". Use "RS256" / "ES256" for asymmetric setups.

'HS256'
default_ttl timedelta

TTL applied by :meth:encode when the caller doesn't pass one. Defaults to 1 hour.

timedelta(hours=1)
issuer str | None

Value for the iss claim. When set, :meth:decode rejects tokens whose iss doesn't match (i.e. domain-level isolation).

None

Raises:

Type Description
ImportError

When the [auth] extra is not installed.

encode

encode(payload: dict[str, Any], *, ttl: timedelta | None = None) -> str

Encode payload as a signed JWT.

Parameters:

Name Type Description Default
payload dict[str, Any]

Claims to include. Typically contains a stable subject ("sub": "<user-id>").

required
ttl timedelta | None

Override :attr:default_ttl for this call (e.g. shorter for password-reset tokens).

None

Returns:

Name Type Description
str str

The compact-serialized JWT.

decode

decode(token: str) -> dict[str, Any]

Decode and verify a JWT.

Parameters:

Name Type Description Default
token str

The token to decode.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The decoded claims.

Raises:

Type Description
ExpiredTokenException

When the exp claim is past.

InvalidTokenException

For every other validation failure (bad signature, wrong issuer, missing claim, malformed payload, etc.).

decode_or_none

decode_or_none(token: str) -> dict[str, Any] | None

Decode and verify a JWT, returning None on failure.

Convenience wrapper for opportunistic decoding (e.g. soft auth that downgrades the user to anonymous when the token is missing/bad).

Parameters:

Name Type Description Default
token str

The token to decode.

required

Returns:

Type Description
dict[str, Any] | None

dict[str, Any] | None: The decoded claims, or None

dict[str, Any] | None

when the token is invalid or expired.

token_type_allowed

token_type_allowed(
    payload: Mapping[str, Any],
    accepted: Collection[str],
    *,
    strict: bool = False,
    legacy_claims: Collection[str] = (),
) -> bool

Return whether a decoded token's type is one of accepted.

Tokens minted by this version carry typ, so the check is a plain membership test. Tokens minted before typ existed — or by a project calling :meth:~tempest_fastapi_sdk.JWTUtils.encode itself — have no typ; those pass by default, because rejecting them would log every existing session out on upgrade. The two markers the SDK already stamped, refresh: True and purpose: "mfa_pending", are read as a fallback so an old refresh or MFA-pending token is still classified instead of being waved through as an access token.

Any other purpose claim is read as the token's type too. A token that declares what it is for — {"purpose": "password_reset"}, the shape single-use links are commonly signed with — is a single-purpose token, never a session, so it passes only where its purpose is listed in accepted. Before this, such a token reached the untyped fallback and authorized every route guarded with the default strict=False for its whole lifetime:

>>> token_type_allowed({"purpose": "password_reset"}, [ACCESS_TOKEN_TYPE])
False
>>> token_type_allowed({"purpose": "password_reset"}, ["password_reset"])
True

That default is right for tokens this SDK minted and wrong for everyone else's. A service that already separated access from refresh under a claim of its own — type, token_type — has no typ on any legacy token and no SDK fallback marker either, so every one of them would reach return True and authorize any call site for the length of the refresh TTL. legacy_claims names where else to read the type from, and strict refuses what stays unclassified:

>>> token_type_allowed({"type": "refresh"}, [ACCESS_TOKEN_TYPE])
True
>>> token_type_allowed(
...     {"type": "refresh"},
...     [ACCESS_TOKEN_TYPE],
...     strict=True,
...     legacy_claims=("type",),
... )
False

Parameters:

Name Type Description Default
payload Mapping[str, Any]

Decoded, signature-verified claims.

required
accepted Collection[str]

Token types the call site allows.

required
strict bool

Reject a payload whose type cannot be determined instead of accepting it. Leaves the migration window closed at the cost of logging out sessions minted before typ.

False
legacy_claims Collection[str]

Extra claim names to read the type from, in order, when typ is absent. For the consumer whose own tokens spell it differently.

()

Returns:

Name Type Description
bool bool

True when the token may be used at this call site.

token_amr

token_amr(payload: Mapping[str, Any]) -> tuple[str, ...] | None

Return the amr methods of a decoded token.

Parameters:

Name Type Description Default
payload Mapping[str, Any]

Decoded, signature-verified claims.

required

Returns:

Type Description
tuple[str, ...] | None

tuple[str, ...] | None: The methods, in the order they were

tuple[str, ...] | None

stamped. None when the claim is absent or is not a list of

tuple[str, ...] | None

strings — a token minted before the claim existed, or by someone

tuple[str, ...] | None

else. Callers treat None as "no second factor proven", so the

tuple[str, ...] | None

rollout window never counts an unknown session as MFA.

token_actor

token_actor(payload: Mapping[str, Any]) -> str | None

Return who is acting behind a decoded token, if anyone.

A token the admin signed to impersonate a user carries act = {"sub": <operator id>} (RFC 8693); the user's own tokens carry no act. A route that must not run under an impersonated session — changing the password, moving money — refuses when this is not None:

>>> token_actor({"sub": "u1", "act": {"sub": "op7"}})
'op7'
>>> token_actor({"sub": "u1"}) is None
True

Parameters:

Name Type Description Default
payload Mapping[str, Any]

Decoded, signature-verified claims.

required

Returns:

Type Description
str | None

str | None: The actor's sub; None only when the claim is

str | None

absent. A malformed act (not an object with a string sub)

str | None

comes back as "unknown", so a guard never reads a broken

str | None

delegation as the user's own session.

ACT_CLAIM module-attribute

ACT_CLAIM: str = 'act'

Claim naming the actor behind a delegated token (RFC 8693, act).

The admin's impersonation handler stamps {"sub": <operator id>} here; read it with :func:token_actor.

TOTPHelper

TOTPHelper(*, issuer: str)

Stateless TOTP issuer + verifier.

Construct one per app/process. Every method is pure — the helper holds only the issuer string shown in Authenticator apps next to the account name. Secrets and verification codes are passed in by the caller (typically loaded from the user row).

Requires the [mfa] extra (pyotp).

Example:

>>> totp = TOTPHelper(issuer="My App")
>>> secret = totp.generate_secret()                   # base32
>>> uri = totp.provisioning_uri(secret, "ana@example.com")
>>> # render `uri` as a QR code; user scans it
>>> totp.verify(secret, "123456")                     # True / False

Initialize.

Parameters:

Name Type Description Default
issuer str

Label rendered by the Authenticator app alongside the account name. Use the human-readable product name ("My App") — pyotp URL-encodes it for you.

required

generate_secret

generate_secret() -> str

Return a fresh URL-safe base32 secret (16 chars, 80 bits).

Returns:

Name Type Description
str str

Base32-encoded TOTP secret ready to feed

str

meth:provisioning_uri and :meth:verify. Persist it

str

on the user row (encrypted at rest is preferable —

str

consider Postgres pgcrypto for the column).

Raises:

Type Description
ImportError

When the [mfa] extra is not installed.

provisioning_uri

provisioning_uri(secret: str, account_name: str) -> str

Build the otpauth:// URI for account_name.

The returned URI encodes the secret + issuer + account name; render it as a QR code (most apps support it directly via a <img> referencing a QR generator route on the backend).

Parameters:

Name Type Description Default
secret str

Base32 secret from :meth:generate_secret.

required
account_name str

Identifier shown next to issuer in the user's Authenticator — typically the email.

required

Returns:

Name Type Description
str str

otpauth://totp/<issuer>:<account>?secret=…&issuer=….

Raises:

Type Description
ImportError

When the [mfa] extra is not installed.

verify

verify(secret: str, code: str, *, window: int = 1) -> bool

Constant-time check that code matches secret now.

Says nothing about whether code was already used: a step stays valid for the whole window, so the same 6 digits verify again until the window moves past it. A caller that needs single-use semantics compares :meth:matching_step against the last accepted step — which is what :meth:~tempest_fastapi_sdk.UserAuthService.mfa_verify does.

Parameters:

Name Type Description Default
secret str

Base32 secret persisted on the user row.

required
code str

6-digit code submitted by the user.

required
window int

Tolerance in 30-second steps to absorb clock drift between client and server. 1 (default) accepts the previous + current + next step (90s window total). Setting it to 0 is strict; values above 2 weaken security noticeably.

1

Returns:

Name Type Description
bool bool

True when the code is valid for the current

bool

window, False otherwise (also when code is

bool

non-numeric or wrong length).

Raises:

Type Description
ImportError

When the [mfa] extra is not installed.

matching_step

matching_step(secret: str, code: str, *, window: int = 1) -> int | None

Return the 30-second step code was generated from.

The step is the TOTP counter value, an integer that only moves forward — so persisting the last accepted one is what makes a code single-use: a code whose step is at or below that one has already been spent, whatever the clock says now.

Parameters:

Name Type Description Default
secret str

Base32 secret persisted on the user row.

required
code str

6-digit code submitted by the user. Spacing and dashes are stripped, as in :meth:verify.

required
window int

Tolerance in 30-second steps, as in :meth:verify.

1

Returns:

Type Description
int | None

int | None: The step whose code equals code, or None

int | None

when no step in the window produces it (also when code is

int | None

non-numeric or the wrong length). Steps are scanned oldest

int | None

first, the order pyotp itself uses, so two steps that

int | None

happen to render the same 6 digits resolve to the older one.

Raises:

Type Description
ImportError

When the [mfa] extra is not installed.

provisioning_qr_terminal

provisioning_qr_terminal(
    uri: str,
    *,
    background: ProvisioningQrBackground = "dark",
    border: int = PROVISIONING_QR_BORDER,
) -> str

Draw the provisioning URI as a QR code made of terminal characters.

Each character covers one module across and two modules down, using the half blocks ▀ (upper), ▄ (lower), █ (full) and a space, so the symbol keeps its square shape in a terminal whose cells are about twice as tall as they are wide. A 95-character URI (issuer Tempest, ana@example.com, 32-char secret) encodes at version 6 and prints 49 columns by 25 lines with the default quiet zone, and a 159-character one (a 22-character issuer, a 41-character e-mail) prints 61 columns by 31 lines — both within 80 columns (segno 1.6.6).

The characters paint in the terminal's foreground colour, so which modules get drawn depends on the background: on a dark terminal the light modules (and the quiet zone) are drawn, which is what makes the symbol read dark-on-light to the camera; on a light terminal the dark modules are drawn.

Example:

>>> from tempest_fastapi_sdk import TOTPHelper, provisioning_qr_terminal
>>> totp = TOTPHelper(issuer="Tempest")
>>> uri = totp.provisioning_uri(totp.generate_secret(), "ana@example.com")
>>> print(provisioning_qr_terminal(uri))  # doctest: +SKIP

Parameters:

Name Type Description Default
uri str

The otpauth:// URI from :meth:TOTPHelper.provisioning_uri.

required
background ProvisioningQrBackground

"dark" (default, the usual terminal) or "light".

'dark'
border int

Quiet zone in modules. See :data:PROVISIONING_QR_BORDER.

PROVISIONING_QR_BORDER

Returns:

Name Type Description
str str

The lines of the drawing joined by "\n", without a

str

trailing newline — ready for print or typer.echo.

Raises:

Type Description
ValueError

When uri is empty or too long for a QR code.

ImportError

When segno (the [mfa] extra) is missing.

provisioning_qr_data_uri

provisioning_qr_data_uri(
    uri: str,
    *,
    kind: ProvisioningQrKind = "svg",
    scale: int = PROVISIONING_QR_SCALE,
    border: int = PROVISIONING_QR_BORDER,
) -> str

Encode the provisioning URI as a QR code image in a data: URI.

Goes straight into <img src="..."> or a mobile image view, so the app shows the QR code without a QR library of its own. With segno 1.6.6 and the defaults, the SVG data: URI for a 95-character URI measured 3 642 to 4 062 characters across 500 random secrets — the path length follows the module pattern.

Example:

>>> from tempest_fastapi_sdk import TOTPHelper, provisioning_qr_data_uri
>>> totp = TOTPHelper(issuer="Tempest")
>>> uri = totp.provisioning_uri(totp.generate_secret(), "ana@example.com")
>>> provisioning_qr_data_uri(uri).startswith("data:image/svg+xml;base64,")
True

Parameters:

Name Type Description Default
uri str

The otpauth:// URI from :meth:TOTPHelper.provisioning_uri.

required
kind ProvisioningQrKind

"svg" (default) or "png".

'svg'
scale int

Pixels (SVG user units) per module. See :data:PROVISIONING_QR_SCALE.

PROVISIONING_QR_SCALE
border int

Quiet zone in modules. See :data:PROVISIONING_QR_BORDER.

PROVISIONING_QR_BORDER

Returns:

Name Type Description
str str

data:image/svg+xml;base64,... or

str

data:image/png;base64,....

Raises:

Type Description
ValueError

When uri is empty or too long for a QR code, or kind is neither "svg" nor "png".

ImportError

When segno (the [mfa] extra) is missing.

ProvisioningQrKind module-attribute

ProvisioningQrKind = Literal['svg', 'png']

Image format of :func:provisioning_qr_data_uri.

ProvisioningQrBackground module-attribute

ProvisioningQrBackground = Literal['dark', 'light']

Background colour of the terminal :func:provisioning_qr_terminal prints to.

PROVISIONING_QR_ERROR module-attribute

PROVISIONING_QR_ERROR: Final[Literal['l', 'm', 'q', 'h']] = 'm'

Error-correction level of the provisioning QR code: M (15 %).

The symbol is scanned off a screen, not off a creased voucher, so the recovery that :data:tempest_fastapi_sdk.pdf.QR_ERROR_CORRECTION buys with H is spent on modules the camera does not need. segno still raises the level when the chosen version has room for it (boost_error), so the symbol is never denser than M requires.

PROVISIONING_QR_BORDER module-attribute

PROVISIONING_QR_BORDER: Final[int] = 4

Quiet zone, in modules, around the provisioning QR code.

The four modules ISO/IEC 18004 asks for. Unlike the voucher, nothing around the symbol supplies white space: a terminal is usually dark and a data: URI lands wherever the app puts it, so the quiet zone has to be part of the drawing.

PROVISIONING_QR_SCALE module-attribute

PROVISIONING_QR_SCALE: Final[int] = 5

Pixels (SVG user units) per module in :func:provisioning_qr_data_uri.

A 95-character otpauth:// URI encodes at version 6 (41 modules), so the default image is (41 + 2 * 4) * 5 = 245 pixels wide — readable in an <img> with no CSS. The SVG scales without loss either way.

EmailUtils

EmailUtils(
    host: str,
    port: int,
    *,
    from_addr: str,
    username: str | None = None,
    password: str | None = None,
    use_tls: bool = False,
    use_starttls: bool = True,
    timeout: float = 30.0,
    template_dir: str | Path | None = None,
    enabled: bool = True,
)

Send transactional emails via SMTP.

Connection configuration is supplied at construction time; each :meth:send call opens a fresh SMTP connection (aiosmtplib's high-level send helper handles connect/login/quit). For high-volume scenarios consider holding a persistent connection via aiosmtplib.SMTP directly.

Attributes:

Name Type Description
host str

SMTP server hostname.

port int

SMTP port.

from_addr str

Default sender address used as the From header.

use_tls bool

Whether to connect using SSL/TLS from the start (port 465 style).

use_starttls bool

Whether to upgrade to TLS via STARTTLS after connect (port 587 style). Opportunistic — the upgrade happens only when the server advertises STARTTLS, so a plain server (e.g. MailHog) is left as-is instead of raising.

enabled bool

False when the e-mail integration is switched off; every send then raises IntegrationDisabledException.

Initialize.

Parameters:

Name Type Description Default
host str

SMTP server hostname.

required
port int

SMTP port. Common values: 25 (plain), 465 (SSL/TLS), 587 (STARTTLS).

required
from_addr str

Default sender address.

required
username str | None

Auth username.

None
password str | None

Auth password.

None
use_tls bool

Connect using SSL/TLS immediately. Set this for port 465.

False
use_starttls bool

Upgrade to TLS via STARTTLS after connect. Set this for port 587 (default). The upgrade is opportunistic — it is skipped (rather than raising) when the server doesn't advertise STARTTLS, so plain dev servers like MailHog work without extra config.

True
timeout float

SMTP socket timeout in seconds.

30.0
template_dir str | Path | None

Directory holding Jinja2 templates for :meth:render_template. Optional — templates can be opted into later, and the directory is only loaded on first render. Requires the [email] extra (Jinja2 ships alongside aiosmtplib).

None
enabled bool

False builds a mailer for an integration switched off by EMAIL_ENABLED=false: :meth:send and :meth:send_many raise :class:~tempest_fastapi_sdk.exceptions.IntegrationDisabledException (503, details={"integration": "email"}) before building any message, and the [email] extra is not required. :meth:render_template keeps working. EmailSettings.email_kwargs passes it. Default True.

True

Raises:

Type Description
ImportError

When the [email] extra is not installed and enabled is True.

Notes

Jinja environments are memoized one per resolved locale, plus a None key for locale-less renders, and built lazily on first use.

require_enabled

require_enabled() -> None

Refuse to go on when the e-mail integration is switched off.

Called first by :meth:send and :meth:send_many. Code that has to decide before a side effect whether a mail can go out — the auth service refuses a signup that would need an activation link — calls it directly.

Raises:

Type Description
IntegrationDisabledException

When the mailer was built with enabled=False.

send async

send(
    to: str | Iterable[str],
    subject: str,
    body: str,
    *,
    html: str | None = None,
    cc: Iterable[str] | None = None,
    bcc: Iterable[str] | None = None,
    attachments: Iterable[Path | EmailAttachment] | None = None,
    reply_to: str | None = None,
    from_addr: str | None = None,
) -> None

Send a single email.

Parameters:

Name Type Description Default
to str | Iterable[str]

Recipient address(es). Listed in the To header.

required
subject str

Subject line.

required
body str

Plain-text body. Always sent; the HTML alternative is added as a multipart child when html is also provided.

required
html str | None

Optional HTML alternative body.

None
cc Iterable[str] | None

Additional Cc recipients.

None
bcc Iterable[str] | None

Bcc recipients (added to the envelope, not the headers).

None
attachments Iterable[Path | EmailAttachment] | None

Files to attach. A Path is read from disk and its content type is guessed from its name; an :class:EmailAttachment carries its bytes in memory, with an explicit or guessed type.

None
reply_to str | None

Value for the Reply-To header.

None
from_addr str | None

Override the default sender for this message.

None

Raises:

Type Description
IntegrationDisabledException

When the mailer was built with enabled=False. Nothing is sent.

EmailDeliveryException

When the transport fails — the host does not resolve, the connection is refused or times out, the TLS handshake fails, the login is rejected, or the server refuses the message (503 EMAIL_UNAVAILABLE). The original aiosmtplib / OSError is chained as __cause__, so the SMTP reply code stays reachable. Logged once at ERROR first — see :meth:_raise_delivery_failed.

OSError

When an attachments path cannot be read. That is the caller's input, not the transport, so it is not translated.

ValueError

When an attachments path's name carries a forbidden character (see :class:EmailAttachment).

Notes

STARTTLS is negotiated opportunistically: aiosmtplib upgrades the connection only when the server advertises support, so a plain server such as MailHog no longer hard-fails with SMTP STARTTLS extension not supported by server. Passing start_tls=True would force the upgrade and raise there instead. use_tls (implicit TLS / SMTPS) is mutually exclusive with STARTTLS, so the upgrade is disabled in that case.

send_many async

send_many(
    recipients: Iterable[str],
    subject: str,
    body: str,
    *,
    html: str | None = None,
    reply_to: str | None = None,
    from_addr: str | None = None,
    batch_size: int = DEFAULT_BULK_BATCH_SIZE,
    max_concurrency: int = DEFAULT_BULK_CONCURRENCY,
) -> BulkEmailReport

Send one message to many recipients and report what happened.

The loop a caller would otherwise write — for user in users: await mailer.send(...) — has four problems this method exists to remove, and the first two are why it is not simply gather over :meth:send:

  • One connection per message. :meth:send opens, authenticates and quits every time, so five thousand recipients cost five thousand TLS handshakes. Here each batch opens one connection and reuses it, which is where the time goes: connections drop from len(recipients) to len(recipients) / batch_size.
  • Unbounded fan-out. gather over the whole list opens as many connections as there are recipients, and every hosted SMTP provider caps how many a sender may hold at once — past the cap the extra ones are throttled or dropped, and the cap belongs to the provider, not to us. At most max_concurrency connections are open at once — the same default the Web Push broadcast uses.
  • Partial failure is unreportable. The first bad address ends the loop; wrapping each item in try/except throws the detail away. Per-recipient failures never raise here, they land in the report.
  • A dead address looks like a busy one. SMTP separates 5xx (this mailbox does not exist — stop trying) from 4xx (full, greylisted — try later), and the two call for opposite actions: prune versus requeue. They are reported apart.

Concurrency is per connection, not per message: SMTP is a serial protocol on a single socket, so a batch is sent sequentially over its own connection and parallelism comes from running several batches at once.

Parameters:

Name Type Description Default
recipients Iterable[str]

Addresses to deliver to. Each gets its own message — nobody sees anyone else's address.

required
subject str

Subject line, shared by every message.

required
body str

Plain-text body, shared by every message.

required
html str | None

Optional HTML alternative body.

None
reply_to str | None

Value for the Reply-To header.

None
from_addr str | None

Override the default sender.

None
batch_size int

Recipients per connection. Larger means fewer handshakes and a longer-lived connection, which some providers cut off on their own schedule.

DEFAULT_BULK_BATCH_SIZE
max_concurrency int

Connections open at once.

DEFAULT_BULK_CONCURRENCY

Returns:

Name Type Description
BulkEmailReport BulkEmailReport

Delivered count plus the permanent and

BulkEmailReport

transient failures, each with the code and message the server

BulkEmailReport

gave.

Raises:

Type Description
IntegrationDisabledException

When the mailer was built with enabled=False. Nothing is sent.

EmailDeliveryException

Only for a failure of the operation itself — the host does not resolve, the connection is refused or times out, the TLS handshake fails, authentication is rejected, the server drops the connection mid-batch. Same 503 EMAIL_UNAVAILABLE as :meth:send, with the aiosmtplib / OSError chained as __cause__. A failure that belongs to one recipient is reported, never raised. Batches already delivered when another batch fails are not reported: the raise replaces the report.

ValueError

When batch_size or max_concurrency is not positive, which would otherwise deliver nothing at all.

render_template

render_template(
    template_name: str, context: dict[str, Any], *, locale: str | None = None
) -> str

Render a Jinja2 template from template_dir with context.

The Jinja environment is built lazily on first call and memoized per locale — subsequent renders for the same locale reuse the same loader. HTML autoescaping is enabled for .html / .htm / .xml templates so caller-supplied values cannot break out into markup.

Template lookup order (first hit wins):

  1. template_dir/<locale>/<name> — project override, this locale.
  2. template_dir/<name> — project override, legacy flat layout.
  3. <sdk>/auth/templates/<locale>/<name> — SDK bundled, this locale (e.g. the localized activation / password-reset emails).

When locale is None the locale subdirectories are skipped and only the flat template_dir and the SDK bundled root are searched — this preserves the pre-0.59 behavior for generic callers that ship their own template_dir.

Parameters:

Name Type Description Default
template_name str

Template filename (e.g. "welcome.html", "password_reset.txt").

required
context dict[str, Any]

Variables exposed inside the template.

required
locale str | None

Canonical locale (e.g. "pt-BR" / "en-US") selecting the per-locale template subdirectory. None uses the flat layout.

None

Returns:

Name Type Description
str str

Rendered template body — pass this directly to

str

meth:send as body (text) or html.

Raises:

Type Description
RuntimeError

When template_dir was not configured at construction time.

ImportError

When Jinja2 is missing (it ships with the [email] extra since v0.24.0; older installs may need to upgrade).

TemplateNotFound

When the file cannot be located under template_dir.

Example:

>>> emails = EmailUtils(..., template_dir="emails/")
>>> html = emails.render_template(
...     "welcome.html",
...     {"user_name": "Ana", "app_url": "https://app/"},
...     locale="pt-BR",
... )
>>> await emails.send(
...     "ana@example.com",
...     subject="Bem-vinda!",
...     body="Bem-vinda, Ana!",
...     html=html,
... )
Notes

Templates resolve through a ChoiceLoader: the project's own template_dir first, then the SDK's bundled ones (auth/activation, auth/password_reset). That is what lets the bundled auth flow render its default emails without the caller having to ship a template_dir at all.

The bundled templates live under per-locale subdirectories (pt-BR / en-US), so a locale-less render falls back to the default locale's subdirectory to reach them.

EmailAttachment dataclass

EmailAttachment(filename: str, content: bytes, content_type: str | None = None)

A file attached from memory, without touching the disk.

Pass it in attachments next to (or instead of) a :class:~pathlib.Path — for example the bytes a PDF renderer returns.

Attributes:

Name Type Description
filename str

Name the recipient sees. Must be non-empty and free of line breaks, NUL, / and \.

content bytes

The file's bytes.

content_type str | None

type/subtype such as "application/pdf", without parameters. None (the default) guesses it from filename with :func:mimetypes.guess_type — the same guess a :class:~pathlib.Path attachment gets. An unknown extension, or a compression suffix such as .gz, falls back to application/octet-stream.

Raises:

Type Description
ValueError

When filename is empty or carries a forbidden character, or content_type is not a bare type/subtype.

resolved_content_type property

resolved_content_type: str

The content type the message is sent with.

Returns:

Name Type Description
str str

content_type when given, otherwise the type guessed

str

from filename.

from_path classmethod

from_path(path: Path) -> EmailAttachment

Read a file from disk into an attachment.

Parameters:

Name Type Description Default
path Path

The file to read. Its name becomes the attachment filename and drives the content-type guess.

required

Returns:

Name Type Description
EmailAttachment EmailAttachment

The attachment, with content_type left

EmailAttachment

None so the type is guessed from the name.

Raises:

Type Description
OSError

When the file cannot be read.

ValueError

When the file name carries a forbidden character.

UploadUtils

UploadUtils(
    source: str | Path | AsyncMinIOClient | None = None,
    *,
    backend: UploadStorage | None = None,
    max_size_bytes: int | None = None,
    allowed_extensions: set[str] | None = None,
    allowed_mimetypes: set[str] | None = None,
    verify_magic_bytes: bool = False,
    require_known_signature: bool = True,
    chunk_size: int = 1024 * 1024,
)

Persist uploaded files to local disk with opt-in validation.

Validation is incremental: extension and MIME type are checked against the configured whitelists before reading any bytes; the file's real content is optionally sniffed from its first bytes (verify_magic_bytes); and size is enforced as the stream is consumed so oversized uploads don't fill the disk before being rejected.

Saved files are streamed in chunks so memory usage stays bounded regardless of the upload size.

Attributes:

Name Type Description
upload_dir Path | None

Local base directory when constructed with a path; None in MinIO mode.

max_size_bytes int | None

Reject uploads larger than this. None disables the size check; a constructor value of 0 is stored as None.

allowed_extensions set[str] | None

Whitelist of file extensions (lowercase, no dot). None disables the extension check; an empty constructor set is stored as None.

allowed_mimetypes set[str] | None

Whitelist of MIME types (lowercase). None disables the MIME check; an empty constructor set is stored as None.

require_known_signature bool

With verify_magic_bytes on, whether an upload whose signature is unrecognized is rejected. True (the default, and the behaviour before this option existed) rejects it; False rejects only a contradiction — the declared type is one :func:sniff_mime knows and the bytes do not carry it.

verify_magic_bytes bool

When True, the first bytes of every upload are sniffed (:func:sniff_mime) and the detected type must be consistent with the declared type / allow-list. Defends against polyglots and content/MIME mismatches. Only enable when every accepted format is one :func:sniff_mime recognizes (images, PDF) — otherwise a legitimate but unsniffable upload is rejected.

Initialize with a local directory, a MinIO client, or a backend.

Parameters:

Name Type Description Default
source str | Path | AsyncMinIOClient | None

Where uploads are persisted. A directory path stores files on local disk (created if missing); an AsyncMinIOClient stores them in its bucket. The backend is fixed here, so callers never pass it per :meth:save. May be None only when a ready-made backend is supplied.

None
backend UploadStorage | None

A pre-built storage backend to use directly, bypassing the source-based selection. Lets a facade such as :class:~tempest_fastapi_sdk.FileStoreUtils construct one backend and share it. When given, source is used only to expose :attr:upload_dir (set from a path, None otherwise) and no backend is built here.

None
max_size_bytes int | None

Reject uploads larger than this. None or 0 disables the size check -- 0 means "no limit", matching UPLOAD_MAX_SIZE_BYTES in :class:~tempest_fastapi_sdk.settings.UploadSettings, so UploadUtils(**settings.upload_kwargs()) honours the documented setting instead of rejecting every non-empty file.

None
allowed_extensions set[str] | None

Whitelist of file extensions. Leading dots and case are normalized internally so {"PNG", ".jpg"} works as expected. None or an empty set disables the check: an empty allow-list would refuse every upload, and the settings mixin documents an empty UPLOAD_ALLOWED_EXTENSIONS as "any extension".

None
allowed_mimetypes set[str] | None

Whitelist of MIME types (case-insensitive, e.g. {"image/png"}). None or an empty set disables the check, for the same reason as allowed_extensions.

None
verify_magic_bytes bool

Sniff the first bytes of each upload and reject content that does not match its declared type / the allow-list. See the class attribute docs for the caveat. Default False.

False
require_known_signature bool

Whether an upload whose signature :func:sniff_mime does not recognize is rejected. Only consulted when verify_magic_bytes is on. True is the historical behaviour and the safe default for an image-only allow-list; False is what a general file store wants, because plain text, CSV and JSON carry no signature at all and would otherwise be refused outright. With False a contradiction is still refused: declaring image/jpeg and sending bytes with no JPEG signature fails, because image/jpeg is in :data:SNIFFABLE_MIMETYPES.

True
chunk_size int

Stream read chunk in bytes. Defaults to 1 MiB; raise to trade memory for fewer syscalls.

1024 * 1024

Raises:

Type Description
ValueError

When neither source nor backend is given.

ImportError

When the local backend is selected but the [upload] extra is not installed.

validate

validate(file: UploadFile) -> None

Validate extension and MIME type before reading the stream.

Size and content (magic bytes) cannot be checked here because they require reading the stream; they are enforced incrementally in :meth:save as bytes are consumed.

Parameters:

Name Type Description Default
file UploadFile

The FastAPI upload to validate.

required

Raises:

Type Description
InvalidFileTypeException

If the extension or MIME type is not in the configured whitelist.

save async

save(
    file: UploadFile,
    *,
    subdir: str = "",
    filename: str | None = None,
    keep_original_name: bool = False,
    content_validator: Callable[[bytes], bool] | None = None,
    hasher: Any | None = None,
) -> Path

Validate and persist file to the configured backend.

The backend (local disk or MinIO) is the one chosen at construction — the validation pipeline (extension / MIME / size / magic bytes / content_validator) is identical for either.

Parameters:

Name Type Description Default
file UploadFile

The FastAPI upload.

required
subdir str

Optional sub-directory / key prefix (e.g. "avatars"). Created on demand for local; used as a key prefix for MinIO.

''
filename str | None

Explicit final filename (e.g. f"{user_id}.jpg") for deterministic, addressable names. Reduced to its basename and guarded against path traversal. Takes precedence over keep_original_name.

None
keep_original_name bool

When True (and filename is not given), preserves the upload's original filename; otherwise generates a UUID-based name with the original extension. Default False so collisions are impossible.

False
content_validator Callable[[bytes], bool] | None

Optional predicate run on the first chunk read from the stream. Returning False aborts the save (and removes the partial object) before any further bytes are written — e.g. lambda b: sniff_mime(b) in {"image/png"}.

It sees only that first chunk, which is what makes rejecting early cheap — and what makes it useless for anything that must read the whole file. Accumulating a SHA-256 inside it digests the first chunk and nothing else, and the result looks like a valid digest of the upload. Pass hasher for that.

None
hasher Any | None

A hashlib object fed every chunk as the file streams past, so the caller can read hasher.hexdigest() after save returns without a second pass over the stored object. Left None, nothing is hashed.

None

Returns:

Name Type Description
Path Path

Path(storage_key) — the key to read the file back

Path

(downloads.download(str(result))). Call str(result)

Path

for the bare key.

Raises:

Type Description
InvalidFileTypeException

If the extension/MIME violates the whitelist, the content_validator rejects the bytes, or verify_magic_bytes detects a content mismatch.

FileTooLargeException

If the stream exceeds max_size_bytes mid-write; the partial object is removed before raising.

delete async

delete(key: Path | str) -> bool

Delete a previously saved object via the configured backend.

For the local backend the key resolves under the base directory (path-traversal attempts raise InvalidFileTypeException); for MinIO it is the object key.

Parameters:

Name Type Description Default
key Path | str

The storage key returned by :meth:save.

required

Returns:

Name Type Description
bool bool

True if the object existed and was deleted,

bool

False when it was already missing.

Raises:

Type Description
InvalidFileTypeException

Local backend, when key resolves outside the base directory (path traversal attempt).

replace async

replace(
    old_key: Path | str | None,
    file: UploadFile,
    *,
    subdir: str = "",
    filename: str | None = None,
    keep_original_name: bool = False,
    content_validator: Callable[[bytes], bool] | None = None,
    hasher: Any | None = None,
) -> Path

Save a new object and delete the one it replaces.

The common "swap the user's avatar / attachment" flow in one call: the new file is persisted first (so a validation error or a write failure leaves the old object untouched), then old_key is deleted through the same configured backend — avoiding the mistake of saving through one backend and deleting through another.

Parameters:

Name Type Description Default
old_key Path | str | None

Storage key of the object being replaced (typically the value currently stored on the model). None or empty skips the delete, so the same call works for the first upload and for replacements.

required
file UploadFile

The new FastAPI upload.

required
subdir str

Optional sub-directory / key prefix.

''
filename str | None

Explicit final filename. Same rules as :meth:save.

None
keep_original_name bool

Preserve the upload's original filename when filename is not given.

False
content_validator Callable[[bytes], bool] | None

Optional predicate run on the first chunk; see :meth:save.

None

Returns:

Name Type Description
Path Path

Path(storage_key) of the newly saved object.

Raises:

Type Description
InvalidFileTypeException

If validation rejects the new file (the old object is left intact).

FileTooLargeException

If the new stream exceeds max_size_bytes (the old object is left intact).

SNIFFABLE_MIMETYPES module-attribute

SNIFFABLE_MIMETYPES: frozenset[str] = frozenset(
    {mime for _signature, mime in _MAGIC_SIGNATURES} | {"image/webp", "image/heic"}
)

The MIME types :func:sniff_mime can recognize from the bytes.

A type outside this set carries no signature to check — plain text, CSV, JSON, most office and archive formats — so "no signature found" says nothing about it. Membership is what lets require_known_signature=False tell a contradiction (declared image/jpeg, no JPEG signature) apart from an unverifiable upload (declared text/csv, and text has no magic bytes).

sniff_mime

sniff_mime(prefix: bytes) -> str | None

Detect a file's MIME type from its leading bytes.

Performs magic-byte sniffing on the first bytes read from an upload stream and returns the MIME the bytes actually represent — regardless of the Content-Type the client declared. Compare the result with the declared type (or an allow-list) to reject content/declaration mismatches such as an HTML payload uploaded as image/jpeg.

Recognizes JPEG, PNG, GIF, BMP, WebP, HEIC and PDF. Returns None for anything else (text, archives, office documents, audio/video containers, AVIF, …) — absence of a match means "not one of the sniffable binary formats", not "invalid".

HEIC is an ISO-BMFF ftyp box: prefix[4:8] is ftyp and prefix[8:12] the major brand. A major brand in :data:HEIC_BRANDS is HEIC; a codec-neutral one (:data:HEIF_STRUCTURAL_BRANDS) is HEIC only when a compatible brand of the box (from byte 16 up to the box size) is in :data:HEIC_BRANDS. An AVIF file (major brand avif, or mif1 with only AV1 compatible brands) returns None.

Parameters:

Name Type Description Default
prefix bytes

The first bytes of the file (≥32 bytes recommended so the WebP RIFF…WEBP marker and the compatible brands of an HEIF ftyp box can be checked; shorter inputs still match the fixed-prefix signatures).

required

Returns:

Type Description
str | None

str | None: The detected MIME type, or None when no known signature matches.

HEIC_BRANDS module-attribute

HEIC_BRANDS: frozenset[bytes] = frozenset(
    {b"heic", b"heix", b"heim", b"heis", b"hevc", b"hevx", b"hevm", b"hevs"}
)

ISO-BMFF ftyp brands of an HEVC-coded HEIF file (HEIC).

Ported from libheif's heif_get_file_mime_type (libheif/api/libheif/heif_brands.cc, commit 1b2a9a8), which maps heic/heix/heim/heis to image/heic and hevc/hevx/hevm/hevs to image/heic-sequence: the HEVC-coded brands of HEIF (ISO/IEC 23008-12). :func:sniff_mime folds both groups into image/heic, so an image sequence declared as image/heic is not refused as a contradiction.

AV1 brands (avif, avis) are deliberately absent: an AVIF file is a HEIF container too, but not HEIC.

HEIF_STRUCTURAL_BRANDS module-attribute

HEIF_STRUCTURAL_BRANDS: frozenset[bytes] = frozenset({b'mif1', b'msf1'})

Codec-neutral HEIF brands (image item, image sequence).

Ported from libheif's heif_get_file_mime_type (libheif/api/libheif/heif_brands.cc, commit 1b2a9a8), which reports them as the generic image/heif/image/heif-sequence. Some encoders write one of them as the major brand of an HEIC file, and others of an AVIF file, so on their own they do not say which codec is inside: :func:sniff_mime reports image/heic for them only when a compatible brand of the ftyp box is in :data:HEIC_BRANDS.

read_upload_capped async

read_upload_capped(
    upload: UploadFile, *, max_bytes: int, label: str = "upload"
) -> bytes

Read an uploaded file into memory, refusing one that is too large.

Reads in :data:UPLOAD_READ_CHUNK_BYTES chunks and stops at the ceiling instead of calling await upload.read() and measuring afterwards: measuring afterwards means the oversized upload already occupied the memory it was meant to be denied. This is the reader every route of the SDK that takes a whole file into memory uses (make_genai_router's /transcribe, make_voice_router, and make_vision_router).

Parameters:

Name Type Description Default
upload UploadFile

The uploaded file.

required
max_bytes int

The largest accepted size, in bytes.

required
label str

What the file is, used in the error message ("audio is larger than ... bytes"). Defaults to "upload".

'upload'

Returns:

Name Type Description
bytes bytes

The whole upload.

Raises:

Type Description
UploadTooLargeException

When the upload exceeds max_bytes (413, code="UPLOAD_TOO_LARGE"); the details carry max_bytes. Up to 0.348.0 this was a ValidationException (422).

UPLOAD_READ_CHUNK_BYTES module-attribute

UPLOAD_READ_CHUNK_BYTES: int = 1 << 20

Chunk size :func:read_upload_capped reads with (1 MiB).

The ceiling is checked after every chunk, so an oversized upload costs at most max_bytes plus one chunk of memory before it is refused.

relative_luminance

relative_luminance(color: str) -> float | None

Return the WCAG relative luminance of a hex color.

Parameters:

Name Type Description Default
color str

#rgb or #rrggbb.

required

Returns:

Type Description
float | None

float | None: 0.0 (black) to 1.0 (white), or None when

float | None

color is not a hex color ("rebeccapurple", rgb(...)).

is_light

is_light(color: str) -> bool

Tell whether a background needs dark text.

Parameters:

Name Type Description Default
color str

The background.

required

Returns:

Name Type Description
bool bool

True for a hex color above

bool

data:LIGHT_BACKGROUND_THRESHOLD. A color that is not hex is

bool

assumed dark, the case a named brand color usually is.

DownloadUtils

DownloadUtils(source: str | Path | AsyncMinIOClient)

Serve files for download — from a local directory or MinIO.

Pick the backend once at construction:

  • pass a directory (DownloadUtils("var/uploads")) to serve files from local disk, or
  • pass an :class:~tempest_fastapi_sdk.AsyncMinIOClient (DownloadUtils(minio_client)) to stream objects straight from a bucket.

Then call :meth:download with the file's path/key for either backend. For local disk, all reads are confined to base_dir: a path that resolves outside it (../ traversal, absolute paths, symlink escapes) raises :class:NotFoundException rather than leaking arbitrary files — the same 404 as a missing file.

Attributes:

Name Type Description
base_dir Path | None

Resolved local root, or None in MinIO mode.

Initialize with a local directory or a MinIO client.

Parameters:

Name Type Description Default
source str | Path | AsyncMinIOClient

A directory path to serve files from local disk, or an AsyncMinIOClient to stream objects from a bucket. The local directory is resolved to an absolute path; it need not exist yet.

required

download async

download(
    key: str,
    *,
    subdir: str = "",
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool = True,
    request: Request | None = None,
    cache_control: str | None = None,
    headers: dict[str, str] | None = None,
) -> Response

Build a download response for key from the configured backend.

Works the same for both backends: local disk returns a streamed FileResponse (range-aware), MinIO returns a StreamingResponse proxied from the bucket — range- and validator-aware when request is passed.

Parameters:

Name Type Description Default
key str

File path (local, relative to base_dir) or object key (MinIO).

required
subdir str

Optional sub-directory / key prefix.

''
filename str | None

Name presented to the client. Defaults to the basename of key.

None
media_type str | None

MIME type. Guessed/derived when omitted.

None
as_attachment bool

True forces a download; False asks for inline, granted only to a type in :data:INLINE_SAFE_MEDIA_TYPES.

True
request Request | None

The incoming request. MinIO mode needs it to answer Range with 206 and validators with 304 (see :meth:AsyncMinIOClient.download_response); local mode ignores it, because FileResponse already reads Range from the ASGI scope.

None
cache_control str | None

Cache-Control value for the response. None sends none.

None
headers dict[str, str] | None

Extra response headers. One named like a security default (X-Content-Type-Options, Content-Security-Policy, Cross-Origin-Resource-Policy) replaces that default.

None

Returns:

Name Type Description
Response Response

A FileResponse (local) or StreamingResponse

Response

(MinIO) ready to return from a router.

Raises:

Type Description
NotFoundException

Local mode, when the path escapes base_dir or the file is missing.

S3Error

MinIO mode, when the object is missing.

resolve

resolve(relative_path: Path | str, *, subdir: str = '') -> Path

Resolve a client-supplied path safely under base_dir.

Parameters:

Name Type Description Default
relative_path Path | str

Path relative to base_dir (or base_dir/subdir). Absolute inputs and .. segments that escape the base are rejected.

required
subdir str

Optional sub-directory between base_dir and relative_path (e.g. "invoices").

''

Returns:

Name Type Description
Path Path

The resolved, existing file path.

Raises:

Type Description
NotFoundException

If the path escapes base_dir, does not exist, or is not a regular file.

RuntimeError

When this DownloadUtils was built with a MinIO client (no local base_dir) — use :meth:download.

file_response

file_response(
    relative_path: Path | str,
    *,
    subdir: str = "",
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool = True,
    headers: dict[str, str] | None = None,
) -> FileResponse

Build a FileResponse streaming a file from disk.

The response is streamed in chunks by Starlette and supports HTTP range requests, so large files never load fully into memory.

Parameters:

Name Type Description Default
relative_path Path | str

Path to the file, relative to base_dir (resolved via :meth:resolve).

required
subdir str

Optional sub-directory under base_dir.

''
filename str | None

Name presented to the client. Defaults to the file's own basename.

None
media_type str | None

MIME type. Guessed from the filename extension when omitted, falling back to application/octet-stream.

None
as_attachment bool

True forces a download; False asks for inline (e.g. view a PDF in-browser), granted only to a type in :data:INLINE_SAFE_MEDIA_TYPES. Default True.

True
headers dict[str, str] | None

Extra response headers. One named like a security default (X-Content-Type-Options, Content-Security-Policy, Cross-Origin-Resource-Policy) replaces that default.

None

Returns:

Name Type Description
FileResponse FileResponse

The response to return from a router.

Raises:

Type Description
NotFoundException

If the file cannot be located (see :meth:resolve).

stream

stream(
    content: bytes | Iterable[bytes] | AsyncIterable[bytes],
    *,
    filename: str,
    media_type: str | None = None,
    as_attachment: bool = True,
    headers: dict[str, str] | None = None,
) -> StreamingResponse

Build a StreamingResponse from in-memory bytes or a generator.

Use when the payload is produced on the fly (a generated report, a zip built in memory, decrypted bytes) rather than read from base_dir. base_dir is not consulted here.

Parameters:

Name Type Description Default
content bytes | Iterable[bytes] | AsyncIterable[bytes]

The payload. Raw bytes are wrapped in a single-chunk iterator; sync and async byte iterables are streamed as-is.

required
filename str

Name presented to the client.

required
media_type str | None

MIME type. Guessed from filename when omitted, falling back to application/octet-stream.

None
as_attachment bool

True forces a download; False asks for inline, granted only to a type in :data:INLINE_SAFE_MEDIA_TYPES. Default True.

True
headers dict[str, str] | None

Extra response headers. One named like a security default (X-Content-Type-Options, Content-Security-Policy, Cross-Origin-Resource-Policy) replaces that default.

None

Returns:

Name Type Description
StreamingResponse StreamingResponse

The response to return from a router.

INLINE_SAFE_MEDIA_TYPES module-attribute

INLINE_SAFE_MEDIA_TYPES: frozenset[str] = frozenset(
    {
        "application/pdf",
        "audio/aac",
        "audio/flac",
        "audio/mp4",
        "audio/mpeg",
        "audio/ogg",
        "audio/wav",
        "audio/webm",
        "audio/x-wav",
        "image/avif",
        "image/gif",
        "image/jpeg",
        "image/png",
        "image/webp",
        "text/plain",
        "video/mp4",
        "video/ogg",
        "video/quicktime",
        "video/webm",
    }
)

Media types a download may serve inline when the caller asks for it.

A download answers on the API's own origin, and inline is what lets the browser render the bytes as a document of that origin. text/html there is a page that runs script with the viewer's session on the API; image/svg+xml is the same risk behind an image type, since SVG can carry <script>. The list is therefore an allowlist: a type absent from it is served as attachment even with as_attachment=False, and so is a type the SDK does not know at build time (None).

What is inside is raster images, application/pdf, text/plain and common audio and video — the inline uses a download helper is asked for (<img>, <video>, viewing a PDF or a log in the browser). SVG and HTML are left out on purpose. To serve another type inline, build the response yourself; the helpers do not take an override, because the whole point is that an uploader-chosen type cannot reach inline.

guess_media_type

guess_media_type(filename: str) -> str | None

Guess a file's media type from its name, independent of the host.

Looks the extension up in this module's table first, then asks :func:mimetypes.guess_type. The table is what keeps the answer the same on a developer machine and in a slim container image that has no /etc/mime.types.

Parameters:

Name Type Description Default
filename str

A file name or path; only the extension is read, case-insensitively.

required

Returns:

Type Description
str | None

str | None: The media type, or None when neither source knows

str | None

the extension.

ImageMediaTypeEnum

Bases: BaseStrEnum

Image media types whose bytes :func:sniff_mime can verify.

Exactly the image/* members of :data:~tempest_fastapi_sdk.utils.upload.SNIFFABLE_MIMETYPES, so every member can be checked against the upload's real content with :meth:matches. Use it as the type of a Pydantic field that carries a declared Content-Type: the input is matched case-insensitively, with surrounding whitespace stripped, and the aliases the upload helpers accept (image/jpg, image/pjpeg → JPEG, image/x-png → PNG) resolve to the canonical member. Anything else fails validation with Pydantic's usual enum error (422 in a route), and the JSON Schema lists the canonical values.

Examples:

>>> ImageMediaTypeEnum(" Image/JPG ")
<ImageMediaTypeEnum.JPEG: 'image/jpeg'>
>>> ImageMediaTypeEnum.HEIC.extension
'heic'

extension property

extension: str

The conventional file extension, lowercase and without the dot.

Returns:

Name Type Description
str str

"jpg", "png", "gif", "bmp", "webp" or

str

"heic".

matches

matches(data: bytes) -> bool

Tell whether data carries this type's signature.

The declared type is client-controlled; this checks it against what the bytes actually are, via :func:sniff_mime.

Parameters:

Name Type Description Default
data bytes

The file content, or at least its first 32 bytes (enough for every signature, including the compatible brands of an HEIF ftyp box).

required

Returns:

Name Type Description
bool bool

True when :func:sniff_mime detects exactly this

bool

type in data.

image_media_type_field

image_media_type_field(
    *allowed: ImageMediaTypeEnum,
    title: str = "Image type",
    description: str | None = None,
    examples: list[str] | None = None,
) -> FieldInfo

Build the metadata of a field accepting some ImageMediaTypeEnum values.

For a schema that takes the declared type of an upload — the photo of an evidence, of a product — and must refuse the types it does not store. Put it in Annotated next to ImageMediaTypeEnum, so the static type is the enum::

class EvidenceCreateSchema(BaseSchema):
    photo_type: Annotated[
        ImageMediaTypeEnum,
        image_media_type_field(
            ImageMediaTypeEnum.JPEG,
            ImageMediaTypeEnum.PNG,
            ImageMediaTypeEnum.WEBP,
            ImageMediaTypeEnum.HEIC,
            title="Photo type",
        ),
    ]

The value is normalized by :class:ImageMediaTypeEnum ("IMAGE/JPG " becomes image/jpeg), a type outside allowed is a 422, and the OpenAPI schema lists allowed only.

Parameters:

Name Type Description Default
*allowed ImageMediaTypeEnum

The accepted types. None means every member of :class:ImageMediaTypeEnum.

()
title str

The field title.

'Image type'
description str | None

The field description. None names the accepted types.

None
examples list[str] | None

The field examples. None uses the first accepted type.

None

Returns:

Name Type Description
FieldInfo FieldInfo

The field metadata, carrying the restriction.

AllowedImageMediaTypes

AllowedImageMediaTypes(allowed: Sequence[ImageMediaTypeEnum])

Pydantic metadata restricting an ImageMediaTypeEnum field to a subset.

Validates after the enum itself, so the normalization the enum already does — case, surrounding whitespace, aliases such as image/jpg — runs first, and narrows the OpenAPI schema to the allowed values only.

Attributes:

Name Type Description
allowed tuple[ImageMediaTypeEnum, ...]

The accepted types, in the order the schema lists them.

Store the accepted types.

Parameters:

Name Type Description Default
allowed Sequence[ImageMediaTypeEnum]

The accepted types.

required

Raises:

Type Description
ValueError

When allowed is empty.

RawTextField module-attribute

RawTextField = Annotated[str, StringConstraints(strip_whitespace=False)]

String kept exactly as sent, leading and trailing whitespace included.

:class:~tempest_fastapi_sdk.BaseSchema sets str_strip_whitespace=True, which is right for names and e-mails and wrong for content: a streaming delta " mundo" became "mundo" and a prompt reached the model different from what the client sent (#718). Annotating the field with this type overrides the model-wide setting for that field only, on construction and on assignment (validate_assignment). Measured on pydantic 2.13.5.

XLSX_MEDIA_TYPE module-attribute

XLSX_MEDIA_TYPE: str = (
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)

Media type of an Office Open XML workbook (.xlsx).

Ported from the media-types 10.1.0 package's /etc/mime.types.

DOCX_MEDIA_TYPE module-attribute

DOCX_MEDIA_TYPE: str = (
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)

Media type of an Office Open XML document (.docx).

Ported from the media-types 10.1.0 package's /etc/mime.types.

PPTX_MEDIA_TYPE module-attribute

PPTX_MEDIA_TYPE: str = (
    "application/vnd.openxmlformats-officedocument.presentationml.presentation"
)

Media type of an Office Open XML presentation (.pptx).

Ported from the media-types 10.1.0 package's /etc/mime.types.

strip_image_metadata

strip_image_metadata(
    data: bytes,
    media_type: ImageMediaTypeEnum | str,
    *,
    max_pixels: int = DEFAULT_MAX_IMAGE_PIXELS,
    jpeg_quality: int = DEFAULT_JPEG_QUALITY,
    webp_quality: int = DEFAULT_WEBP_QUALITY,
) -> bytes

Re-encode an image in its own format, without any metadata.

The image is decoded by Pillow, turned upright according to its EXIF orientation (ImageOps.exif_transpose, so a portrait photo does not come back lying on its side once the orientation tag is gone), and encoded again from its pixels alone. EXIF (GPS, device, capture time, embedded thumbnail), XMP, IPTC, the ICC color profile, comments and PNG text chunks are all left behind. The pixel size is kept (with width and height swapped when the orientation rotates by 90 degrees), and so are the mode and the transparency.

Format notes:

  • JPEG is re-encoded at jpeg_quality, which is lossy: the bytes differ from the source even for an image with no metadata.
  • WEBP stays lossless when the source is lossless; a lossy source is re-encoded at webp_quality.
  • GIF and WEBP animations come back as their first frame. Re-encoding every frame would multiply the decode cost by a frame count the client controls; a service that must keep animations should not route them through this function.
  • Dropping the ICC profile means the pixels are read as sRGB. Nothing changes for an sRGB photo; a wide-gamut one (Display P3, common on recent phones) can shift slightly in saturation.
  • image/heic is refused: Pillow ships no HEIC codec.

The function is CPU-bound and synchronous; from an async route, call it through asyncio.to_thread.

Parameters:

Name Type Description Default
data bytes

The image file content.

required
media_type ImageMediaTypeEnum | str

The declared media type, usually the client's Content-Type. A string resolves through :class:ImageMediaTypeEnum, aliases included.

required
max_pixels int

Ceiling on width * height, checked from the header before any pixel is decoded. Pillow's own process-wide guard (PIL.Image.MAX_IMAGE_PIXELS) still runs when the file is opened and is never changed here: above it Pillow emits a DecompressionBombWarning, above twice it Pillow refuses, and both cases surface as :class:ImageTooLargeException (the warning only when it is escalated to an error, otherwise this ceiling refuses next).

DEFAULT_MAX_IMAGE_PIXELS
jpeg_quality int

JPEG quality, 1 to 100.

DEFAULT_JPEG_QUALITY
webp_quality int

Lossy WEBP quality, 1 to 100.

DEFAULT_WEBP_QUALITY

Returns:

Name Type Description
bytes bytes

The re-encoded image, in the declared format.

Raises:

Type Description
ImportError

When the [image] extra (Pillow) is not installed.

ValueError

When max_pixels is not positive or a quality is outside 1-100.

ImageFormatUnsupportedException

When media_type is not an image type this function can re-encode (415).

ImageDecodeException

When the bytes are not an image of an accepted format, or are truncated or corrupt (422).

ImageTypeMismatchException

When the bytes are a different accepted format than the declared one (415).

ImageTooLargeException

When the image has more than max_pixels pixels (413).

Examples:

>>> import io
>>> from PIL import Image
>>> buffer = io.BytesIO()
>>> Image.new("RGB", (4, 2)).save(buffer, "JPEG", comment=b"secret")
>>> clean = strip_image_metadata(buffer.getvalue(), "image/jpeg")
>>> b"secret" in clean
False

DEFAULT_MAX_IMAGE_PIXELS module-attribute

DEFAULT_MAX_IMAGE_PIXELS: int = 50000000

Default ceiling on width * height accepted by :func:strip_image_metadata.

Fits the full-resolution output of a 48 or 50 megapixel phone sensor (8064 x 6048 is 48.8 million pixels). Memory grows with the pixel count: measured on Pillow 13.0.0 with an 8000 x 6000 JPEG (48 million pixels), the call's peak memory rose by about 186 MB for an upright photo and 368 MB for one its orientation rotates by 90 degrees (Pillow holds RGB at four bytes per pixel, and the rotation keeps two copies for a moment). Raise the ceiling only with that cost in mind.

DEFAULT_JPEG_QUALITY module-attribute

DEFAULT_JPEG_QUALITY: int = 90

Default JPEG quality used when re-encoding (Pillow's own default is 75).

DEFAULT_WEBP_QUALITY module-attribute

DEFAULT_WEBP_QUALITY: int = 90

Default quality for a lossy WEBP re-encode (Pillow's own default is 80).

A lossless source is re-encoded lossless, where quality does not apply.

FileStoreUtils

FileStoreUtils(
    source: str | Path | AsyncMinIOClient,
    *,
    max_size_bytes: int | None = None,
    allowed_extensions: set[str] | None = None,
    allowed_mimetypes: set[str] | None = None,
    verify_magic_bytes: bool = False,
    chunk_size: int = 1024 * 1024,
)

Single entry point for storing, serving and signing files.

Composes an :class:~tempest_fastapi_sdk.utils.upload.UploadUtils and a :class:~tempest_fastapi_sdk.utils.download.DownloadUtils over one storage backend, plus presign shortcuts for the MinIO backend. Use it when a service both persists and serves the same files and you want one configured object instead of three.

The individual pieces stay reachable for escape hatches: :attr:uploader, :attr:downloader, :attr:backend and :attr:client.

Attributes:

Name Type Description
uploader UploadUtils

Validation + persistence half.

downloader DownloadUtils

Read + serve half.

backend UploadStorage

The shared storage backend (LocalUploadStorage or MinIOUploadStorage).

client AsyncMinIOClient | None

The MinIO client when MinIO-backed, otherwise None (local disk).

Build the facade, selecting the backend from source.

Parameters:

Name Type Description Default
source str | Path | AsyncMinIOClient

A directory path for local disk, or an AsyncMinIOClient for MinIO / S3. To target a non-default bucket, set the client's default_bucket — both halves read it.

required
max_size_bytes int | None

Reject uploads larger than this. None disables the size check.

None
allowed_extensions set[str] | None

Whitelist of file extensions (leading dots and case normalized internally).

None
allowed_mimetypes set[str] | None

Whitelist of MIME types (case-insensitive).

None
verify_magic_bytes bool

Sniff the first bytes of each upload and reject content that mismatches its declared type / allow-list. Default False.

False
chunk_size int

Stream read chunk in bytes. Default 1 MiB.

1024 * 1024

Raises:

Type Description
ImportError

When the required extra ([upload] for local, [minio] for MinIO) is not installed.

validate

validate(file: UploadFile) -> None

Validate extension and MIME before reading the stream.

Parameters:

Name Type Description Default
file UploadFile

The FastAPI upload to validate.

required

Raises:

Type Description
InvalidFileTypeException

If the extension or MIME type is not in the configured whitelist.

save async

save(
    file: UploadFile,
    *,
    subdir: str = "",
    filename: str | None = None,
    keep_original_name: bool = False,
    content_validator: Callable[[bytes], bool] | None = None,
) -> Path

Validate and persist file to the configured backend.

Parameters:

Name Type Description Default
file UploadFile

The FastAPI upload.

required
subdir str

Optional sub-directory / key prefix.

''
filename str | None

Explicit final filename (sanitized to its basename). Takes precedence over keep_original_name.

None
keep_original_name bool

Preserve the original filename when filename is not given. Default False.

False
content_validator Callable[[bytes], bool] | None

Optional predicate run on the first chunk; False aborts the save.

None

Returns:

Name Type Description
Path Path

Path(storage_key) to read the file back with

Path

meth:download / :meth:presigned_get_url.

Raises:

Type Description
InvalidFileTypeException

On a whitelist / content violation.

FileTooLargeException

If the stream exceeds max_size_bytes.

replace async

replace(
    old_key: Path | str | None,
    file: UploadFile,
    *,
    subdir: str = "",
    filename: str | None = None,
    keep_original_name: bool = False,
    content_validator: Callable[[bytes], bool] | None = None,
) -> Path

Save a new object and delete the one it replaces.

Parameters:

Name Type Description Default
old_key Path | str | None

Key of the object being replaced; None/empty skips the delete (first upload).

required
file UploadFile

The new FastAPI upload.

required
subdir str

Optional sub-directory / key prefix.

''
filename str | None

Explicit final filename. Same rules as :meth:save.

None
keep_original_name bool

Preserve the upload's original filename when filename is not given.

False
content_validator Callable[[bytes], bool] | None

Optional first-chunk predicate; see :meth:save.

None

Returns:

Name Type Description
Path Path

Path(storage_key) of the newly saved object.

Raises:

Type Description
InvalidFileTypeException

If validation rejects the new file (the old object is left intact).

FileTooLargeException

If the new stream exceeds max_size_bytes (the old object is left intact).

delete async

delete(key: Path | str) -> bool

Delete a previously saved object via the shared backend.

Parameters:

Name Type Description Default
key Path | str

The storage key returned by :meth:save.

required

Returns:

Name Type Description
bool bool

True if the object existed and was deleted, False

bool

when it was already missing.

Raises:

Type Description
InvalidFileTypeException

Local backend, when key resolves outside the base directory (path traversal attempt).

exists async

exists(key: Path | str) -> bool

Return whether an object lives at key.

Parameters:

Name Type Description Default
key Path | str

The storage key.

required

Returns:

Name Type Description
bool bool

True when the object exists.

download async

download(
    key: str,
    *,
    subdir: str = "",
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool = True,
    request: Request | None = None,
    cache_control: str | None = None,
    headers: dict[str, str] | None = None,
) -> Response

Build a download response for key from the configured backend.

Parameters:

Name Type Description Default
key str

File path (local, relative to the base dir) or object key (MinIO).

required
subdir str

Optional sub-directory / key prefix.

''
filename str | None

Name presented to the client. Defaults to the basename of key.

None
media_type str | None

MIME type. Guessed/derived when omitted.

None
as_attachment bool

True forces a download; False asks for inline, granted only to a type in :data:~tempest_fastapi_sdk.utils.download.INLINE_SAFE_MEDIA_TYPES.

True
request Request | None

The incoming request. MinIO mode needs it to answer Range with 206 and validators with 304 (see :meth:AsyncMinIOClient.download_response); local mode ignores it, because FileResponse already reads Range from the ASGI scope.

None
cache_control str | None

Cache-Control value for the response. None sends none.

None
headers dict[str, str] | None

Extra response headers. One named like a download security default replaces that default.

None

Returns:

Name Type Description
Response Response

A FileResponse (local) or StreamingResponse

Response

(MinIO) ready to return from a router.

Raises:

Type Description
NotFoundException

Local mode, when the path escapes the base directory or the file is missing.

S3Error

MinIO mode, when the object is missing.

file_response

file_response(
    relative_path: Path | str,
    *,
    subdir: str = "",
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool = True,
    headers: dict[str, str] | None = None,
) -> FileResponse

Build a FileResponse streaming a file from local disk.

Parameters:

Name Type Description Default
relative_path Path | str

Path to the file, relative to the base directory (resolved safely).

required
subdir str

Optional sub-directory under the base directory.

''
filename str | None

Name presented to the client. Defaults to the file's own basename.

None
media_type str | None

MIME type. Guessed from the filename when omitted.

None
as_attachment bool

True forces a download; False asks for inline, granted only to a type in :data:~tempest_fastapi_sdk.utils.download.INLINE_SAFE_MEDIA_TYPES. Default True.

True
headers dict[str, str] | None

Extra response headers. One named like a download security default replaces that default.

None

Returns:

Name Type Description
FileResponse FileResponse

The response to return from a router.

Raises:

Type Description
NotFoundException

If the file cannot be located.

RuntimeError

When this store is MinIO-backed — use :meth:download instead.

stream

stream(
    content: bytes | Iterable[bytes] | AsyncIterable[bytes],
    *,
    filename: str,
    media_type: str | None = None,
    as_attachment: bool = True,
    headers: dict[str, str] | None = None,
) -> StreamingResponse

Build a StreamingResponse from in-memory bytes or a generator.

Use for payloads produced on the fly (a generated report, an in-memory zip) rather than read from storage.

Parameters:

Name Type Description Default
content bytes | Iterable[bytes] | AsyncIterable[bytes]

The payload. Raw bytes are wrapped in a single-chunk iterator; iterables are streamed as-is.

required
filename str

Name presented to the client.

required
media_type str | None

MIME type. Guessed from filename when omitted.

None
as_attachment bool

True forces a download; False asks for inline, granted only to a type in :data:~tempest_fastapi_sdk.utils.download.INLINE_SAFE_MEDIA_TYPES. Default True.

True
headers dict[str, str] | None

Extra response headers. One named like a download security default replaces that default.

None

Returns:

Name Type Description
StreamingResponse StreamingResponse

The response to return from a router.

resolve

resolve(relative_path: Path | str, *, subdir: str = '') -> Path

Resolve a client-supplied path safely under the local base dir.

Parameters:

Name Type Description Default
relative_path Path | str

Path relative to the base directory (absolute inputs and escaping .. segments are rejected).

required
subdir str

Optional sub-directory between the base directory and relative_path.

''

Returns:

Name Type Description
Path Path

The resolved, existing file path.

Raises:

Type Description
NotFoundException

If the path escapes the base directory, does not exist, or is not a regular file.

RuntimeError

When this store is MinIO-backed — use :meth:download instead.

presigned_get_url async

presigned_get_url(
    key: str, *, bucket: str | None = None, expires: timedelta = timedelta(hours=1)
) -> str | None

Return a presigned GET URL, or None for the local backend.

Parameters:

Name Type Description Default
key str

The object key.

required
bucket str | None

Target bucket. None uses the client's default_bucket.

None
expires timedelta

URL lifetime. Default 1 hour.

timedelta(hours=1)

Returns:

Type Description
str | None

str | None: A signed download URL, or None when the backend

str | None

cannot mint one (local disk).

presigned_put_url async

presigned_put_url(
    key: str, *, bucket: str | None = None, expires: timedelta = timedelta(minutes=15)
) -> str | None

Return a presigned PUT URL, or None for the local backend.

Lets the client upload directly to MinIO / S3 without streaming the bytes through the API.

Parameters:

Name Type Description Default
key str

The object key to upload to.

required
bucket str | None

Target bucket. None uses the client's default_bucket.

None
expires timedelta

URL lifetime. Default 15 minutes.

timedelta(minutes=15)

Returns:

Type Description
str | None

str | None: A signed upload URL, or None when the backend

str | None

cannot mint one (local disk).

MetricsUtils

Aggregated CPU/RAM/disk/GPU readings for the current host.

Built on top of :mod:psutil (always required by the [metrics] extra) and pynvml (optional — NVIDIA GPU support degrades to an empty list when the library is missing or no NVIDIA device is present).

Every method has a synchronous and an asynchronous variant. Sync methods call :mod:psutil directly (most calls are non-blocking or block briefly for sampling); async variants run the same code via :func:asyncio.to_thread so they never stall the event loop when a longer sampling interval is requested.

Stateless — instantiation is unnecessary; every method is a classmethod.

cpu classmethod

cpu(*, interval: float = 0.1) -> CPUMetrics

Sample CPU usage.

Parameters:

Name Type Description Default
interval float

Sampling window in seconds. 0 returns the cumulative measure since the previous call (which is meaningless on first invocation). Defaults to a short blocking sample.

0.1

Returns:

Name Type Description
CPUMetrics CPUMetrics

The sampled metrics.

cpu_async async classmethod

cpu_async(*, interval: float = 0.1) -> CPUMetrics

Asyncio-friendly wrapper around :meth:cpu.

Parameters:

Name Type Description Default
interval float

Sampling window in seconds.

0.1

Returns:

Name Type Description
CPUMetrics CPUMetrics

The sampled metrics.

memory classmethod

memory() -> MemoryMetrics

Sample RAM usage.

Returns:

Name Type Description
MemoryMetrics MemoryMetrics

The current memory snapshot.

memory_async async classmethod

memory_async() -> MemoryMetrics

Asyncio-friendly wrapper around :meth:memory.

Returns:

Name Type Description
MemoryMetrics MemoryMetrics

The current memory snapshot.

disk classmethod

disk(path: str = '/') -> DiskMetrics

Sample disk usage for path.

Parameters:

Name Type Description Default
path str

The filesystem path to inspect. Defaults to the root partition.

'/'

Returns:

Name Type Description
DiskMetrics DiskMetrics

The usage snapshot.

Raises:

Type Description
FileNotFoundError

When path does not exist.

disk_async async classmethod

disk_async(path: str = '/') -> DiskMetrics

Asyncio-friendly wrapper around :meth:disk.

Same error semantics as the sync method — an unreadable path raises. That is the difference from calling disks_async([path]), which logs and skips: on a metrics endpoint a skipped path answers 200 with the disk block simply absent, and a dashboard cannot tell a mount that vanished from a disk that was never asked for.

Parameters:

Name Type Description Default
path str

The filesystem path to inspect. Defaults to the root partition.

'/'

Returns:

Name Type Description
DiskMetrics DiskMetrics

The usage snapshot.

Raises:

Type Description
FileNotFoundError

When path does not exist.

PermissionError

When path cannot be read.

disks classmethod

disks(paths: list[str] | None = None, *, strict: bool = False) -> list[DiskMetrics]

Sample usage for multiple disks.

Parameters:

Name Type Description Default
paths list[str] | None

Paths to inspect. None defaults to ["/"].

None
strict bool

When True, the first unreadable path raises instead of being logged and skipped. Use it when a short list is worse than an error — a caller that asked for four mounts and got two has no way to learn which two are missing, or why.

False

Returns:

Type Description
list[DiskMetrics]

list[DiskMetrics]: One entry per resolvable path; paths that

list[DiskMetrics]

raise are logged and skipped unless strict.

Raises:

Type Description
FileNotFoundError

Under strict, when a path is absent.

PermissionError

Under strict, when a path is unreadable.

disks_async async classmethod

disks_async(
    paths: list[str] | None = None, *, strict: bool = False
) -> list[DiskMetrics]

Asyncio-friendly wrapper around :meth:disks.

Parameters:

Name Type Description Default
paths list[str] | None

Paths to inspect.

None
strict bool

Propagate the first failure instead of logging and skipping it.

False

Returns:

Type Description
list[DiskMetrics]

list[DiskMetrics]: The collected snapshots.

Raises:

Type Description
FileNotFoundError

Under strict, when a path is absent.

PermissionError

Under strict, when a path is unreadable.

gpus classmethod

gpus() -> list[GPUMetrics]

Sample NVIDIA GPU usage via pynvml when available.

Returns an empty list (without raising) when:

  • pynvml is not installed,
  • the NVML library cannot be loaded (no NVIDIA driver, WSL without compute, etc.), or
  • no NVIDIA devices are present.

Returns:

Type Description
list[GPUMetrics]

list[GPUMetrics]: One entry per detected GPU.

gpus_async async classmethod

gpus_async() -> list[GPUMetrics]

Asyncio-friendly wrapper around :meth:gpus.

Returns:

Type Description
list[GPUMetrics]

list[GPUMetrics]: One entry per detected GPU.

snapshot classmethod

snapshot(
    *, disk_paths: list[str] | None = None, cpu_interval: float = 0.1
) -> SystemMetrics

Build a full :class:SystemMetrics snapshot.

Parameters:

Name Type Description Default
disk_paths list[str] | None

Disks to inspect.

None
cpu_interval float

CPU sampling window.

0.1

Returns:

Name Type Description
SystemMetrics SystemMetrics

The combined snapshot.

snapshot_async async classmethod

snapshot_async(
    *, disk_paths: list[str] | None = None, cpu_interval: float = 0.1
) -> SystemMetrics

Asyncio-friendly wrapper around :meth:snapshot.

Runs every sub-collector concurrently via :func:asyncio.gather so the wall-clock cost is bounded by the slowest sample (typically CPU).

Parameters:

Name Type Description Default
disk_paths list[str] | None

Disks to inspect.

None
cpu_interval float

CPU sampling window.

0.1

Returns:

Name Type Description
SystemMetrics SystemMetrics

The combined snapshot.

LogUtils

LogUtils(
    name: str,
    *,
    level: str | int = "INFO",
    json_output: bool = True,
    log_dir: str | Path | None = "logs",
    stdout: bool = True,
    file_output: bool = True,
    max_bytes: int = DEFAULT_LOG_MAX_BYTES,
    backup_count: int = DEFAULT_LOG_BACKUP_COUNT,
    rotate_when: str | None = None,
    rotate_interval: int = 1,
    scope: Literal["root", "logger"] = "root",
)

High-level logging facade used across SDK consumers.

Wraps :func:tempest_fastapi_sdk.configure_logging so callers can obtain a fully configured JSON logger with one line, and exposes structured info/warning/error/debug/exception methods that forward **fields as top-level keys on the JSON payload via Python's logging.LogRecord.extra.

The class can be used in two flavors:

  • Instance API — keeps a configured logger as state and exposes level methods directly. Recommended for service-wide singletons.
  • Static helpers — :meth:configure and :meth:get_logger for ad-hoc configuration without tying state to an object.

Attributes:

Name Type Description
logger Logger

The configured stdlib logger.

name str

The logger name.

Configure and bind a logger to this instance.

Mirrors :func:configure_logging defaults — stdout and file output are enabled out of the box, writing under logs/.

scope="root" is what makes LogUtils(__name__) safe to write in every module, which is how the class reads and how it gets used. The handlers land on the root logger, once per process, and each module's logger propagates into them. Under the old per-logger behavior a service with N modules opened N stdout handlers and N * 6 file handlers on the same six paths, with that many RotatingFileHandler instances racing to roll one file over.

Parameters:

Name Type Description Default
name str

Logger name. Typically __name__ of the root module, or the service name.

required
level str | int

Minimum log level to emit. Accepts stdlib names ("INFO", "DEBUG") or integers.

'INFO'
json_output bool

When True (default), structured JSON output via :class:JSONFormatter. When False, a human-readable text formatter.

True
log_dir str | Path | None

Directory for per-level files. Defaults to "logs". Pass None to disable file logging.

'logs'
stdout bool

Attach the stdout handler. Defaults to True.

True
file_output bool

Attach the per-level + 500.log file handlers under log_dir. Defaults to True.

True
max_bytes int

Size at which each file rotates. 0 disables rotation.

DEFAULT_LOG_MAX_BYTES
backup_count int

Rotated files kept per level.

DEFAULT_LOG_BACKUP_COUNT
rotate_when str | None

Rotate by time instead of size ("midnight", "H", ...); max_bytes is then ignored. See :func:configure_logging.

None
rotate_interval int

Units of rotate_when per period.

1
scope Literal['root', 'logger']

Which logger receives the handlers. "root" (default) configures the root logger once per process and binds name to propagate into it. "logger" gives name its own handler set with propagate = False — the pre-0.280.0 behavior, for a process that deliberately isolates one logger's output.

'root'

configure staticmethod

configure(
    level: str | int = "INFO",
    *,
    json_output: bool = True,
    logger_name: str | None = None,
    log_dir: str | Path | None = "logs",
    stdout: bool = True,
    file_output: bool = True,
    max_bytes: int = DEFAULT_LOG_MAX_BYTES,
    backup_count: int = DEFAULT_LOG_BACKUP_COUNT,
    rotate_when: str | None = None,
    rotate_interval: int = 1,
) -> Logger

Imperative shortcut for :func:configure_logging.

Forwards every keyword to :func:configure_logging so the two share defaults — stdout and file output enabled, logs/ directory used unless overridden.

Parameters:

Name Type Description Default
level str | int

Minimum log level.

'INFO'
json_output bool

Emit JSON when True.

True
logger_name str | None

Target logger; None configures the root logger.

None
log_dir str | Path | None

Directory for per-level files. Defaults to "logs". Pass None to disable file logging.

'logs'
stdout bool

Attach the stdout handler. Defaults to True.

True
file_output bool

Attach the per-level + 500.log file handlers under log_dir. Defaults to True.

True
max_bytes int

Size at which each file rotates. 0 disables rotation.

DEFAULT_LOG_MAX_BYTES
backup_count int

Rotated files kept per level.

DEFAULT_LOG_BACKUP_COUNT
rotate_when str | None

Rotate by time instead of size; max_bytes is then ignored.

None
rotate_interval int

Units of rotate_when per period.

1

Returns:

Type Description
Logger

logging.Logger: The configured logger.

get_logger staticmethod

get_logger(name: str) -> Logger

Return the stdlib logger named name without reconfiguring.

Parameters:

Name Type Description Default
name str

The logger name.

required

Returns:

Type Description
Logger

logging.Logger: The (possibly unconfigured) logger.

current_request_id staticmethod

current_request_id() -> str | None

Return the current request ID from the contextvar.

Useful when callers want to surface the correlation ID outside the log line (e.g. in an HTTP response body).

Returns:

Type Description
str | None

str | None: The active request ID, or None.

info

info(
    message: str,
    *args: Any,
    stacklevel: int = 2,
    exc_info: bool | Literal["auto"] = False,
    **fields: Any,
) -> None

Emit an INFO record.

Parameters:

Name Type Description Default
message str

The log message, or a %-style template when args are given.

required
*args Any

Positional arguments for %-style interpolation, forwarded to logging untouched — the interpolation stays lazy, and the template stays the same string across calls, which is what a log aggregator groups on.

()
stacklevel int

How many frames to walk back when resolving funcName/lineno. The default of 2 points the record at your call site instead of at this facade.

2
exc_info bool | Literal['auto']

Whether to attach the current traceback. "auto" attaches it only when an exception is being handled, which is what lets one helper serve a call site that is sometimes inside an except and sometimes not — True outside an except writes NoneType: None.

False
**fields Any

Extra structured fields merged into the JSON payload. A key that shadows a LogRecord attribute raises TypeError here rather than KeyError at emission time.

{}

Raises:

Type Description
TypeError

When a field name is reserved by LogRecord.

debug

debug(
    message: str,
    *args: Any,
    stacklevel: int = 2,
    exc_info: bool | Literal["auto"] = False,
    **fields: Any,
) -> None

Emit a DEBUG record.

Parameters:

Name Type Description Default
message str

The log message, or a %-style template when args are given.

required
*args Any

Positional arguments for %-style interpolation, forwarded to logging untouched — the interpolation stays lazy, and the template stays the same string across calls, which is what a log aggregator groups on.

()
stacklevel int

How many frames to walk back when resolving funcName/lineno. The default of 2 points the record at your call site instead of at this facade.

2
exc_info bool | Literal['auto']

Whether to attach the current traceback. "auto" attaches it only when an exception is being handled, which is what lets one helper serve a call site that is sometimes inside an except and sometimes not — True outside an except writes NoneType: None.

False
**fields Any

Extra structured fields merged into the JSON payload. A key that shadows a LogRecord attribute raises TypeError here rather than KeyError at emission time.

{}

Raises:

Type Description
TypeError

When a field name is reserved by LogRecord.

warning

warning(
    message: str,
    *args: Any,
    stacklevel: int = 2,
    exc_info: bool | Literal["auto"] = False,
    **fields: Any,
) -> None

Emit a WARNING record.

Parameters:

Name Type Description Default
message str

The log message, or a %-style template when args are given.

required
*args Any

Positional arguments for %-style interpolation, forwarded to logging untouched — the interpolation stays lazy, and the template stays the same string across calls, which is what a log aggregator groups on.

()
stacklevel int

How many frames to walk back when resolving funcName/lineno. The default of 2 points the record at your call site instead of at this facade.

2
exc_info bool | Literal['auto']

Whether to attach the current traceback. "auto" attaches it only when an exception is being handled, which is what lets one helper serve a call site that is sometimes inside an except and sometimes not — True outside an except writes NoneType: None.

False
**fields Any

Extra structured fields merged into the JSON payload. A key that shadows a LogRecord attribute raises TypeError here rather than KeyError at emission time.

{}

Raises:

Type Description
TypeError

When a field name is reserved by LogRecord.

error

error(
    message: str,
    *args: Any,
    stacklevel: int = 2,
    exc_info: bool | Literal["auto"] = False,
    **fields: Any,
) -> None

Emit an ERROR record.

Parameters:

Name Type Description Default
message str

The log message, or a %-style template when args are given.

required
*args Any

Positional arguments for %-style interpolation, forwarded to logging untouched — the interpolation stays lazy, and the template stays the same string across calls, which is what a log aggregator groups on.

()
stacklevel int

How many frames to walk back when resolving funcName/lineno. The default of 2 points the record at your call site instead of at this facade.

2
exc_info bool | Literal['auto']

Whether to attach the current traceback. "auto" attaches it only when an exception is being handled, which is what lets one helper serve a call site that is sometimes inside an except and sometimes not — True outside an except writes NoneType: None.

False
**fields Any

Extra structured fields merged into the JSON payload. A key that shadows a LogRecord attribute raises TypeError here rather than KeyError at emission time.

{}

Raises:

Type Description
TypeError

When a field name is reserved by LogRecord.

error_500

error_500(message: str, *args: Any, stacklevel: int = 2, **fields: Any) -> None

Emit an ERROR record routed to the dedicated 500.log.

configure_logging writes a 500.log and filters it on the :data:~tempest_fastapi_sdk.core.logging.HTTP_500_MARKER extra, but the only things that set that marker are this SDK's own exception handlers — so a service reporting a grave failure of its own had to import a private-looking constant from core.logging to reach a file the SDK already writes for it.

The record also lands in error.log like any other ERROR. The isolated file exists so grave failures are not buried among the rest, not to remove them from the level stream.

The traceback is attached whenever one is being handled, since a 500 that reports no traceback is the case the file exists for.

Parameters:

Name Type Description Default
message str

The log message, or a %-style template when args are given.

required
*args Any

Positional arguments for %-style interpolation, forwarded to logging untouched.

()
stacklevel int

How many frames to walk back when resolving funcName/lineno. The default of 2 points the record at your call site instead of at this facade.

2
**fields Any

Extra structured fields. A http_500 key here is overridden by the marker.

{}

Raises:

Type Description
TypeError

When a field name is reserved by LogRecord.

critical

critical(
    message: str,
    *args: Any,
    stacklevel: int = 2,
    exc_info: bool | Literal["auto"] = False,
    **fields: Any,
) -> None

Emit a CRITICAL record.

Parameters:

Name Type Description Default
message str

The log message, or a %-style template when args are given.

required
*args Any

Positional arguments for %-style interpolation, forwarded to logging untouched — the interpolation stays lazy, and the template stays the same string across calls, which is what a log aggregator groups on.

()
stacklevel int

How many frames to walk back when resolving funcName/lineno. The default of 2 points the record at your call site instead of at this facade.

2
exc_info bool | Literal['auto']

Whether to attach the current traceback. "auto" attaches it only when an exception is being handled, which is what lets one helper serve a call site that is sometimes inside an except and sometimes not — True outside an except writes NoneType: None.

False
**fields Any

Extra structured fields merged into the JSON payload. A key that shadows a LogRecord attribute raises TypeError here rather than KeyError at emission time.

{}

Raises:

Type Description
TypeError

When a field name is reserved by LogRecord.

exception

exception(message: str, *args: Any, stacklevel: int = 2, **fields: Any) -> None

Emit an ERROR record with the current exception traceback.

Must be called from inside an except block — the traceback is attached unconditionally, and True outside an except writes NoneType: None. Use error(..., exc_info="auto") for a call site that is sometimes inside one.

Parameters:

Name Type Description Default
message str

The log message, or a %-style template when args are given.

required
*args Any

Positional arguments for %-style interpolation, forwarded to logging untouched — the interpolation stays lazy, and the template stays the same string across calls, which is what a log aggregator groups on.

()
stacklevel int

How many frames to walk back when resolving funcName/lineno. The default of 2 points the record at your call site instead of at this facade.

2
**fields Any

Extra structured fields merged into the JSON payload. A key that shadows a LogRecord attribute raises TypeError here rather than KeyError at emission time.

{}

Raises:

Type Description
TypeError

When a field name is reserved by LogRecord.

AttemptThrottle

AttemptThrottle(
    backend: ThrottleBackend,
    *,
    max_attempts: int,
    window_seconds: int,
    namespace: str = "throttle",
    fail_open: bool = True,
)

Fixed-window failure counter over an injected async KV backend.

Initialize the throttle.

Parameters:

Name Type Description Default
backend ThrottleBackend

Async KV store (e.g. redis.asyncio.Redis).

required
max_attempts int

Failures allowed before a key is blocked. Must be >= 1.

required
window_seconds int

Sliding window length (also the TTL applied on the first failure). Must be > 0.

required
namespace str

Key prefix so multiple throttles can share a backend without colliding.

'throttle'
fail_open bool

When True (default), backend errors degrade to "allowed" instead of raising — a cache outage must not lock every user out.

True

Raises:

Type Description
ValueError

If max_attempts < 1 or window_seconds <= 0.

status async

status(key: str) -> ThrottleStatus

Read the current status for key without mutating it.

Parameters:

Name Type Description Default
key str

The domain key (e.g. f"{event_id}:{ip}").

required

Returns:

Name Type Description
ThrottleStatus ThrottleStatus

Current attempts / blocked state. On a backend error with fail_open set, an empty, unblocked status.

hit async

hit(key: str) -> ThrottleStatus

Record one failure for key and return the new status.

Increments the counter and, on the first failure of a window, applies the TTL so the window expires on its own.

Parameters:

Name Type Description Default
key str

The domain key.

required

Returns:

Name Type Description
ThrottleStatus ThrottleStatus

Status after the increment. On a backend error with fail_open set, an empty, unblocked status.

reset async

reset(key: str) -> None

Clear the counter for key (e.g. after a success).

Parameters:

Name Type Description Default
key str

The domain key.

required

reserve async

reserve(
    key: str,
    *,
    message: str | None = None,
    exception: type[TooManyRequestsException] = TooManyRequestsException,
) -> ThrottleStatus

Take one attempt from key's budget before verifying it.

The increment is the check: the backend's atomic INCR hands each concurrent caller a distinct count, so at most max_attempts callers per window get past this line however many arrive at once. Use it instead of :meth:raise_if_blocked followed by a later :meth:hit, which only bounds sequential attempts.

The reserved slot stays spent when the attempt fails. When it turns out not to be a failure (a successful login), either clear the key with :meth:reset or give back just this slot with :meth:release. A refused reservation is counted too, so a key that keeps trying while blocked stays blocked until the window ends.

Parameters:

Name Type Description Default
key str

The domain key.

required
message str | None

Optional override for the 429 message.

None
exception type[TooManyRequestsException]

The class to raise.

TooManyRequestsException

Returns:

Name Type Description
ThrottleStatus ThrottleStatus

The status after the reservation, when it fits

ThrottleStatus

the budget. On a backend error with fail_open set, an empty,

ThrottleStatus

unblocked status.

Raises:

Type Description
TooManyRequestsException

When the reservation exceeds max_attempts; carries Retry-After.

release async

release(key: str) -> None

Give back one slot taken by :meth:reserve.

Decrements the counter when the backend offers decr (Redis and :class:InMemoryThrottleBackend do). A counter that reaches zero, or a key that expired in between, is deleted rather than left behind without a TTL. A backend without decr keeps the slot spent, which errs towards throttling.

Parameters:

Name Type Description Default
key str

The domain key.

required

raise_if_blocked async

raise_if_blocked(
    key: str,
    *,
    message: str | None = None,
    exception: type[TooManyRequestsException] = TooManyRequestsException,
) -> ThrottleStatus

Raise :class:TooManyRequestsException when key is blocked.

Parameters:

Name Type Description Default
key str

The domain key.

required
message str | None

Optional override for the 429 message.

None
exception type[TooManyRequestsException]

The class to raise — a subclass carrying its own code (LOGIN_THROTTLED) keeps the status and the Retry-After and lets the client tell this refusal from any other 429.

TooManyRequestsException

This only reads the counter. Paired with a :meth:hit after a slow verification it does not bound concurrent attempts; use :meth:reserve for that.

Returns:

Name Type Description
ThrottleStatus ThrottleStatus

The (unblocked) status when within budget.

Raises:

Type Description
TooManyRequestsException

When the attempt budget for key is exhausted; carries Retry-After.

InMemoryThrottleBackend

InMemoryThrottleBackend(*, clock: Callable[[], float] = monotonic)

Process-local :class:ThrottleBackend — no Redis, no network.

Holds one (count, expires_at) pair per key in a dict and serves the five async verbs :class:AttemptThrottle calls, with the same return contract Redis has: ttl answers -2 for an absent key and -1 for one carrying no TTL.

The counter lives in the process that served the request.

Two workers each keep their own dict, so the budget an account can reach is max_attempts * workers: the bound holds per worker, not per account. Anything served by more than one process (uvicorn --workers, gunicorn, more than one pod) needs a shared backend; pass the Redis client to :class:AttemptThrottle there. Correct for a single-process deployment, a dev server, and tests.

Every incr first drops the entries whose TTL already passed, so the dict stays bounded by the keys touched inside one window and a key nobody touches again does not live as long as the process.

Example

backend = InMemoryThrottleBackend() throttle = AttemptThrottle(backend, max_attempts=5, window_seconds=900) await throttle.hit("mfa:user-id") ThrottleStatus(attempts=1, blocked=False, retry_after_seconds=0)

Initialize an empty backend.

Parameters:

Name Type Description Default
clock Callable[[], float]

Zero-argument callable returning the current time in seconds. Defaults to :func:time.monotonic.

monotonic

incr async

incr(name: str) -> int

Atomically increment name and return the new count.

The first increment of a window creates the key with no TTL, exactly like Redis INCR — the caller is the one that follows up with :meth:expire.

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email).

required

Returns:

Name Type Description
int int

The attempt count after the increment.

decr async

decr(name: str) -> int

Decrement name and return the new count, like Redis DECR.

An absent or expired key starts from zero, so the result is -1 with no TTL, exactly as Redis answers; :meth:AttemptThrottle.release deletes such a key.

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email).

required

Returns:

Name Type Description
int int

The attempt count after the decrement.

expire async

expire(name: str, seconds: int) -> None

Set a TTL (seconds) on name.

A key that is absent or already expired is left absent, which is what EXPIRE does.

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email).

required
seconds int

Window length in seconds.

required

ttl async

ttl(name: str) -> int

Return remaining TTL in seconds (-1/-2 when unset).

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email).

required

Returns:

Name Type Description
int int

-2 when the key is absent, -1 when it carries no

int

TTL, and otherwise the seconds left, rounded up — a key

int

that is still alive never answers 0, which the throttle

int

reads as "no TTL" and would replace with the full window.

get async

get(name: str) -> str | bytes | None

Return the counter at name as text.

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email).

required

Returns:

Type Description
str | bytes | None

str | bytes | None: The attempt count as a decimal string, or

str | bytes | None

None when the key is absent or expired. The throttle only

str | bytes | None

ever parses it as an int.

delete async

delete(name: str) -> None

Delete name, whether or not it was there.

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email).

required

sign_path

sign_path(
    path: str,
    *,
    secret: str,
    expires_in: timedelta,
    purpose: str,
    now: datetime | None = None,
) -> str

Return path signed for purpose and valid for expires_in.

Call it where the caller has already been authorized — typically in the mapper that turns a stored key into the response schema — so only an allowed caller ever holds the URL.

Parameters:

Name Type Description Default
path str

The route path, decoded, exactly as the route will see it in request.scope["path"] (for example "/api/files/report 2026.pdf"). Must start with /.

required
secret str

The application secret. Domain separation makes reusing JWT_SECRET safe.

required
expires_in timedelta

How long the URL stays valid. Must be positive.

required
purpose str

Label binding the signature to one use ("files", "email-link"); a URL signed for one purpose never verifies for another.

required
now datetime | None

The signing instant. None uses the current UTC time; tests pass a fixed value. A naive datetime is read as UTC.

None

Returns:

Name Type Description
str str

The percent-encoded path followed by

str

?expires=<unix seconds>&signature=<mac>.

Raises:

Type Description
ValueError

If path does not start with /, expires_in is not positive, or secret/purpose is empty.

verify_path

verify_path(
    path: str,
    *,
    expires: int,
    signature: str,
    secret: str,
    purpose: str,
    now: datetime | None = None,
) -> None

Check that signature authorizes path until expires.

The signature is checked first and the expiry second, so a forged expires is reported as invalid, not as expired. A URL stops being valid at the expires second itself.

Parameters:

Name Type Description Default
path str

The decoded request path — request.scope["path"].

required
expires int

The expires query parameter, unix seconds.

required
signature str

The signature query parameter.

required
secret str

The secret the URL was signed with.

required
purpose str

The purpose the URL was signed for.

required
now datetime | None

The verification instant. None uses the current UTC time; tests pass a fixed value. A naive datetime is read as UTC.

None

Raises:

Type Description
InvalidSignedURLException

403 when the signature does not match the path, expires, purpose and secret.

ExpiredSignedURLException

403 when the signature is authentic but expires is not in the future.

ValueError

If secret or purpose is empty.

VAPID_SUBJECT_PATTERN module-attribute

VAPID_SUBJECT_PATTERN: Final[str] = (
    "^(mailto:.+@((localhost|[%\\w-]+(\\.[%\\w-]+)+|([0-9a-f]{1,4}):+([0-9a-f]{1,4})?)))|https:\\/\\/(localhost|[\\w-]+\\.[\\w\\.-]+|([0-9a-f]{1,4}:+)+([0-9a-f]{1,4})?)$"
)

The pattern a VAPID sub must match, matched case-insensitively.

Ported from py_vapid 1.9.4's _check_sub, character for character, so what passes here is exactly what the signature accepts. Its quirk is ported too: the trailing $ anchors only the https:// branch, so a mailto: address may be followed by anything. tests/utils/test_vapid.py compares this string with the installed py_vapid source, so an upstream change fails a test instead of drifting.

check_vapid_subject

check_vapid_subject(subject: str, *, name: str = 'VAPID_SUBJECT') -> None

Refuse a sub claim py_vapid would not sign with.

Parameters:

Name Type Description Default
subject str

The candidate sub claim.

required
name str

What the value is called in the message (the setting or the argument).

'VAPID_SUBJECT'

Raises:

Type Description
ValueError

When subject is not mailto:<email> nor https://<host>, naming what it is instead (got a bare e-mail; prefix it with 'mailto:').

is_valid_vapid_subject

is_valid_vapid_subject(subject: str) -> bool

Return whether py_vapid would sign with this sub claim.

Parameters:

Name Type Description Default
subject str

The candidate sub claim.

required

Returns:

Name Type Description
bool bool

True for a mailto:<email> or https://<host> value.

SIGNED_URL_EXPIRES_PARAM module-attribute

SIGNED_URL_EXPIRES_PARAM: str = 'expires'

Query parameter carrying the expiry, in unix seconds.

SIGNED_URL_SIGNATURE_PARAM module-attribute

SIGNED_URL_SIGNATURE_PARAM: str = 'signature'

Query parameter carrying the URL-safe base64 HMAC-SHA256.

UFEnum

Bases: StrEnum

The 27 Brazilian federative units, keyed by their acronym.

RegionEnum

Bases: StrEnum

The five official IBGE macro-regions of Brazil.

StateBR

Bases: BaseModel

A Brazilian federative unit and its municipalities.

Attributes:

Name Type Description
uf UFEnum

The federative unit acronym (e.g. UFEnum.SP).

name str

The full state name (e.g. "São Paulo").

region RegionEnum

The IBGE macro-region the state belongs to.

cities list[str]

The municipality names, alphabetically sorted, in canonical proper case.

CityBR

Bases: BaseModel

A single Brazilian municipality.

Attributes:

Name Type Description
name str

The municipality name in canonical proper case (e.g. "Rio Branco").

uf UFEnum

The federative unit the municipality belongs to.

list_states

list_states() -> list[StateBR]

Return every Brazilian state ordered by acronym.

Returns:

Type Description
list[StateBR]

list[StateBR]: All 27 federative units with their cities.

get_state

get_state(uf: str | UFEnum) -> StateBR

Return the :class:StateBR for a given federative unit.

Parameters:

Name Type Description Default
uf str | UFEnum

The acronym (case-insensitive) or :class:UFEnum.

required

Returns:

Name Type Description
StateBR StateBR

The matching state, including its municipalities.

Raises:

Type Description
ValueError

If uf is not a known federative unit.

cities_by_uf

cities_by_uf(uf: str | UFEnum) -> list[str]

Return the alphabetically sorted municipalities of a state.

Parameters:

Name Type Description Default
uf str | UFEnum

The acronym (case-insensitive) or :class:UFEnum.

required

Returns:

Type Description
list[str]

list[str]: The municipality names in canonical proper case.

Raises:

Type Description
ValueError

If uf is not a known federative unit.

states_by_region

states_by_region(region: RegionEnum) -> list[StateBR]

Return every state belonging to a given macro-region.

Parameters:

Name Type Description Default
region RegionEnum

The IBGE macro-region to filter by.

required

Returns:

Type Description
list[StateBR]

list[StateBR]: The states in that region, ordered by acronym.

is_valid_uf

is_valid_uf(value: str) -> bool

Check whether value is a valid federative unit acronym.

The match is case-insensitive and ignores surrounding whitespace, so "sp" and " SP " are both accepted.

Parameters:

Name Type Description Default
value str

The acronym to inspect.

required

Returns:

Name Type Description
bool bool

True when value maps to a known :class:UFEnum.

normalize_uf

normalize_uf(value: str) -> UFEnum

Validate value and return the matching :class:UFEnum.

Parameters:

Name Type Description Default
value str

The acronym (any case, optional whitespace).

required

Returns:

Name Type Description
UFEnum UFEnum

The federative unit enum member.

Raises:

Type Description
ValueError

If value is not a known federative unit.

is_valid_city

is_valid_city(uf: str | UFEnum, city: str) -> bool

Check whether city exists in the given federative unit.

Matching ignores accents, letter case and surrounding whitespace, so "sao paulo" matches "São Paulo".

Parameters:

Name Type Description Default
uf str | UFEnum

The acronym (case-insensitive) or :class:UFEnum.

required
city str

The municipality name to look up.

required

Returns:

Name Type Description
bool bool

True when the city belongs to the state. Returns

bool

False for an unknown uf instead of raising.

normalize_city

normalize_city(uf: str | UFEnum, city: str) -> str

Validate city against uf and return its canonical name.

Parameters:

Name Type Description Default
uf str | UFEnum

The acronym (case-insensitive) or :class:UFEnum.

required
city str

The municipality name (any case/accents).

required

Returns:

Name Type Description
str str

The canonical proper-case municipality name.

Raises:

Type Description
ValueError

If uf is unknown or city is not part of it.

uf_choices

uf_choices() -> list[ChoiceBR]

Return every federative unit as a frontend <select> choice.

Each choice carries the acronym as value (what you store/submit, and what :data:UFField validates) and the full state name as label. Ordered by acronym.

Returns:

Type Description
list[ChoiceBR]

list[ChoiceBR]: One choice per state, e.g.

list[ChoiceBR]

ChoiceBR(value="SP", label="São Paulo").

region_choices

region_choices() -> list[ChoiceBR]

Return every IBGE macro-region as a frontend <select> choice.

Both value and label carry the region name (e.g. "Sudeste") since that is the stored :class:RegionEnum value.

Returns:

Type Description
list[ChoiceBR]

list[ChoiceBR]: One choice per macro-region, ordered as declared.

city_choices

city_choices(uf: str | UFEnum) -> list[ChoiceBR]

Return the cities of a federative unit as <select> choices.

Each choice uses the canonical city name for both value and label. Ordered alphabetically.

Parameters:

Name Type Description Default
uf str | UFEnum

The acronym (case-insensitive) or :class:UFEnum.

required

Returns:

Type Description
list[ChoiceBR]

list[ChoiceBR]: One choice per municipality.

Raises:

Type Description
ValueError

If uf is not a known federative unit (matching :func:cities_by_uf).

parse_currency_br

parse_currency_br(text: str) -> Decimal | None

Read an amount printed in Brazilian notation into an exact Decimal.

Accepts both separator conventions, because a source that transcribes a Brazilian document sometimes normalizes to the US one:

  • "R$ 2.930,00" / "2.930,00" — comma decimal, dot thousands
  • "2930.00" / "2,930.00" — dot decimal, the US convention
  • "2930" — no separator at all

The last separator present decides which one is decimal. The one genuinely ambiguous case is a lone dot followed by exactly three digits: "2.930" is read as two thousand nine hundred and thirty, never as two point nine three, because that is what the notation means in the documents this parses. Pass the US form with its own thousands separator ("2,930.00") when the other reading is intended.

Parameters:

Name Type Description Default
text str

The printed amount, with or without symbol and spaces.

required

Returns:

Type Description
Decimal | None

Decimal | None: The parsed amount, or None when the text carries

Decimal | None

no digit at all. None rather than zero keeps "the document did

Decimal | None

not print a price" distinguishable from "the document printed

Decimal | None

R$ 0,00" — a distinction that decides whether a line is missing data

Decimal | None

or is genuinely free of charge.

format_currency_br

format_currency_br(amount: Decimal, *, symbol: bool = True) -> str

Render an amount in Brazilian currency notation.

Parameters:

Name Type Description Default
amount Decimal

The amount to render; quantized to two places before formatting.

required
symbol bool

Whether to prefix the R$ symbol.

True

Returns:

Name Type Description
str str

The formatted amount, e.g. "R$ 484.365,84". A negative

str

amount carries the sign ahead of the symbol ("-R$ 0,01"), which

str

is how a credit reads on a Brazilian statement and how a closing

str

difference must appear on a worksheet.

format_percent_br

format_percent_br(ratio: Decimal, *, places: int = 2) -> str

Render a ratio as a Brazilian-formatted percentage.

Parameters:

Name Type Description Default
ratio Decimal

The ratio to render, where Decimal("0.30") means thirty percent.

required
places int

How many decimal places to keep.

2

Returns:

Name Type Description
str str

The formatted percentage, e.g. "30,00%".

format_quantity_br

format_quantity_br(amount: Decimal, *, places: int = 2) -> str

Render a non-monetary quantity in Brazilian notation.

Parameters:

Name Type Description Default
amount Decimal

The quantity to render.

required
places int

How many decimal places to keep.

2

Returns:

Name Type Description
str str

The formatted quantity, e.g. "1.250,00".

quantize_money

quantize_money(amount: Decimal) -> Decimal

Round a monetary amount to two decimal places, half away from zero.

Uses ROUND_HALF_UP rather than :class:~decimal.Decimal's default ROUND_HALF_EVEN. Banker's rounding is the better choice for a long series of independent roundings, but it is not what a Brazilian accountant, a printed invoice, or a spreadsheet built by hand does — and a generated document that disagrees with the manual one by a cent is a document that gets rejected.

Parameters:

Name Type Description Default
amount Decimal

The unrounded amount.

required

Returns:

Name Type Description
Decimal Decimal

The amount quantized to two decimal places.

CENT module-attribute

CENT: Decimal = Decimal('0.01')

The smallest representable monetary unit; the quantization target.

HUNDRED module-attribute

HUNDRED: Decimal = Decimal('100')

Literal one hundred, used to convert ratios to display percentages.

get_client_ip

get_client_ip(request: Request, *, trusted_header: str | None = None) -> str

Resolve the client IP from a Starlette/FastAPI request.

Parameters:

Name Type Description Default
request Request

The inbound request.

required
trusted_header str | None

Name of the single edge-set header to trust (case-insensitive, e.g. "x-real-ip"). None uses the direct transport peer only.

None

Returns:

Name Type Description
str str

The resolved client IP, or "unknown" when neither the trusted header nor the transport peer is available. A header value that is not one IP address is ignored (see :func:parse_client_ip).

get_client_ip_from_scope

get_client_ip_from_scope(scope: Scope, *, trusted_header: str | None = None) -> str

Resolve the client IP from a raw ASGI scope.

Mirrors :func:get_client_ip for middleware that sees the ASGI scope directly instead of a Starlette :class:Request.

Parameters:

Name Type Description Default
scope Scope

The ASGI scope.

required
trusted_header str | None

Name of the single edge-set header to trust (case-insensitive). None uses the transport peer only.

None

Returns:

Name Type Description
str str

The resolved client IP, or "unknown" when unavailable. A header value that is not one IP address is ignored.

parse_client_ip

parse_client_ip(value: str) -> str | None

Return value as a canonical IP address, or None.

An IPv4-mapped IPv6 address is rendered with the IPv4 part dotted (::ffff:1.2.3.4) on every Python version. str() of the address does that only from Python 3.13 on; 3.12 renders the same address as ::ffff:102:304, so two replicas on different Pythons keyed one client under two rate-limit buckets.

Parameters:

Name Type Description Default
value str

A header value claimed to be one client address.

required

Returns:

Type Description
str | None

str | None: The canonical form (ipaddress.ip_address rendered

str | None

back to text) after stripping whitespace, or None when the

str | None

value is not exactly one IPv4 or IPv6 address.

to_utc

to_utc(value: datetime) -> datetime

Convert a datetime to UTC.

Naive datetimes are assumed to be in UTC and tagged with the UTC tzinfo. Aware datetimes are converted to UTC.

Parameters:

Name Type Description Default
value datetime

The datetime to normalize.

required

Returns:

Name Type Description
datetime datetime

A timezone-aware datetime in UTC.

utcnow

utcnow() -> datetime

Return the current time as a timezone-aware UTC datetime.

Returns:

Name Type Description
datetime datetime

The current UTC time.

modify_dict

modify_dict(
    data: dict[str, Any],
    exclude: list[str] | None = None,
    include: dict[str, Any] | None = None,
) -> dict[str, Any]

Filter and extend a dictionary in a single pass.

Removes any keys listed in exclude and merges the include mapping on top of the remaining items.

Parameters:

Name Type Description Default
data dict[str, Any]

The source dictionary.

required
exclude list[str] | None

Keys to drop from the output.

None
include dict[str, Any] | None

Extra entries to merge into the output (these win over keys already in data).

None

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A new dictionary with the requested mutations.

build_content_disposition

build_content_disposition(
    filename: str, *, as_attachment: bool = True, media_type: str | None = None
) -> str

Build an RFC 6266 Content-Disposition header value.

Emits both an ASCII filename (with quotes/backslashes stripped as a legacy fallback) and a UTF-8 filename* parameter (RFC 5987) so non-ASCII names survive across clients.

The name is treated as untrusted, because in the documented usage it is UploadFile.filename — a value the client chose. Taking the basename stops a path from being injected, but on its own left the control characters in: a name containing \r\n produced a header value with a real line break, which an ASGI server that does not validate header values (uvicorn on httptools) writes to the socket verbatim, letting the caller append headers of their own to your response. Every character below 0x20 plus DEL is dropped here, so what comes out is always a single header line.

as_attachment=False is a request, not a decision: it yields inline only when media_type is in :data:INLINE_SAFE_MEDIA_TYPES. Any other type — text/html, image/svg+xml, application/octet-stream — and None yield attachment.

Parameters:

Name Type Description Default
filename str

The name the client should see for the download. Reduced to its basename, with control characters removed, so neither a path nor a header break can be injected.

required
as_attachment bool

True forces a download (attachment); False asks for inline, granted only to an inline-safe media_type. Default True.

True
media_type str | None

The type the response carries. Parameters are ignored in the check. None (unknown) is not inline-safe. Default None.

None

Returns:

Name Type Description
str str

A ready-to-use header value, e.g.

str

attachment; filename="a.pdf"; filename*=UTF-8''a.pdf.

BulkEmailReport dataclass

BulkEmailReport(
    delivered: int, permanent: list[FailedRecipient], transient: list[FailedRecipient]
)

What a bulk send actually did.

Split by what the caller should do next, which is the whole point: 5xx means the mailbox does not exist and the address should be pruned, 4xx means full or greylisted and the message should be requeued. Collapsing them into one "failed" list forces the caller to re-parse SMTP codes it already had.

Attributes:

Name Type Description
delivered int

Messages the server accepted.

permanent list[FailedRecipient]

5xx refusals — prune these.

transient list[FailedRecipient]

4xx refusals — retry these.

failed property

failed: int

Return how many recipients did not receive the message.

Returns:

Name Type Description
int int

len(permanent) + len(transient).

FailedRecipient dataclass

FailedRecipient(email: str, code: int | None, message: str)

One address a bulk send could not deliver to.

Attributes:

Name Type Description
email str

The address that failed.

code int | None

SMTP reply code, when the server gave one.

message str

The server's reply text, verbatim.

CentsField module-attribute

CentsField = Annotated[int, Ge(0)]

Monetary amount in minor units (cents): a non-negative integer.

Storing money as integer cents avoids binary float rounding. Use this for prices/balances and divide by 100 only at the presentation edge.

DecimalPercentField module-attribute

DecimalPercentField = Annotated[Decimal, Field(ge=0, le=100)]

Exact percentage in the inclusive range 0..100.

The :class:~decimal.Decimal counterpart of :data:PercentField, for the same reason as :data:DecimalRatioField. Divide by :data:~tempest_fastapi_sdk.utils.currency.HUNDRED to reach the ratio.

DecimalRatioField module-attribute

DecimalRatioField = Annotated[Decimal, Field(ge=0, le=1)]

Exact fraction in the inclusive range 0..1.

The :class:~decimal.Decimal counterpart of :data:RatioField. Use it — never the float one — wherever the fraction multiplies money. Decimal("0.28") is exactly twenty-eight percent; 0.28 is not, and the difference surfaces the moment it meets a :data:PriceField: Python raises TypeError on Decimal * float, and the "fix" of casting one side is what moves the cent a bid is judged on.

HexColorField module-attribute

HexColorField = Annotated[
    str, StringConstraints(pattern="^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
]

CSS hex color, 3 or 6 hex digits with a leading # (#fff / #abc123).

LatitudeField module-attribute

LatitudeField = Annotated[float, Ge(-90), Le(90)]

Geographic latitude in degrees, -90..90.

LocaleField module-attribute

LocaleField = Annotated[LocaleEnum, BeforeValidator(normalize_locale_tag)]

Pydantic type that accepts a loose locale string and yields a :class:LocaleEnum.

The :class:~pydantic.BeforeValidator runs ahead of the enum coercion, so case and separator variants ("pt_BR", "PT-BR") and the bare primary subtag ("pt" -> PT_BR) are accepted; an unsupported tag raises a clear invalid locale error (HTTP 422). Use it on a request schema the way :data:UFField is used for state — the stored/response value can stay a plain str.

LongitudeField module-attribute

LongitudeField = Annotated[float, Ge(-180), Le(180)]

Geographic longitude in degrees, -180..180.

NonEmptyStrField module-attribute

NonEmptyStrField = Annotated[
    str, StringConstraints(strip_whitespace=True, min_length=1)
]

String trimmed of surrounding whitespace, rejected when empty.

Whitespace-only input fails because it is stripped to "" before the min_length=1 check.

NonNegativeFloatField module-attribute

NonNegativeFloatField = Annotated[float, Ge(0)]

Float greater than or equal to zero.

NonNegativeIntField module-attribute

NonNegativeIntField = Annotated[int, Ge(0)]

Integer greater than or equal to zero.

PercentField module-attribute

PercentField = Annotated[float, Ge(0), Le(100)]

Percentage in the inclusive range 0..100.

PortField module-attribute

PortField = Annotated[int, Ge(1), Le(65535)]

TCP/UDP port number in the valid range 1..65535.

PositiveFloatField module-attribute

PositiveFloatField = Annotated[float, Gt(0)]

Float strictly greater than zero.

PositiveIntField module-attribute

PositiveIntField = Annotated[int, Gt(0)]

Integer strictly greater than zero (quantities, counts, 1-based ids).

PriceField module-attribute

PriceField = Annotated[Decimal, Field(ge=0, decimal_places=2)]

Non-negative monetary amount as a :class:~decimal.Decimal, 2 places.

Prefer :data:CentsField (integer cents) for storage; use PriceField when an exact decimal with two fractional digits is the contract (e.g. a payment gateway payload).

RatingField module-attribute

RatingField = Annotated[int, Ge(0), Le(5)]

Star rating as an integer in the inclusive range 0..5.

The canonical 0-to-5-star review score: 0 means "no stars", 5 the maximum. Use it for a rating column/field so the 0..5 bound lives in the type instead of a hand-written validator.

RatioField module-attribute

RatioField = Annotated[float, Ge(0), Le(1)]

Fraction/probability in the inclusive range 0..1.

SignedDecimalRatioField module-attribute

SignedDecimalRatioField = Annotated[Decimal, Field(le=1)]

Exact fraction, capped at 1, that may go below zero.

For a derived share that can legitimately come out negative: a balancing line the premises left no slack for, or a closing difference a document must disclose rather than clamp to zero. Bounding it above but not below is deliberate — over 100% is a bug, under 0% is news.

SlugField module-attribute

SlugField = Annotated[str, StringConstraints(pattern='^[a-z0-9]+(?:-[a-z0-9]+)*$')]

URL-safe slug: lowercase alphanumerics in kebab-case (my-post-1).

REQUEST_ID_HEADER module-attribute

REQUEST_ID_HEADER: str = 'X-Request-ID'

Default outbound header carrying the inbound correlation id.

Override per client with HTTPClient(request_id_header=...).

ChoiceBR

Bases: BaseModel

A value/label pair ready for a frontend <select>.

The shape every dropdown wants: a stable value to store/submit and a human label to show. Returned by :func:uf_choices, :func:region_choices and :func:city_choices.

Attributes:

Name Type Description
value str

The value to store/submit (e.g. the UF acronym "SP" or a city name).

label str

The human-facing text to display (e.g. the full state name "São Paulo").

CityNameField module-attribute

CityNameField = Annotated[str, AfterValidator(lambda v: v.strip())]

Pydantic type for a trimmed city name (no cross-field UF validation).

UFField module-attribute

UFField = Annotated[UFEnum, BeforeValidator(normalize_uf)]

Pydantic type that accepts any-case acronym and yields a :class:UFEnum.

The :class:~pydantic.BeforeValidator runs ahead of the enum coercion, so lower-case and whitespace-padded acronyms ("sp", " RJ ") are accepted and an invalid value raises a clear invalid UFEnum error.

CPUMetrics dataclass

CPUMetrics(
    percent: float,
    cores_logical: int,
    cores_physical: int,
    load_average: tuple[float, float, float] | None = None,
)

CPU usage snapshot.

Attributes:

Name Type Description
percent float

Aggregate CPU utilization (0-100).

cores_logical int

Logical core count (including SMT).

cores_physical int

Physical core count.

load_average tuple[float, float, float] | None

⅕/15-minute load averages on POSIX; None on Windows.

to_dict

to_dict() -> dict[str, Any]

Return the metrics as a plain dict.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The dataclass fields.

DiskMetrics dataclass

DiskMetrics(
    path: str, total_bytes: int, used_bytes: int, free_bytes: int, percent: float
)

Disk usage snapshot for a single mount point.

Attributes:

Name Type Description
path str

The mount point inspected.

total_bytes int

Filesystem total capacity.

used_bytes int

Used bytes.

free_bytes int

Free bytes.

percent float

Used percentage (0-100).

to_dict

to_dict() -> dict[str, Any]

Return the metrics as a plain dict.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The dataclass fields.

GPUMetrics dataclass

GPUMetrics(
    index: int,
    name: str,
    memory_total_bytes: int,
    memory_used_bytes: int,
    memory_free_bytes: int,
    utilization_percent: float,
    temperature_celsius: float | None = None,
)

Single-GPU usage snapshot.

Populated by :func:pynvml (NVIDIA only). Non-NVIDIA hosts get an empty list from :meth:MetricsUtils.gpus.

Attributes:

Name Type Description
index int

Device index (0-based).

name str

Device model name.

memory_total_bytes int

VRAM capacity.

memory_used_bytes int

VRAM in use.

memory_free_bytes int

VRAM free.

utilization_percent float

GPU utilization (0-100).

temperature_celsius float | None

Core temperature, when reported by the driver.

to_dict

to_dict() -> dict[str, Any]

Return the metrics as a plain dict.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The dataclass fields.

MemoryMetrics dataclass

MemoryMetrics(total_bytes: int, used_bytes: int, available_bytes: int, percent: float)

RAM usage snapshot.

Attributes:

Name Type Description
total_bytes int

Total physical memory.

used_bytes int

Memory actively in use.

available_bytes int

Memory available for new allocations.

percent float

Used percentage (0-100).

to_dict

to_dict() -> dict[str, Any]

Return the metrics as a plain dict.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The dataclass fields.

SystemMetrics dataclass

SystemMetrics(
    cpu: CPUMetrics,
    memory: MemoryMetrics,
    disks: list[DiskMetrics] = list(),
    gpus: list[GPUMetrics] = list(),
)

Full machine snapshot returned by :meth:MetricsUtils.snapshot.

Attributes:

Name Type Description
cpu CPUMetrics

CPU usage block.

memory MemoryMetrics

RAM usage block.

disks list[DiskMetrics]

One entry per inspected path.

gpus list[GPUMetrics]

One entry per detected NVIDIA GPU.

to_dict

to_dict() -> dict[str, Any]

Return the snapshot as a nested dict ready for JSON.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: cpu/memory/disks/gpus keys.

generate_opaque_token

generate_opaque_token(nbytes: int = _DEFAULT_NBYTES) -> tuple[str, str]

Generate a cryptographically random token and its digest.

Parameters:

Name Type Description Default
nbytes int

Entropy in bytes for the URL-safe token. Defaults to 32 (~43 characters), well above brute-force reach.

_DEFAULT_NBYTES

Returns:

Type Description
tuple[str, str]

tuple[str, str]: (plaintext, token_hash). Show plaintext to the user once; persist only token_hash.

hash_opaque_token

hash_opaque_token(plaintext: str) -> str

Return the SHA-256 hex digest of a token's plaintext.

Parameters:

Name Type Description Default
plaintext str

The token value to hash.

required

Returns:

Name Type Description
str str

64-character lowercase hex digest.

verify_opaque_token

verify_opaque_token(plaintext: str, token_hash: str) -> bool

Constant-time check that plaintext hashes to token_hash.

Parameters:

Name Type Description Default
plaintext str

The token submitted by the caller.

required
token_hash str

The stored SHA-256 hex digest.

required

Returns:

Name Type Description
bool bool

True when the hashes match, False otherwise.

CEP_PATTERN module-attribute

CEP_PATTERN: Final[Pattern[str]] = re.compile('^\\d{5}-?\\d{3}$')

Match a Brazilian CEP in either masked (00000-000) or raw form.

CEPField module-attribute

CEPField = Annotated[str, AfterValidator(normalize_cep)]

Pydantic field type that validates a Brazilian CEP, normalized to 8 digits.

CNPJ_PATTERN module-attribute

CNPJ_PATTERN: Final[Pattern[str]] = re.compile(
    "^\\d{2}\\.?\\d{3}\\.?\\d{3}/?\\d{4}-?\\d{2}$"
)

Match a CNPJ in either masked (00.000.000/0000-00) or raw form.

CNPJField module-attribute

CNPJField = Annotated[str, AfterValidator(normalize_cnpj)]

Pydantic field type that validates and normalizes a CNPJ to 14 digits.

CPF_CNPJ_PATTERN module-attribute

CPF_CNPJ_PATTERN: Final[Pattern[str]] = re.compile(
    f"(?:{CPF_PATTERN.pattern[1:-1]})|(?:{CNPJ_PATTERN.pattern[1:-1]})"
)

Match either a CPF or a CNPJ (masked or raw).

CPF_PATTERN module-attribute

CPF_PATTERN: Final[Pattern[str]] = re.compile('^\\d{3}\\.?\\d{3}\\.?\\d{3}-?\\d{2}$')

Match a CPF in either masked (000.000.000-00) or raw form.

CPFField module-attribute

CPFField = Annotated[str, AfterValidator(normalize_cpf)]

Pydantic field type that validates and normalizes a CPF to 11 digits.

CPFOrCNPJField module-attribute

CPFOrCNPJField = Annotated[str, AfterValidator(normalize_cpf_cnpj)]

Pydantic field type that accepts either a CPF or a CNPJ.

detect_pix_key_type

detect_pix_key_type(value: str) -> PixKeyType | None

Return the :class:PixKeyType a PIX key belongs to, or None.

Detection is by shape: @ → e-mail, leading + → phone, UUID shape → random, otherwise digits-only length + check digits decide between CPF and CNPJ.

Parameters:

Name Type Description Default
value str

The raw PIX key (masked CPF/CNPJ accepted).

required

Returns:

Type Description
PixKeyType | None

PixKeyType | None: The detected type, or None when value

PixKeyType | None

is not a valid key of any type, including any value longer than

PixKeyType | None

77 characters once trimmed.

is_valid_cep

is_valid_cep(value: str) -> bool

Check whether value looks like a Brazilian CEP.

CEPs have no check digits — validation only enforces the eight-digit shape (with or without the canonical 00000-000 mask). Use the official Correios API for existence checks.

Parameters:

Name Type Description Default
value str

The CEP string to inspect.

required

Returns:

Name Type Description
bool bool

True when the value matches the CEP pattern.

is_valid_cnpj

is_valid_cnpj(value: str) -> bool

Check whether value is a syntactically valid CNPJ.

Accepts both masked (00.000.000/0000-00) and unmasked input. Sequences with all repeated digits are rejected.

Parameters:

Name Type Description Default
value str

The CNPJ string to inspect.

required

Returns:

Name Type Description
bool bool

True when the value matches the CNPJ pattern and

bool

has correct check digits.

is_valid_cpf

is_valid_cpf(value: str) -> bool

Check whether value is a syntactically valid CPF.

Accepts both masked (000.000.000-00) and unmasked input. Sequences with all repeated digits (e.g. "11111111111") are rejected even though they pass the modulo math.

Parameters:

Name Type Description Default
value str

The CPF string to inspect.

required

Returns:

Name Type Description
bool bool

True when the value matches the CPF pattern and

bool

has correct check digits.

is_valid_cpf_cnpj

is_valid_cpf_cnpj(value: str) -> bool

Check whether value is a valid CPF or CNPJ.

Parameters:

Name Type Description Default
value str

The document string to inspect.

required

Returns:

Name Type Description
bool bool

True when the value passes :func:is_valid_cpf

or bool

func:is_valid_cnpj.

is_valid_mobile_phone_br

is_valid_mobile_phone_br(value: str) -> bool

Check whether value is a Brazilian mobile number.

Use this instead of :func:is_valid_phone_br whenever the number is a delivery address -- WhatsApp, SMS, an OTP. A landline passes :func:is_valid_phone_br and then fails silently at delivery time, with no error for the user and no obvious log for the operator.

Parameters:

Name Type Description Default
value str

The phone string to inspect.

required

Returns:

Name Type Description
bool bool

True when the value is a mobile line (area code plus a

bool

9-digit subscriber number starting with 9).

is_valid_phone_br

is_valid_phone_br(value: str) -> bool

Check whether value looks like a Brazilian phone number.

Accepts optional +55 country code, optional DDD parentheses and an optional 9th digit for mobile numbers. After stripping non-digits the remaining length must be 10 (landline) or 11 (mobile), with an optional leading 55 country code.

Parameters:

Name Type Description Default
value str

The phone string to inspect.

required

Returns:

Name Type Description
bool bool

True when the value matches a BR phone shape.

is_valid_pix_key

is_valid_pix_key(value: str) -> bool

Return True when value is a valid PIX key of any type.

Parameters:

Name Type Description Default
value str

The PIX key to check.

required

Returns:

Name Type Description
bool bool

Whether the value is a recognizable, valid PIX key.

MobilePhoneBRField module-attribute

MobilePhoneBRField = Annotated[str, AfterValidator(normalize_mobile_phone_br)]

Pydantic field type that accepts only a BR mobile number.

Rejects landlines, which :data:PhoneBRField accepts, and normalizes to the 11 digits of the national form (DDD + subscriber number) so the same line always lands in the column as the same string.

normalize_cep

normalize_cep(value: str) -> str

Return value as 8 digits, validating along the way.

Parameters:

Name Type Description Default
value str

The CEP string (masked or unmasked).

required

Returns:

Name Type Description
str str

The CEP stripped down to 8 digits.

Raises:

Type Description
ValueError

If value is not a valid CEP.

normalize_cnpj

normalize_cnpj(value: str) -> str

Return value as 14 digits, validating along the way.

Parameters:

Name Type Description Default
value str

The CNPJ string (masked or unmasked).

required

Returns:

Name Type Description
str str

The CNPJ stripped down to 14 digits.

Raises:

Type Description
ValueError

If value is not a valid CNPJ.

normalize_cpf

normalize_cpf(value: str) -> str

Return value as 11 digits, validating along the way.

Parameters:

Name Type Description Default
value str

The CPF string (masked or unmasked).

required

Returns:

Name Type Description
str str

The CPF stripped down to 11 digits.

Raises:

Type Description
ValueError

If value is not a valid CPF.

normalize_cpf_cnpj

normalize_cpf_cnpj(value: str) -> str

Return value as 11 or 14 digits, validating along the way.

Parameters:

Name Type Description Default
value str

The document string (masked or unmasked).

required

Returns:

Name Type Description
str str

The document stripped down to digits only.

Raises:

Type Description
ValueError

If value is not a valid CPF nor CNPJ.

normalize_mobile_phone_br

normalize_mobile_phone_br(value: str) -> str

Return a BR mobile number as the 11 digits of its national form.

Unlike :func:normalize_phone_br, which keeps whatever the caller typed and therefore returns 10, 11, 12 or 13 digits, this one always returns DDD + 9-digit subscriber number: the +55 country code is dropped, so two spellings of the same line normalize to the same string and compare equal in a database column. Use :attr:PhoneNumberBR.e164 when the +55 form is what you need.

Parameters:

Name Type Description Default
value str

The phone string (masked or unmasked).

required

Returns:

Name Type Description
str str

The mobile number as 11 digits.

Raises:

Type Description
ValueError

If value is not a valid BR mobile number.

normalize_phone_br

normalize_phone_br(value: str) -> str

Return value as digits-only with an optional 55 prefix.

Parameters:

Name Type Description Default
value str

The phone string (masked or unmasked).

required

Returns:

Name Type Description
str str

The phone stripped down to digits only.

Raises:

Type Description
ValueError

If value does not look like a BR phone.

normalize_pix_key

normalize_pix_key(value: str) -> str

Validate a PIX key and return it in canonical form.

Canonicalization per type: CPF/CNPJ → digits only; e-mail → trimmed + lowercased; phone → the E.164 +55… string; random → lowercased UUID.

Parameters:

Name Type Description Default
value str

The raw PIX key.

required

Returns:

Name Type Description
str str

The normalized key.

Raises:

Type Description
ValueError

When value is not a valid PIX key.

only_digits

only_digits(value: str) -> str

Strip every non-digit character from value.

Parameters:

Name Type Description Default
value str

The raw input (masked CPF, phone, etc.).

required

Returns:

Name Type Description
str str

A string containing only the digits found in value.

parse_phone_br

parse_phone_br(value: str) -> PhoneNumberBR | None

Split a BR phone number into area code, subscriber number and kind.

Stricter than :func:is_valid_phone_br, which checks shape and length only: this one also applies the ANATEL prefix rules, so an 8-digit subscriber number that does not start with 2-5 returns None even though :func:is_valid_phone_br accepts it.

A 9-digit subscriber number needs no prefix check here: the optional 9 in :data:PHONE_BR_PATTERN is the only way an 11-digit number matches at all, so the leading 9 is already guaranteed by the time this function runs. test_pattern_already_forces_the_ninth_digit pins that coupling.

Parameters:

Name Type Description Default
value str

The phone string, masked or unmasked, with or without the +55 country code.

required

Returns:

Type Description
PhoneNumberBR | None

PhoneNumberBR | None: The parsed number, or None when

PhoneNumberBR | None

value is not a number Brazil assigns.

PHONE_BR_PATTERN module-attribute

PHONE_BR_PATTERN: Final[Pattern[str]] = re.compile(
    "^(?:\\+?55\\s?)?(?:\\(?\\d{2}\\)?\\s?)?9?\\d{4}[-\\s]?\\d{4}$"
)

Match a BR phone number with optional +55, DDD, mask or 9th digit.

PhoneBRField module-attribute

PhoneBRField = Annotated[str, AfterValidator(normalize_phone_br)]

Pydantic field type that validates a BR phone and normalizes to digits.

PhoneNumberBR

Bases: BaseModel

A Brazilian phone number split into its parts.

Returned by :func:parse_phone_br. The country code never shows up in :attr:area_code or :attr:number, only in :attr:e164, so the national parts compare equal whether or not the caller typed +55.

Attributes:

Name Type Description
area_code str

The two-digit area code (DDD), e.g. "89".

number str

The subscriber number without the area code: 9 digits for a mobile line, 8 for a landline.

is_mobile bool

Whether the line is a mobile one -- the question a WhatsApp/SMS delivery path actually asks.

e164 str

The number in E.164 form, e.g. "+5589912345678".

PixKeyField module-attribute

PixKeyField = Annotated[str, AfterValidator(normalize_pix_key)]

Pydantic field type that validates any PIX key and normalizes it.

Accepts a CPF, CNPJ, e-mail, E.164 phone (+55…) or random UUID key; raises ValidationError (HTTP 422) on anything else. Use :func:detect_pix_key_type when you also need to know which type.

PixKeyType

Bases: BaseStrEnum

The five kinds of PIX key defined by BACEN.

  • CPF — an 11-digit CPF (individual taxpayer id).
  • CNPJ — a 14-digit CNPJ (company taxpayer id).
  • EMAIL — an e-mail address.
  • PHONE — an E.164 phone (+55 + DDD + number).
  • RANDOM — a random key (EVP), i.e. a UUID.

Bases: Protocol

An upload backend that can give a permanent link to a stored file.

The link is not a presigned URL: it does not expire and only opens for someone the store itself authorizes (the Google Drive webViewLink opens for a Drive user with access to the file). The admin download route redirects to it when :meth:UploadStorage.presigned_url has nothing to offer.

web_view_link(key: str) -> str | None

Return the permanent link of the file under key.

Parameters:

Name Type Description Default
key str

Storage key.

required

Returns:

Type Description
str | None

str | None: The link, or None when no file matches.

UploadResult dataclass

UploadResult(key: str, size: int, path: Path | None = None, url: str | None = None)

Outcome of an :meth:UploadStorage.write_stream call.

The key is the canonical identifier for the persisted object — a path string for the local backend, an S3 key for MinIO. path is set only when the backend wrote to a real filesystem location; url only when the backend can mint a download URL (presigned or static).

Attributes:

Name Type Description
key str

Identifier used to read the object back.

size int

Bytes written.

path Path | None

On-disk path when applicable.

url str | None

Public or presigned download URL when applicable.

UploadStorage

Bases: Protocol

Protocol every upload backend implements.

Implementations must be safe to call concurrently — FastAPI routes share the same instance.

write_stream async

write_stream(
    key: str,
    chunks: AsyncIterator[bytes],
    *,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
    max_size_bytes: int | None = None,
    validator: ContentValidator | None = None,
) -> UploadResult

Persist a chunked async stream under key.

Parameters:

Name Type Description Default
key str

Storage key. Backends interpret this as a relative path (local) or object key (S3).

required
chunks AsyncIterator[bytes]

Source stream.

required
content_type str

MIME type of the payload.

'application/octet-stream'
metadata dict[str, str] | None

User metadata.

None
max_size_bytes int | None

When set, the backend aborts the write and removes any partial object once the limit is exceeded.

None
validator ContentValidator | None

Optional callable invoked with the first chunk. Returning False aborts the write before further bytes are persisted.

None

Returns:

Name Type Description
UploadResult UploadResult

Identifier + size + optional path/url.

Raises:

Type Description
FileTooLargeException

When max_size_bytes is exceeded mid-write.

InvalidFileTypeException

When validator rejects the first chunk.

delete async

delete(key: str) -> bool

Delete the object under key.

Parameters:

Name Type Description Default
key str

Storage key.

required

Returns:

Name Type Description
bool bool

True when an object was removed, False

bool

when it was already gone.

exists async

exists(key: str) -> bool

Return whether an object lives at key.

Parameters:

Name Type Description Default
key str

Storage key.

required

Returns:

Name Type Description
bool bool

True when the object exists.

presigned_url async

presigned_url(key: str, *, expires: timedelta = timedelta(hours=1)) -> str | None

Return a temporary download URL, or say the backend has none.

A backend says it cannot mint one in either of two ways: it returns None (local disk), or it raises :class:~tempest_fastapi_sdk.exceptions.PresignedUrlUnsupportedException (Google Drive, which has no temporary link and refuses to pass a permanent one off as such). A caller that works with any backend handles both forms the same way.

Parameters:

Name Type Description Default
key str

Storage key.

required
expires timedelta

URL lifetime.

timedelta(hours=1)

Returns:

Type Description
str | None

str | None: Download URL. None when the backend

str | None

cannot mint one (e.g. local disk).

Raises:

Type Description
PresignedUrlUnsupportedException

From a backend that signals "no presigned URLs" by raising instead of returning None.

login_throttle_key

login_throttle_key(identifier: str) -> str

Return the per-identifier login throttle key for identifier.

"login:<sha256 of the stripped, lowercased identifier>" — hashed so the throttle backend (often a shared Redis) never stores the address, and normalized so Root@Example.com and root@example.com spend one budget. Shared by POST /auth/login and POST /admin/login, which is what keeps the two from drifting into two key shapes.

Parameters:

Name Type Description Default
identifier str

The submitted login identifier (an e-mail).

required

Returns:

Name Type Description
str str

The throttle key.

ThrottleBackend

Bases: Protocol

Minimal async key-value contract a throttle backend must satisfy.

Matches the relevant subset of redis.asyncio.Redis.

incr

incr(name: str) -> Awaitable[int]

Atomically increment name and return the new value.

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email). Positional-only: redis-py is free to call it whatever it likes.

required

Returns:

Type Description
Awaitable[int]

Awaitable[int]: Resolves to the current attempt count.

expire

expire(name: str, seconds: int) -> Awaitable[object]

Set a TTL (seconds) on name.

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email).

required
seconds int

Window length in seconds. Positional-only because redis.asyncio.Redis.expire calls this parameter time.

required

Returns:

Type Description
Awaitable[object]

Awaitable[object]: Resolves once the backend call completes. The result is discarded, so any return type is accepted — redis-py resolves bool.

ttl

ttl(name: str) -> Awaitable[int]

Return remaining TTL in seconds (-1/-2 when unset).

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email).

required

Returns:

Type Description
Awaitable[int]

Awaitable[int]: Resolves to the remaining TTL in seconds.

get

get(name: str) -> Awaitable[str | bytes | None]

Return the value at name (None when absent).

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email).

required

Returns:

Type Description
Awaitable[str | bytes | None]

Awaitable[str | bytes | None]: Resolves to the stored counter as text, or None when the key is absent. Both halves matter: a client with decode_responses=True resolves str, one without resolves bytes.

delete

delete(name: str) -> Awaitable[object]

Delete name.

Parameters:

Name Type Description Default
name str

Identifier being throttled (an IP, a user, an email). Positional-only because redis.asyncio.Redis.delete takes *names, which no keyword call can reach.

required

Returns:

Type Description
Awaitable[object]

Awaitable[object]: Resolves once the backend call completes. The result is discarded, so any return type is accepted — redis-py resolves int.

ThrottleStatus dataclass

ThrottleStatus(attempts: int, blocked: bool, retry_after_seconds: int)

Outcome of a throttle query.

Attributes:

Name Type Description
attempts int

Failures recorded in the current window.

blocked bool

Whether the attempt budget is exhausted.

retry_after_seconds int

Seconds until the window resets. 0 when not blocked.

ACCESS_TOKEN_TYPE module-attribute

ACCESS_TOKEN_TYPE: str = 'access'

typ of a token that authorizes API calls.

AMR_CLAIM module-attribute

AMR_CLAIM: str = 'amr'

Claim listing how the session was authenticated (RFC 8176, amr).

AMR_EMAIL_LINK: str = 'email'

amr value for a session opened by a single-use emailed link — account activation or password reset. Not in the RFC 8176 registry, like :data:AMR_EXTERNAL: the request proved control of the mailbox, not knowledge of the password, and RFC 8176 has no value for that. Kept out of :data:MFA_AMR_METHODS, so make_mfa_required_dependency refuses it, and deliberately not otp: a link is one factor, and calling it a one-time password would let it pass the second-factor gate.

AMR_EXTERNAL module-attribute

AMR_EXTERNAL: str = 'ext'

amr value for a session that an OAuth provider authenticated. Not in the RFC 8176 registry: the SDK cannot see which methods the provider used, so it records only that the proof happened elsewhere.

AMR_HARDWARE_KEY module-attribute

AMR_HARDWARE_KEY: str = 'hwk'

amr value for a WebAuthn assertion (RFC 8176: proof of possession of a hardware-secured key).

AMR_OTP module-attribute

AMR_OTP: str = 'otp'

amr value for a one-time code — a TOTP code or a single-use recovery code, both of which RFC 8176 files under "one-time password".

AMR_PASSWORD module-attribute

AMR_PASSWORD: str = 'pwd'

amr value for a password check (RFC 8176).

MFA_AMR module-attribute

MFA_AMR: tuple[str, ...] = (AMR_PASSWORD, AMR_OTP)

amr of a session that passed the password and the second factor.

MFA_AMR_METHODS module-attribute

MFA_AMR_METHODS: frozenset[str] = frozenset({AMR_OTP})

The amr values that prove a second factor by default.

MFA_TOKEN_TYPE module-attribute

MFA_TOKEN_TYPE: str = 'mfa'

typ of the token bridging step one and step two of an MFA login.

PASSWORD_AMR module-attribute

PASSWORD_AMR: tuple[str, ...] = (AMR_PASSWORD,)

amr of a session opened with the password alone.

REFRESH_TOKEN_TYPE module-attribute

REFRESH_TOKEN_TYPE: str = 'refresh'

typ of a token that only buys a new access/refresh pair.

STREAM_TOKEN_TYPE module-attribute

STREAM_TOKEN_TYPE: str = 'stream'

typ of a short-lived SSE ticket: it opens one event stream and authorizes nothing else, so the URL it travels in can leak without leaking a session. Minted by the POST <prefix>/ticket route of :func:~tempest_fastapi_sdk.make_sse_router.