Ir para o conteúdo

tempest_fastapi_sdk.storage

Object storage (MinIO, S3 ou disco local), upload resumível (tus) e os clientes de storage.

« Documentos e arquivos


AsyncMinIOClient

AsyncMinIOClient(
    endpoint: str,
    access_key: str,
    secret_key: str,
    *,
    default_bucket: str = "uploads",
    secure: bool = False,
    region: str = "us-east-1",
    session_token: str | None = None,
    public_endpoint: str | None = None,
    public_secure: bool | None = None,
    accel_redirect: bool = False,
    accel_prefix: str = "/_bucket/",
    enabled: bool = True,
)

Async-friendly facade over minio.Minio.

Use as an async context manager when you want explicit cleanup, or hold a long-lived instance on the FastAPI app — the underlying Minio client is thread-safe and reuses its connection pool.

Example:

>>> from tempest_fastapi_sdk import AsyncMinIOClient
>>> storage = AsyncMinIOClient(
...     endpoint="localhost:9000",
...     access_key="minioadmin",
...     secret_key="minioadmin",
...     default_bucket="uploads",
... )
>>> await storage.ensure_bucket()
>>> await storage.put_object("hello.txt", b"world")
>>> body = await storage.get_object_bytes("hello.txt")
>>> assert body == b"world"

Initialize the client.

Parameters:

Name Type Description Default
endpoint str

host[:port] without scheme. Used for every server-side operation.

required
access_key str

S3 access key.

required
secret_key str

S3 secret key.

required
default_bucket str

Bucket used by object operations when no explicit bucket keyword is passed. Created by :meth:ensure_bucket.

'uploads'
secure bool

Use HTTPS when True.

False
region str

S3 region. Match the bucket region for AWS S3; any value works for MinIO.

'us-east-1'
session_token str | None

Optional STS session token for temporary credentials.

None
public_endpoint str | None

Split-endpoint mode. When set, presigned URLs (:meth:presigned_get_url / :meth:presigned_put_url) are signed against this host instead of endpoint — for deployments where the backend reaches MinIO over a private network but the browser must hit a public, TLS-terminated host. A scheme:// prefix and any trailing path are stripped, and https:// implies public_secure=True. None signs presigned URLs with endpoint (unchanged).

None
public_secure bool | None

HTTPS for public_endpoint. None falls back to secure (unless a https:// scheme on public_endpoint forces it).

None
accel_redirect bool

Delivery mode of :meth:serve_object. True answers with an X-Accel-Redirect for nginx to fetch the object (:meth:accel_redirect_response); False (default) streams the bytes through the app (:meth:download_response).

False
accel_prefix str

Internal nginx location the X-Accel-Redirect points into, and the default internal_prefix of :meth:accel_redirect_response. Must start with /. Default "/_bucket/".

'/_bucket/'
enabled bool

False builds a client for an integration switched off by STORAGE_ENABLED=false: no minio client is created (nor imported), and every operation — anything that reaches :attr:client — raises :class:~tempest_fastapi_sdk.exceptions.IntegrationDisabledException (503, details={"integration": "storage"}). StorageSettings.storage_kwargs passes it. Default True.

True

Raises:

Type Description
ValueError

When accel_prefix does not start with /.

ImportError

When the minio package is not installed and enabled is True. Install the [minio] extra: pip install tempest-fastapi-sdk[minio].

Notes

In split-endpoint mode a second client is built with the same credentials, whose only job is signing presigned URLs against the public host. SigV4 signs the Host header, so the URL has to be signed with the public endpoint — rewriting the host afterwards would invalidate the signature.

client property

client: Minio

Return the underlying minio.Minio used for server-side calls.

Every operation of this class goes through it (or through :attr:_presign_client), which is what makes a disabled client refuse all of them at one point.

Returns:

Name Type Description
Minio Minio

The configured minio client.

Raises:

Type Description
IntegrationDisabledException

When the client was built with enabled=False.

bucket_exists async

bucket_exists(bucket: str | None = None) -> bool

Check whether bucket exists.

Parameters:

Name Type Description Default
bucket str | None

Target bucket; defaults to default_bucket.

None

Returns:

Name Type Description
bool bool

True when the bucket exists and is reachable

bool

with the configured credentials.

ensure_bucket async

ensure_bucket(bucket: str | None = None) -> bool

Create the bucket if it does not exist yet.

Parameters:

Name Type Description Default
bucket str | None

Target bucket; defaults to default_bucket.

None

Returns:

Name Type Description
bool bool

True when a bucket was created, False

bool

when it already existed.

list_buckets async

list_buckets() -> list[str]

Return every bucket reachable with the current credentials.

Returns:

Type Description
list[str]

list[str]: Bucket names. Empty list when none exist.

remove_bucket async

remove_bucket(bucket: str | None = None) -> None

Delete an empty bucket.

Parameters:

Name Type Description Default
bucket str | None

Target bucket; defaults to default_bucket.

None

Raises:

Type Description
S3Error

When the bucket is missing or non-empty.

put_object async

put_object(
    key: str,
    data: bytes | BinaryIO,
    *,
    bucket: str | None = None,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
    length: int | None = None,
    part_size: int = 10 * 1024 * 1024,
) -> str

Upload an object.

Accepts both raw bytes and any binary file-like object (open("file", "rb"), BytesIO, UploadFile.file). For unknown-length streams pass length=-1 to enable multipart upload via part_size chunks.

Parameters:

Name Type Description Default
key str

Destination object key.

required
data bytes | BinaryIO

Payload. bytes is wrapped in a BytesIO; file-like objects are forwarded as-is.

required
bucket str | None

Override target bucket.

None
content_type str

MIME type. "application/octet-stream" by default.

'application/octet-stream'
metadata dict[str, str] | None

User metadata. Keys are stored under the x-amz-meta- namespace by minio automatically — pass plain names.

None
length int | None

Payload size in bytes. Required for unknown-length streams; computed automatically when data is bytes.

None
part_size int

Chunk size for multipart upload (when length is -1 or larger than 5 GiB). Must be at least 5 MiB. Default 10 MiB.

10 * 1024 * 1024

Returns:

Name Type Description
str str

ETag of the uploaded object (quotes stripped).

Raises:

Type Description
S3Error

When the upload fails (auth, network, bucket missing, content rejected).

fput_object async

fput_object(
    key: str,
    file_path: str | Path,
    *,
    bucket: str | None = None,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
) -> str

Upload a file from disk.

Parameters:

Name Type Description Default
key str

Destination object key.

required
file_path str | Path

Source path on disk.

required
bucket str | None

Override target bucket.

None
content_type str

MIME type.

'application/octet-stream'
metadata dict[str, str] | None

User metadata.

None

Returns:

Name Type Description
str str

ETag of the uploaded object (quotes stripped).

Raises:

Type Description
FileNotFoundError

When file_path does not exist.

S3Error

When the upload fails.

get_object_bytes async

get_object_bytes(key: str, *, bucket: str | None = None) -> bytes

Download an object as bytes.

Suitable for small objects. For large payloads prefer :meth:stream_object to avoid loading everything in memory.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override source bucket.

None

Returns:

Name Type Description
bytes bytes

Object payload.

Raises:

Type Description
S3Error

When the object is missing or the request fails.

fget_object async

fget_object(key: str, file_path: str | Path, *, bucket: str | None = None) -> Path

Download an object straight to disk.

Parameters:

Name Type Description Default
key str

Object key.

required
file_path str | Path

Destination path. Parent directories are created if missing.

required
bucket str | None

Override source bucket.

None

Returns:

Name Type Description
Path Path

The path the object was written to.

Raises:

Type Description
S3Error

When the object is missing or the request fails.

stream_object async

stream_object(
    key: str,
    *,
    bucket: str | None = None,
    chunk_size: int = 64 * 1024,
    offset: int = 0,
    length: int | None = None,
) -> AsyncIterator[bytes]

Stream an object (or one byte range of it) in fixed-size chunks.

The whole network read still runs in a worker thread — each chunk_size read is one asyncio.to_thread round-trip — but the event loop yields between chunks so other requests progress.

offset and length are forwarded to Minio.get_object, which turns them into a Range header on the request to the store, so only that slice crosses the network — what a 206 response needs. A whole-object read (the defaults) still calls get_object(bucket, key) without them, so a test double written against the older two-argument call keeps working.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override source bucket.

None
chunk_size int

Bytes per chunk. Default 64 KiB.

64 * 1024
offset int

First byte to read. Default 0.

0
length int | None

How many bytes to read from offset. None (default) reads to the end of the object.

None

Returns:

Type Description
AsyncIterator[bytes]

AsyncIterator[bytes]: Async generator yielding chunks

AsyncIterator[bytes]

until the stream ends.

Raises:

Type Description
ValueError

When offset is negative, or length or chunk_size is not positive.

S3Error

When the object is missing or the request fails.

download_response async

download_response(
    key: str,
    *,
    request: Request | None = None,
    bucket: str | None = None,
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool = True,
    chunk_size: int = 64 * 1024,
    cache_control: str | None = None,
    headers: dict[str, str] | None = None,
) -> StreamingResponse

Stream an object straight to the client as a download response.

Reads the object's metadata (for the content type, length and validators) and streams its bytes through the app — the file never lands on the app's disk nor loads fully into memory. Reach for this when the download must be auth-gated or the MinIO endpoint is not publicly reachable; prefer :meth:presigned_get_url to offload the transfer to MinIO directly when the client can hit it.

Every response carries Accept-Ranges: bytes plus the object's ETag (quoted) and Last-Modified, and the download security headers of :data:~tempest_fastapi_sdk.api.static.DEFAULT_STATIC_SECURITY_HEADERS, since the bytes reach the client on the API's origin with the type stored at upload. Pass request to let the client use the validators:

  • If-None-Match matching the ETag — or, when no If-None-Match is sent, If-Modified-Since not older than the object — answers 304 with no body, without reading the object.
  • Range: bytes=a-b, bytes=a- or bytes=-n answers 206 with Content-Range, reading only that slice from the store (offset/length on get_object). This is what lets a <video> seek and a download manager resume.
  • A range starting at or past the end answers 416 with Content-Range: bytes */<size>.
  • Several ranges (bytes=0-1,5-6), an unparseable Range, or an If-Range that no longer matches the object serve the whole object with 200 — RFC 9110 allows ignoring Range, and it avoids a multipart/byteranges body.

Without request no request header is read and the response is always 200 with the whole object.

Parameters:

Name Type Description Default
key str

Object key.

required
request Request | None

The incoming request, whose Range, If-Range, If-None-Match and If-Modified-Since headers are honoured. None always serves the whole object.

None
bucket str | None

Override source bucket.

None
filename str | None

Name presented to the client. Defaults to the object key's basename.

None
media_type str | None

Content type. Defaults to the object's stored content type, then a guess from filename, then application/octet-stream.

None
as_attachment bool

True forces a download; False asks for inline (e.g. view a PDF in-browser), granted only when the resolved type is in :data:~tempest_fastapi_sdk.utils.download.INLINE_SAFE_MEDIA_TYPES. Default True.

True
chunk_size int

Bytes per streamed chunk. Default 64 KiB.

64 * 1024
cache_control str | None

Cache-Control value, for example "private, max-age=3600". None sends none.

None
headers dict[str, str] | None

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

None

Returns:

Name Type Description
StreamingResponse StreamingResponse

Response ready to return from a router —

StreamingResponse

200, 206, 304 or 416; the last two carry an empty

StreamingResponse

body.

Raises:

Type Description
S3Error

When the object is missing or the request fails.

accel_redirect_response async

accel_redirect_response(
    key: str,
    *,
    bucket: str | None = None,
    internal_prefix: str | None = None,
    expires: timedelta = timedelta(minutes=5),
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool = True,
    cache_control: str | None = None,
    headers: dict[str, str] | None = None,
) -> Response

Hand the transfer to nginx with an X-Accel-Redirect header.

The route keeps the authorisation decision and nginx moves the bytes: the response is empty and carries X-Accel-Redirect: <internal_prefix><bucket>/<key>?X-Amz-..., a URL presigned against the internal endpoint — never public_endpoint — so the bucket stays private and the client only ever sees the backend's domain. nginx follows the header into an internal location that proxies to the bucket; the client's Range and If-None-Match travel with that request, so 206 and 304 come from the store itself.

SigV4 signs the Host header and the path, so the internal location must strip the prefix (proxy_pass with a trailing /) and send Host equal to endpoint; otherwise the store answers 403 SignatureDoesNotMatch. The storage recipe carries the full nginx block.

Content-Disposition, Content-Type and Cache-Control are not set on this response but signed into the URL as the S3 response-* overrides, so the store returns them with the bytes. Measured on nginx 1.27.5: the upstream's Content-Type wins over the one the app sets, and a Content-Disposition set on both reaches the client twice.

The download security headers (:data:~tempest_fastapi_sdk.api.static.DEFAULT_STATIC_SECURITY_HEADERS) are not set here: S3 has no response-* override for them, and nginx answers with the store's response — measured on nginx 1.22.1, 1.27.5 and 1.29.8, a Content-Security-Policy the app sets on the empty response does not reach the client. They belong in the internal location, as add_header ... always; the storage recipe's nginx block carries them.

No stat is made: a missing object surfaces as the store's 404 through nginx instead of an S3Error here.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override source bucket.

None
internal_prefix str | None

The nginx internal location the header points into, starting with /. None uses accel_prefix from the constructor ("/_bucket/" by default).

None
expires timedelta

Lifetime of the presigned URL. nginx uses it at once, so it only has to outlive the hop. Default five minutes.

timedelta(minutes=5)
filename str | None

Name presented to the client. Defaults to the object key's basename.

None
media_type str | None

Content type the store should answer with, a bare type/subtype checked by :func:~tempest_fastapi_sdk.storage.presign.download_overrides exactly as :meth:presigned_get_url checks it. None keeps the type stored with the object.

None
as_attachment bool

True (default) forces a download. False asks for inline — what <video> and <img> want — and is granted only when media_type is passed and is in :data:~tempest_fastapi_sdk.utils.download.INLINE_SAFE_MEDIA_TYPES. No stat is made, so with media_type=None the type the store will answer with is unknown here and the object is served as attachment; a type passed in is signed into the URL, so it is also the type the client receives.

True
cache_control str | None

Cache-Control the store should answer with. None sends none.

None
headers dict[str, str] | None

Extra headers on the app's response.

None

Returns:

Name Type Description
Response Response

An empty 200 carrying X-Accel-Redirect, for

Response

nginx to replace with the object.

Raises:

Type Description
ValueError

When internal_prefix does not start with /, or when media_type is not a bare type/subtype (parameters, a comma or a line break are refused before anything is signed).

serve_object async

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

Serve an object the way the constructor's accel_redirect says.

One route, two delivery modes chosen by configuration (STORAGE_ACCEL_REDIRECT via :meth:MinIOSettings.minio_kwargs): accel_redirect=False proxies the bytes through the app with :meth:download_response; True answers with :meth:accel_redirect_response into accel_prefix. Both honour Range and revalidation — the first in the app, the second in the store behind nginx.

Parameters:

Name Type Description Default
key str

Object key.

required
request Request | None

The incoming request. Proxy mode needs it for 206/304/416; redirect mode ignores it, because nginx forwards the client's headers itself.

None
bucket str | None

Override source bucket.

None
filename str | None

Name presented to the client. Defaults to the object key's basename.

None
media_type str | None

Content type. None uses the type stored with the object.

None
as_attachment bool

True (default) forces a download; False asks for inline, granted only to a type in :data:~tempest_fastapi_sdk.utils.download.INLINE_SAFE_MEDIA_TYPES. Proxy mode checks the type stored with the object; redirect mode makes no stat and checks only media_type, so pass it there to serve inline.

True
cache_control str | None

Cache-Control value. None sends none.

None
headers dict[str, str] | None

Extra headers on the app's response. In proxy mode, one named like a security default replaces that default.

None

Returns:

Name Type Description
Response Response

A :class:StreamingResponse (proxy mode) or an empty

Response

X-Accel-Redirect response (redirect mode).

Raises:

Type Description
S3Error

Proxy mode, when the object is missing or the request fails.

stat_object async

stat_object(key: str, *, bucket: str | None = None) -> ObjectStat

Fetch metadata for an object without downloading it.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override source bucket.

None

Returns:

Name Type Description
ObjectStat ObjectStat

Subset of fields commonly needed by callers.

ObjectStat

Use .raw for the full minio Object (never None

ObjectStat

on this client).

Raises:

Type Description
S3Error

When the object is missing.

list_objects async

list_objects(
    prefix: str = "", *, bucket: str | None = None, recursive: bool = True
) -> list[str]

List object keys under a prefix.

Parameters:

Name Type Description Default
prefix str

Prefix filter. Empty string returns everything.

''
bucket str | None

Override source bucket.

None
recursive bool

Walk into pseudo-directories. False returns only the immediate level.

True

Returns:

Type Description
list[str]

list[str]: Object keys. Empty list when no matches —

list[str]

matching the SDK convention of "no rows is not an

list[str]

error".

remove_object async

remove_object(
    key: str, *, bucket: str | None = None, version_id: str | None = None
) -> None

Delete an object (or a specific version).

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override target bucket.

None
version_id str | None

When the bucket has versioning enabled, the specific version to delete.

None

Raises:

Type Description
S3Error

When the delete fails for a reason other than "already gone" (deletes are idempotent on S3).

remove_objects async

remove_objects(
    keys: Iterable[str], *, bucket: str | None = None
) -> list[ObjectDeleteError]

Delete many objects with S3 batch deletes.

Uses Minio.remove_objects, which sends one DeleteObjects request per 1000 keys instead of one DELETE per key. Duplicate keys are collapsed. Keys that do not exist count as deleted (S3 deletes are idempotent), so they never appear in the result.

Parameters:

Name Type Description Default
keys Iterable[str]

Object keys to delete.

required
bucket str | None

Override target bucket.

None

Returns:

Type Description
list[ObjectDeleteError]

list[ObjectDeleteError]: The keys the store refused to delete,

list[ObjectDeleteError]

with the reported error. Empty list when every key was deleted.

Raises:

Type Description
S3Error

When a whole batch request fails (auth, network, bucket missing).

copy_object async

copy_object(
    source_key: str,
    dest_key: str,
    *,
    source_bucket: str | None = None,
    dest_bucket: str | None = None,
) -> str

Copy an object inside the same store.

Parameters:

Name Type Description Default
source_key str

Source object key.

required
dest_key str

Destination object key.

required
source_bucket str | None

Source bucket; defaults to default_bucket.

None
dest_bucket str | None

Destination bucket; defaults to default_bucket.

None

Returns:

Name Type Description
str str

ETag of the copied object (quotes stripped).

Raises:

Type Description
S3Error

When the source is missing or the copy fails.

presigned_get_url async

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

Generate a temporary download URL.

With filename, media_type or as_attachment the headers the store answers with are signed into the URL as S3 response-* overrides, the same ones :meth:download_response signs — so the link serves the type the server checked, not the one the uploader declared. Changing them in the URL breaks the signature. With none of them the store answers with what it stored.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override source bucket.

None
expires timedelta

URL lifetime. Maximum is 7 days (S3 hard limit).

timedelta(hours=1)
filename str | None

Name presented to the client; signs a Content-Disposition.

None
media_type str | None

Content-Type the store answers with, a bare type/subtype.

None
as_attachment bool | None

True forces a download; False asks for inline, granted only when media_type is inline-safe. None with a filename means True.

None

Returns:

Name Type Description
str str

Pre-signed HTTPS URL that anyone with the link

str

can GET until expiry.

Raises:

Type Description
ValueError

When media_type is not a bare type/subtype.

presigned_put_url async

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

Generate a temporary upload URL.

Lets the browser PUT directly to MinIO/S3 without the bytes touching the FastAPI process — ideal for large files.

Parameters:

Name Type Description Default
key str

Destination object key.

required
bucket str | None

Override target bucket.

None
expires timedelta

URL lifetime. Maximum is 7 days.

timedelta(minutes=15)

Returns:

Name Type Description
str str

Pre-signed HTTPS URL accepting a PUT with the

str

object body until expiry.

presigned_post_policy async

presigned_post_policy(
    key: str,
    *,
    max_bytes: int,
    content_type: str | None = None,
    min_bytes: int = 0,
    bucket: str | None = None,
    expires: timedelta = timedelta(minutes=15),
) -> PresignedPost

Generate a form upload the store caps at max_bytes.

A presigned PUT signs nothing about the body, so the service only learns the size after the bytes landed. An S3 POST policy carries a content-length-range condition, and the store refuses the upload itself (400 EntityTooLarge / EntityTooSmall) — the same cap the local backend's route applies. The key, and the Content-Type when given, are eq conditions too: the form cannot be reused for another object or another type.

The URL is path-style (<scheme>://<host>/<bucket>) on the signing host — public_endpoint when set.

Signing is local: with region set (it always is here) the client never asks the store for the bucket's region, so it runs in the event loop. minio 7.2.20 calls datetime.utcnow() while signing; that DeprecationWarning is silenced around the call, because a service running filterwarnings = ["error"] would otherwise fail every upload it tries to sign.

Parameters:

Name Type Description Default
key str

Destination object key.

required
max_bytes int

Largest accepted file, in bytes.

required
content_type str | None

The only Content-Type accepted; sent in the form fields. None leaves it free.

None
min_bytes int

Smallest accepted file. Default 0.

0
bucket str | None

Override target bucket.

None
expires timedelta

Policy lifetime. Maximum is 7 days.

timedelta(minutes=15)

Returns:

Name Type Description
PresignedPost PresignedPost

The URL, the form fields to send before the file,

PresignedPost

and the cap.

Raises:

Type Description
ValueError

When the size range is empty or inverted, or content_type is not a bare type/subtype.

IntegrationDisabledException

When the client was built with enabled=False.

presigned_get_urls async

presigned_get_urls(
    keys: Iterable[str],
    *,
    bucket: str | None = None,
    expires: timedelta = timedelta(hours=1),
    max_concurrency: int = 16,
) -> dict[str, str]

Generate presigned download URLs for many keys concurrently.

Duplicate keys are collapsed, so each object is signed once and appears a single time in the result. Signing is fail-fast: the first failure aborts the batch and propagates.

Parameters:

Name Type Description Default
keys Iterable[str]

Object keys to sign.

required
bucket str | None

Override source bucket for every key.

None
expires timedelta

URL lifetime for every key. Maximum is 7 days (S3 hard limit).

timedelta(hours=1)
max_concurrency int

Maximum signings awaited at once.

16

Returns:

Type Description
dict[str, str]

dict[str, str]: Mapping of each unique key to its presigned

dict[str, str]

GET URL.

Raises:

Type Description
ValueError

If max_concurrency is less than 1.

S3Error

When signing a key fails.

put_objects async

put_objects(
    items: Iterable[PutObjectItem],
    *,
    bucket: str | None = None,
    max_concurrency: int = 16,
) -> dict[str, str]

Upload many objects concurrently.

Uploads are fail-fast: the first failure aborts the batch and propagates. When two items share a key the later one wins in the returned mapping, matching last-write-wins on the store.

Parameters:

Name Type Description Default
items Iterable[PutObjectItem]

The objects to upload, each carrying its key, payload and per-object options.

required
bucket str | None

Override target bucket for every item.

None
max_concurrency int

Maximum uploads awaited at once.

16

Returns:

Type Description
dict[str, str]

dict[str, str]: Mapping of each item's key to the uploaded

dict[str, str]

object's ETag (quotes stripped).

Raises:

Type Description
ValueError

If max_concurrency is less than 1, or an item with file-like data omits length.

S3Error

When an upload fails.

get_objects_bytes async

get_objects_bytes(
    keys: Iterable[str], *, bucket: str | None = None, max_concurrency: int = 16
) -> dict[str, bytes]

Download many objects as bytes concurrently.

Duplicate keys are collapsed, so each object is fetched once. Downloads are fail-fast: the first failure aborts the batch and propagates. Suitable for small objects — stream large payloads individually via :meth:stream_object.

Parameters:

Name Type Description Default
keys Iterable[str]

Object keys to download.

required
bucket str | None

Override source bucket for every key.

None
max_concurrency int

Maximum downloads awaited at once.

16

Returns:

Type Description
dict[str, bytes]

dict[str, bytes]: Mapping of each unique key to its payload.

Raises:

Type Description
ValueError

If max_concurrency is less than 1.

S3Error

When a download fails.

ObjectStat dataclass

ObjectStat(
    bucket: str,
    key: str,
    size: int,
    etag: str | None,
    content_type: str | None,
    last_modified: datetime | None,
    metadata: dict[str, str],
    raw: Object | None,
)

Subset of object metadata returned by :meth:AsyncMinIOClient.stat_object.

The full minio.datatypes.Object instance is also reachable via the raw attribute when you need the long tail of fields (version id, owner, restoration state, etc.).

Attributes:

Name Type Description
bucket str

Bucket the object lives in.

key str

Object key (S3 path).

size int

Size in bytes.

etag str | None

Server-side ETag (quotes stripped).

content_type str | None

MIME type recorded at upload.

last_modified datetime | None

Last modification timestamp in UTC.

metadata dict[str, str]

User metadata keyed without the x-amz-meta- prefix.

raw Object | None

Underlying minio Object for advanced use (versioning id, owner, restore state, …). None when the stat did not come from MinIO: LocalObjectStorageClient and FakeObjectStorageClient have no minio object to hand back, so code that must run against every backend narrows it before reading.

ObjectDeleteError dataclass

ObjectDeleteError(key: str, code: str, message: str)

One key that :meth:AsyncMinIOClient.remove_objects failed to delete.

Attributes:

Name Type Description
key str

Object key the store refused to delete.

code str

S3 error code reported for the key (AccessDenied, InternalError, ...).

message str

Human-readable message reported by the store.

BucketRoutedMinIOClient

BucketRoutedMinIOClient(
    endpoint: str,
    access_key: str,
    secret_key: str,
    *,
    bucket_credentials: Mapping[str, StorageBucketCredential],
    default_bucket: str = "uploads",
    secure: bool = False,
    region: str = "us-east-1",
    session_token: str | None = None,
    public_endpoint: str | None = None,
    public_secure: bool | None = None,
    accel_redirect: bool = False,
    accel_prefix: str = "/_bucket/",
    enabled: bool = True,
)

Bases: AsyncMinIOClient

An :class:AsyncMinIOClient that signs each bucket with its own key.

Built like :class:AsyncMinIOClient, plus bucket_credentials. The constructor arguments describe the primary credential, which answers every bucket missing from bucket_credentials; each listed bucket gets a client of its own with the same endpoint, region, TLS and public endpoint, and only its keys swapped.

Every operation that takes bucket resolves it first (bucket or default_bucket) and is sent through the client of that bucket — presigned URLs included, so a link is signed by the key that can read the object. Two calls name no bucket and stay on the primary credential: :meth:list_buckets and the :attr:client property.

:meth:copy_object is the one call with two buckets. When both resolve to the same credential it is the store's server-side copy, unchanged; when they resolve to different credentials no single key can read the source and write the destination, so the object is read with the source key into a temporary file and uploaded with the destination key.

Example:

>>> from pydantic import SecretStr
>>> from tempest_fastapi_sdk.storage import (
...     BucketRoutedMinIOClient,
...     StorageBucketCredential,
... )
>>> storage = BucketRoutedMinIOClient(
...     "storage.example.com",
...     "images-key",
...     "images-secret",
...     default_bucket="images",
...     secure=True,
...     bucket_credentials={
...         "documents": StorageBucketCredential(
...             access_key="documents-key",
...             secret_key=SecretStr("documents-secret"),
...         ),
...     },
... )
>>> sorted(storage.routed_buckets)
['documents']

Initialize the primary client and one client per listed bucket.

Parameters:

Name Type Description Default
endpoint str

host[:port] without scheme, shared by every credential.

required
access_key str

Primary access key, used for every bucket missing from bucket_credentials.

required
secret_key str

Primary secret key.

required
bucket_credentials Mapping[str, StorageBucketCredential]

Bucket name to the credential that reaches it.

required
default_bucket str

Bucket of a call that names none. It is routed like any other: listed in bucket_credentials, it uses that credential.

'uploads'
secure bool

Use HTTPS when True.

False
region str

S3 region.

'us-east-1'
session_token str | None

STS session token of the primary credential only; the per-bucket clients sign without one.

None
public_endpoint str | None

Split-endpoint host presigned URLs are signed against, for every credential.

None
public_secure bool | None

HTTPS for public_endpoint.

None
accel_redirect bool

Delivery mode of :meth:serve_object.

False
accel_prefix str

Internal nginx location of X-Accel-Redirect.

'/_bucket/'
enabled bool

False builds a client whose every operation raises IntegrationDisabledException; no per-bucket client is built.

True

Raises:

Type Description
ValueError

When a bucket name in bucket_credentials is empty, or accel_prefix does not start with /.

ImportError

When the minio package is not installed and enabled is True.

routed_buckets property

routed_buckets: frozenset[str]

Return the buckets that have a credential of their own.

Empty when the client was built with enabled=False.

Returns:

Type Description
frozenset[str]

frozenset[str]: Bucket names; any other bucket uses the

frozenset[str]

primary credential.

copy_object async

copy_object(
    source_key: str,
    dest_key: str,
    *,
    source_bucket: str | None = None,
    dest_bucket: str | None = None,
) -> str

Copy an object, across credentials when the buckets need it.

Both buckets on the same credential: the store's server-side copy (:meth:AsyncMinIOClient.copy_object). On different credentials: the source is downloaded with its key into a temporary file (deleted afterwards) and uploaded with the destination key, carrying the source's Content-Type and user metadata. Other stored headers (Cache-Control, Content-Disposition) are not carried over on that path, and the bytes cross the app.

Parameters:

Name Type Description Default
source_key str

Source object key.

required
dest_key str

Destination object key.

required
source_bucket str | None

Source bucket; defaults to default_bucket.

None
dest_bucket str | None

Destination bucket; defaults to default_bucket.

None

Returns:

Name Type Description
str str

ETag of the copied object (quotes stripped).

Raises:

Type Description
S3Error

When the source is missing or either side refuses.

IntegrationDisabledException

When the client was built with enabled=False.

LocalObjectStorageClient

LocalObjectStorageClient(
    base_dir: Path | str,
    *,
    public_url: str,
    signing_secret: str,
    default_bucket: str = "uploads",
    route_prefix: str = DEFAULT_LOCAL_STORAGE_ROUTE_PREFIX,
    max_upload_bytes: int = DEFAULT_LOCAL_MAX_UPLOAD_BYTES,
    enabled: bool = True,
    encryption_keys: Mapping[str, bytes] | None = None,
    allow_plaintext_read: bool = False,
)

Object storage in a local directory, with signed links to the app.

Satisfies :class:~tempest_fastapi_sdk.privacy.SubjectStorageClient, so it drops in where :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient goes under :class:~tempest_fastapi_sdk.privacy.SubjectObjectStorage.

Example:

>>> client = LocalObjectStorageClient(
...     "/var/lib/app/storage",
...     public_url="https://api.example.com",
...     signing_secret=settings.JWT_SECRET,
... )
>>> await client.put_object("a.txt", b"hi", content_type="text/plain")
'49f68a5c8493ec2c0bf489821c21fc3b'
>>> await client.presigned_get_url("a.txt")
'https://api.example.com/storage/uploads/a.txt?expires=...&signature=...'

Attributes:

Name Type Description
base_dir Path

Resolved root of the store.

public_url str

Scheme and host the links start with, no trailing slash.

route_prefix str

Path the signed routes live under.

default_bucket str

Bucket used when a call passes none.

max_upload_bytes int

Largest body the signed PUT accepts.

enabled bool

False makes every operation raise :class:~tempest_fastapi_sdk.exceptions.IntegrationDisabledException.

allow_plaintext_read bool

Whether an object without the encrypted header is served as plaintext while encryption is on.

Create the store's directories and keep the signing material.

Parameters:

Name Type Description Default
base_dir Path | str

Root directory of the store. Created with its parents when missing.

required
public_url str

Scheme and host the browser reaches the app at ("https://api.example.com"). A trailing slash is stripped.

required
signing_secret str

Secret the links are signed with. Domain separation makes reusing JWT_SECRET safe.

required
default_bucket str

Bucket used when a call passes none. Default "uploads".

'uploads'
route_prefix str

Path the signed routes are mounted at, as the app sees it in request.scope["path"] — include any parent prefix ("/api/storage"). Must start with /.

DEFAULT_LOCAL_STORAGE_ROUTE_PREFIX
max_upload_bytes int

Largest body the signed PUT accepts. Default 25 MiB.

DEFAULT_LOCAL_MAX_UPLOAD_BYTES
enabled bool

False builds a client for an integration switched off by STORAGE_ENABLED=false: no directory is created and every operation raises :class:~tempest_fastapi_sdk.exceptions.IntegrationDisabledException (503). Default True.

True
encryption_keys Mapping[str, bytes] | None

Key id to 32-byte AES-256 key. Set, every object written is encrypted at rest with the first key (insertion order), and an object is read with whichever key its header names — put a new key first to rotate, and keep the old ones until :meth:reencrypt ran. None or empty (default) stores plaintext, exactly as before. Needs cryptography (the [storage-encryption] extra).

None
allow_plaintext_read bool

With encryption_keys, serve an object that has no encrypted header as plaintext — for a store that held files before encryption was switched on, until :meth:encrypt_existing converted them. False (default) refuses such a file with :class:~tempest_fastapi_sdk.exceptions.StorageIntegrityException. Ignored without keys.

False

Raises:

Type Description
ValueError

When public_url has no http(s):// scheme, route_prefix does not start with /, the default bucket is not a single valid segment, max_upload_bytes is not positive, signing_secret is empty (only checked when enabled), or a key id or key in encryption_keys is malformed.

ImportError

When encryption_keys is set on an enabled client and cryptography is not installed.

encrypted property

encrypted: bool

Whether objects are written encrypted at rest.

Returns:

Name Type Description
bool bool

True when the client holds encryption_keys.

write_key_id property

write_key_id: str | None

Id of the key new objects are sealed with.

Returns:

Type Description
str | None

str | None: The first id of encryption_keys; None

str | None

without encryption.

check_key staticmethod

check_key(key: str) -> str

Validate an object key.

Parameters:

Name Type Description Default
key str

The candidate key, /-separated.

required

Returns:

Name Type Description
str str

key unchanged.

Raises:

Type Description
ValueError

When the key is empty, starts with /, or holds an empty, ., .. or metadata-suffixed segment, a backslash or a NUL — anything that could leave the bucket.

object_path

object_path(key: str, *, bucket: str | None = None) -> Path

Return where the bytes of key live on disk.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Bucket; None for the default.

None

Returns:

Name Type Description
Path Path

The file path (it may not exist).

Raises:

Type Description
ValueError

When the bucket or key is invalid, or resolves out of the store.

put_object async

put_object(
    key: str,
    data: bytes | BinaryIO,
    *,
    bucket: str | None = None,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
    length: int | None = None,
) -> str

Store one object, replacing any previous one atomically.

Parameters:

Name Type Description Default
key str

Object key.

required
data bytes | BinaryIO

The payload; a stream is read up to length bytes, or to its end.

required
bucket str | None

Target bucket.

None
content_type str

MIME type, reported back by :meth:stat_object and served by the download route.

'application/octet-stream'
metadata dict[str, str] | None

User metadata, reported back by :meth:stat_object.

None
length int | None

Bytes to read from a stream; None or -1 reads to the end.

None

Returns:

Name Type Description
str str

The ETag — the MD5 of the payload, hex; with

str

encryption_keys, the MD5 of the encrypted file instead.

Raises:

Type Description
ValueError

When the bucket or key is invalid.

OSError

When the write fails (disk full, permissions, a key that needs a directory where a file is).

IntegrationDisabledException

When built with enabled=False.

write_stream async

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

Store an object from an async chunk stream, capped at max_bytes.

The stream is written to a temporary file as it arrives and moved into place only when it ended within the cap; going past the cap stops reading and leaves nothing behind.

Parameters:

Name Type Description Default
key str

Object key.

required
chunks AsyncIterator[bytes]

The payload, in order.

required
bucket str | None

Target bucket.

None
content_type str

MIME type.

'application/octet-stream'
metadata dict[str, str] | None

User metadata.

None
max_bytes int | None

Largest payload accepted; None for no cap.

None

Returns:

Name Type Description
str str

The ETag — the MD5 of the payload, hex; with

str

encryption_keys, the MD5 of the encrypted file instead.

str

max_bytes always counts the payload, never the header and

str

tags encryption adds.

Raises:

Type Description
FileTooLargeException

When the stream passes max_bytes (413).

ValueError

When the bucket or key is invalid.

OSError

When the write fails.

IntegrationDisabledException

When built with enabled=False.

presigned_get_url async

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

Build a temporary download link served by the app.

The object does not need to exist yet; the route answers 404 if it still does not when the link is opened.

filename, media_type and as_attachment travel in the query and are bound into the signature (:func:bound_purpose), the way S3 signs its response-* overrides: the route answers with them, and editing one breaks the link. Unset, the route serves the stored type with its own as_attachment default.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Source bucket.

None
expires timedelta

Link lifetime; at most 7 days.

timedelta(hours=1)
filename str | None

Name presented to the client.

None
media_type str | None

Content-Type the route answers with, a bare type/subtype.

None
as_attachment bool | None

True forces a download; False asks for inline, granted only to inline-safe types. None keeps the router's default.

None

Returns:

Name Type Description
str str

<public_url><route_prefix>/<bucket>/<key>, with the

str

expires and signature query parameters.

Raises:

Type Description
ValueError

When the key is invalid or expires is out of range.

IntegrationDisabledException

When built with enabled=False.

presigned_put_url async

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

Build a temporary upload link served by the app.

The client PUTs the raw bytes to it with a Content-Type header; the route caps the body at :attr:max_upload_bytes. As with S3, nothing about the payload is signed — verify it with :meth:stat_object before trusting it.

Parameters:

Name Type Description Default
key str

Destination object key.

required
bucket str | None

Target bucket.

None
expires timedelta

Link lifetime; at most 7 days.

timedelta(minutes=15)

Returns:

Name Type Description
str str

The signed URL accepting a PUT.

Raises:

Type Description
ValueError

When the key is invalid or expires is out of range.

IntegrationDisabledException

When built with enabled=False.

presigned_post_policy async

presigned_post_policy(
    key: str,
    *,
    max_bytes: int,
    content_type: str | None = None,
    min_bytes: int = 0,
    bucket: str | None = None,
    expires: timedelta = timedelta(minutes=15),
) -> PresignedPost

Build a form upload the route caps at max_bytes.

The same call, and the same :class:PresignedPost, as :meth:AsyncMinIOClient.presigned_post_policy <tempest_fastapi_sdk.storage.AsyncMinIOClient.presigned_post_policy>: the browser posts multipart/form-data with the fields and then the file, and the code that sends it does not know which backend signed. The limits ride in the URL, bound into the signature; the route refuses a file outside them (413 FILE_TOO_LARGE / 400 FILE_TOO_SMALL), a different Content-Type field or a different key field (403), and stores nothing.

Reading the form needs python-multipart (the [upload] extra); it is checked here, so a missing extra fails where the link is issued instead of on the uploader's request.

Parameters:

Name Type Description Default
key str

Destination object key.

required
max_bytes int

Largest accepted file; at most :attr:max_upload_bytes.

required
content_type str | None

The only Content-Type accepted. None leaves it free.

None
min_bytes int

Smallest accepted file. Default 0.

0
bucket str | None

Target bucket.

None
expires timedelta

Link lifetime; at most 7 days.

timedelta(minutes=15)

Returns:

Name Type Description
PresignedPost PresignedPost

The URL, the form fields and the cap.

Raises:

Type Description
ValueError

When the size range is empty, inverted or above :attr:max_upload_bytes, the key is invalid, or content_type is not a bare type/subtype.

ImportError

When python-multipart is not installed.

IntegrationDisabledException

When built with enabled=False.

verify_link(
    request: Request, *, purpose: str, names: tuple[str, ...] = ()
) -> dict[str, str]

Verify a link whose extra query parameters are bound to it.

The check behind the routes of :func:~tempest_fastapi_sdk.storage.make_local_storage_router: the purpose is rebuilt with :func:bound_purpose from the parameters in names that the request carries, so a link whose limits or overrides were edited verifies as another purpose and fails.

Parameters:

Name Type Description Default
request Request

The incoming request.

required
purpose str

The route's base purpose.

required
names tuple[str, ...]

The parameters this route binds — :data:LOCAL_GET_LINK_PARAMS or :data:LOCAL_POST_LINK_PARAMS.

()

Returns:

Type Description
dict[str, str]

dict[str, str]: The bound parameters the link carried.

Raises:

Type Description
InvalidSignedURLException

403 when the signature is missing, malformed or does not match.

ExpiredSignedURLException

403 when the link expired.

signature_dependency

signature_dependency(purpose: str) -> Callable[..., Coroutine[Any, Any, None]]

Build the FastAPI dependency that verifies this store's links.

:func:~tempest_fastapi_sdk.storage.make_local_storage_router uses it; call it yourself only to serve the links from a route of your own.

Parameters:

Name Type Description Default
purpose str

:data:LOCAL_STORAGE_GET_PURPOSE or :data:LOCAL_STORAGE_PUT_PURPOSE.

required

Returns:

Type Description
Callable[..., Coroutine[Any, Any, None]]

Callable[..., Coroutine[Any, Any, None]]: The dependency from

Callable[..., Coroutine[Any, Any, None]]

func:~tempest_fastapi_sdk.api.make_signed_path_dependency,

Callable[..., Coroutine[Any, Any, None]]

bound to this store's secret.

Raises:

Type Description
ValueError

When the store was built with an empty secret.

stat_object async

stat_object(key: str, *, bucket: str | None = None) -> ObjectStat

Describe a stored object without reading it.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Source bucket.

None

Returns:

Name Type Description
ObjectStat ObjectStat

Size and modification time from the file; content

ObjectStat

type, metadata and ETag from the metadata file. raw is

ObjectStat

None: there is no minio object behind a disk. With

ObjectStat

encryption_keys, size is the plaintext size, computed

ObjectStat

from the file's header and length without decrypting; a

ObjectStat

plaintext file reports its own size.

Raises:

Type Description
LocalObjectNotFoundError

When the object is not stored.

StorageIntegrityException

"format" when an encrypted file's header or size is malformed.

ValueError

When the bucket or key is invalid.

IntegrationDisabledException

When built with enabled=False.

stream_object async

stream_object(
    key: str,
    *,
    bucket: str | None = None,
    chunk_size: int = LOCAL_STORAGE_CHUNK_SIZE,
    offset: int = 0,
    length: int | None = None,
) -> AsyncIterator[bytes]

Open a stored object, or one byte range of it, as a chunk stream.

The file is opened before this returns, so a missing object fails here and not at the first chunk. A length past the end yields what exists.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Source bucket.

None
chunk_size int

Bytes per chunk. Default 64 KiB.

LOCAL_STORAGE_CHUNK_SIZE
offset int

First byte to read.

0
length int | None

Bytes to read from offset; None reads to the end.

None

With encryption_keys, offset and length count plaintext bytes, and only the blocks that overlap the range are read and decrypted — a Range request or a capped :meth:~tempest_fastapi_sdk.privacy.SubjectObjectStorage.read decrypts no more than it serves. The first block is authenticated before this returns; every later one before it is yielded.

Returns:

Type Description
AsyncIterator[bytes]

AsyncIterator[bytes]: The chunks, in order; the file closes when

AsyncIterator[bytes]

the stream ends or is closed.

Raises:

Type Description
ValueError

When offset is negative, length or chunk_size is not positive, or the bucket or key is invalid.

LocalObjectNotFoundError

When the object is not stored.

StorageIntegrityException

With encryption_keys, when a block fails authentication, the file is cut or malformed, its key id is not in the ring, or it is plaintext and allow_plaintext_read is off. Raised here for the first block of the range, and by the iterator for a later one.

IntegrationDisabledException

When built with enabled=False.

list_objects async

list_objects(
    prefix: str = "", *, bucket: str | None = None, recursive: bool = True
) -> list[str]

List object keys under prefix, sorted.

Parameters:

Name Type Description Default
prefix str

Prefix filter.

''
bucket str | None

Source bucket.

None
recursive bool

True (default) lists every key under the prefix; False lists one level, with each "subdirectory" as a key ending in / — as S3 answers.

True

Returns:

Type Description
list[str]

list[str]: The matching keys; [] for an empty or unknown

list[str]

bucket.

Raises:

Type Description
ValueError

When the bucket is invalid.

IntegrationDisabledException

When built with enabled=False.

remove_object async

remove_object(
    key: str, *, bucket: str | None = None, version_id: str | None = None
) -> None

Delete one object; a missing key is not an error, as on S3.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Target bucket.

None
version_id str | None

Accepted for signature parity; a disk keeps no versions.

None

Raises:

Type Description
ValueError

When the bucket or key is invalid.

OSError

When the file cannot be removed (permissions).

IntegrationDisabledException

When built with enabled=False.

remove_objects async

remove_objects(
    keys: Iterable[str], *, bucket: str | None = None
) -> list[ObjectDeleteError]

Delete many objects, reporting the ones that could not go.

Parameters:

Name Type Description Default
keys Iterable[str]

Object keys; duplicates collapse.

required
bucket str | None

Target bucket.

None

Returns:

Type Description
list[ObjectDeleteError]

list[ObjectDeleteError]: AccessDenied for a permission error,

list[ObjectDeleteError]

InternalError for any other failure (an invalid key

list[ObjectDeleteError]

included); those objects stay. Empty when all were deleted.

Raises:

Type Description
IntegrationDisabledException

When built with enabled=False.

encrypt_existing async

encrypt_existing(prefix: str = '', *, bucket: str | None = None) -> int

Encrypt every plaintext object under prefix with the write key.

The migration of a store that held files before encryption_keys was set. Idempotent: an object that already has the encrypted header is skipped, so running it twice — or after an interrupted run — rewrites nothing that is done. Content type and metadata are kept; the ETag becomes the MD5 of the encrypted file. Runs whether allow_plaintext_read is on or off.

Parameters:

Name Type Description Default
prefix str

Only keys starting with it. Default: all.

''
bucket str | None

Bucket; None for the default. Use :meth:list_buckets to cover every bucket.

None

Returns:

Name Type Description
int int

Objects encrypted by this call.

Raises:

Type Description
ValueError

When the client has no encryption_keys, or the bucket is invalid.

OSError

When a file cannot be read or written.

IntegrationDisabledException

When built with enabled=False.

reencrypt async

reencrypt(prefix: str = '', *, bucket: str | None = None) -> int

Rewrite every object sealed with an older key under the write key.

The second half of a key rotation: put the new key first in encryption_keys (writes switch to it at once, reads keep working with the old one), run this, then drop the old key. Idempotent: an object already under the write key is skipped, and so is a plaintext one (:meth:encrypt_existing handles those). An object that fails to decrypt stops the run with the error, before anything is written for it.

Parameters:

Name Type Description Default
prefix str

Only keys starting with it. Default: all.

''
bucket str | None

Bucket; None for the default.

None

Returns:

Name Type Description
int int

Objects rewritten by this call.

Raises:

Type Description
ValueError

When the client has no encryption_keys, or the bucket is invalid.

StorageIntegrityException

When an object fails to decrypt — its key is no longer in the ring, or the file is damaged.

OSError

When a file cannot be read or written.

IntegrationDisabledException

When built with enabled=False.

list_buckets async

list_buckets() -> list[str]

List the buckets that hold at least one directory on disk.

Returns:

Type Description
list[str]

list[str]: Bucket names, sorted; [] for an empty store.

Raises:

Type Description
IntegrationDisabledException

When built with enabled=False.

download_response async

download_response(
    key: str,
    *,
    request: Request | None = None,
    bucket: str | None = None,
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool = True,
    chunk_size: int = LOCAL_STORAGE_CHUNK_SIZE,
    cache_control: str | None = None,
    headers: dict[str, str] | None = None,
) -> StreamingResponse

Stream an object as a download response, Range included.

Same behaviour as :meth:AsyncMinIOClient.download_response <tempest_fastapi_sdk.storage.AsyncMinIOClient.download_response>: both delegate to the same function.

Parameters:

Name Type Description Default
key str

Object key.

required
request Request | None

The incoming request, whose Range and validator headers are honoured.

None
bucket str | None

Source bucket.

None
filename str | None

Name presented to the client.

None
media_type str | None

Content type; defaults to the stored one.

None
as_attachment bool

True forces a download; False asks for inline, granted only for inline-safe types.

True
chunk_size int

Bytes per streamed chunk.

LOCAL_STORAGE_CHUNK_SIZE
cache_control str | None

Cache-Control value.

None
headers dict[str, str] | None

Extra response headers.

None

Returns:

Name Type Description
StreamingResponse StreamingResponse

200, 206, 304 or 416.

With encryption_keys the response is the decrypted object; Content-Length, Range and Content-Range count plaintext bytes, and a range decrypts only the blocks it covers.

Raises:

Type Description
LocalObjectNotFoundError

When the object is not stored.

StorageIntegrityException

When the first block served fails to verify (see :meth:stream_object). A later block that fails aborts the stream after the response started; no byte of an unverified block is sent.

IntegrationDisabledException

When built with enabled=False.

bound_purpose

bound_purpose(purpose: str, params: dict[str, str]) -> str

Bind a link's extra query parameters into its signing purpose.

:func:~tempest_fastapi_sdk.utils.signed_url.sign_path covers the path and the expiry only. The download overrides and the upload limits ride in the query, so they are folded into the purpose instead: the route rebuilds the purpose from the parameters it received, and any change to them — a bigger max_bytes, another media_type — verifies as a different purpose and fails. With no parameters the purpose is unchanged, so a plain link signed before these existed still verifies.

Parameters:

Name Type Description Default
purpose str

The base purpose.

required
params dict[str, str]

The parameters the link carries.

required

Returns:

Name Type Description
str str

purpose alone, or followed by NUL and the parameters,

str

sorted and URL-encoded.

PresignedPost dataclass

PresignedPost(url: str, max_bytes: int, fields: dict[str, str] = dict())

A form upload the store accepts only within the signed limits.

The browser sends multipart/form-data to :attr:url with every pair of :attr:fields and then the file in :data:POST_FILE_FIELD. A body outside [min_bytes, max_bytes], a different key or a different Content-Type is refused by the store itself.

Attributes:

Name Type Description
url str

Where the form is posted.

fields dict[str, str]

Form fields to send, unchanged, before the file.

max_bytes int

The largest file the store accepts.

LocalObjectNotFoundError

LocalObjectNotFoundError(bucket: str, key: str)

Bases: FileNotFoundError

Raised when a key is not stored in the bucket.

A :class:FileNotFoundError — so except OSError catches it — with the S3 error code beside it, so code written against S3Error.code can branch the same way.

Attributes:

Name Type Description
code str

Always "NoSuchKey".

bucket str

The bucket that was read.

key str

The key that is missing.

Build the error.

Parameters:

Name Type Description Default
bucket str

The bucket that was read.

required
key str

The key that is missing.

required

LocalObjectCipher

LocalObjectCipher(keys: Mapping[str, bytes])

The key ring of an encrypted local store.

The first key (insertion order) seals new objects; any key opens the objects sealed with it, by the id in their header — which is how a key is rotated: put the new one first, keep the old one until :meth:~tempest_fastapi_sdk.storage.LocalObjectStorageClient.reencrypt has rewritten everything.

Attributes:

Name Type Description
write_key_id str

Id of the key new objects are sealed with.

Validate the keys and build one AES-GCM instance per key.

Parameters:

Name Type Description Default
keys Mapping[str, bytes]

Key id to 32-byte key; at least one.

required

Raises:

Type Description
ValueError

When keys is empty or a key fails :func:check_encryption_keys.

ImportError

When cryptography is not installed.

has_key

has_key(key_id: str) -> bool

Tell whether the ring holds a key.

Parameters:

Name Type Description Default
key_id str

The key id.

required

Returns:

Name Type Description
bool bool

True when objects sealed with it can be opened.

encryptor

encryptor(object_name: str) -> BlockEncryptor

Start sealing a new object with the write key.

Parameters:

Name Type Description Default
object_name str

<bucket>/<key>, bound into every block.

required

Returns:

Name Type Description
BlockEncryptor BlockEncryptor

The encryptor, with a fresh nonce prefix.

reader

reader(
    handle: IO[bytes], header: EncryptedHeader, *, file_size: int, object_name: str
) -> EncryptedObjectReader

Open the blocks of a stored object for reading.

Parameters:

Name Type Description Default
handle IO[bytes]

The open file.

required
header EncryptedHeader

Its header, already read.

required
file_size int

The file's size on disk.

required
object_name str

<bucket>/<key> the object is read as.

required

Returns:

Name Type Description
EncryptedObjectReader EncryptedObjectReader

The reader.

Raises:

Type Description
StorageIntegrityException

"unknown_key" when the ring lacks the header's key id, "format" when the size is not one this format produces.

make_local_storage_router

make_local_storage_router(
    client: LocalObjectStorageClient,
    *,
    as_attachment: bool = False,
    cache_control: str | None = "private, no-store",
) -> APIRouter

Build the GET/PUT/POST routes for a local store's signed links.

  • GET {route_prefix}/{bucket}/{key} verifies a download signature and streams the object with its stored content type, honouring Range and the validators (206/304/416) the same way :meth:AsyncMinIOClient.download_response <tempest_fastapi_sdk.storage.AsyncMinIOClient.download_response> does. A missing object answers 404 NOT_FOUND. A link signed with filename/media_type/as_attachment answers with those, the way S3 answers a link with signed response-* overrides.
  • PUT {route_prefix}/{bucket}/{key} verifies an upload signature and stores the raw body with the request's Content-Type. A Content-Length over :attr:LocalObjectStorageClient.max_upload_bytes is refused before reading; without it the body is counted while it streams and cut at the cap — 413 FILE_TOO_LARGE either way, and nothing is stored. Success answers 200 with the ETag, as S3 does.
  • POST {route_prefix}/{bucket}/{key} answers a :meth:LocalObjectStorageClient.presigned_post_policy form. The file must fit the signed [min_bytes, max_bytes] — 413 FILE_TOO_LARGE / 400 FILE_TOO_SMALL otherwise — and the key and Content-Type fields must match the signed ones (403 SIGNED_URL_INVALID). Success answers 204 with the ETag, as S3 does. Reading the form needs python-multipart ([upload]).

A tampered, unsigned or wrong-purpose link answers 403 SIGNED_URL_INVALID, an expired one 403 SIGNED_URL_EXPIRED. Both routes stay out of the OpenAPI schema.

With encryption_keys on the client the routes do not change shape: PUT and POST store the body encrypted, the caps count the plaintext, and GET (Range included) answers the plaintext. A stored file whose first served block fails its check answers 500 STORAGE_INTEGRITY_ERROR with no byte of it; a later block that fails cuts the connection after the blocks that verified.

Parameters:

Name Type Description Default
client LocalObjectStorageClient

The store whose links to serve.

required
as_attachment bool

True makes downloads save as a file; False (default) shows inline-safe types (images, PDF) in the browser, which is what an <img src> needs.

False
cache_control str | None

Cache-Control of downloads. Default "private, no-store": the link is a short-lived capability, so no shared cache keeps the bytes. None sends none.

'private, no-store'

Returns:

Name Type Description
APIRouter APIRouter

Router with prefix=client.route_prefix; include it at

APIRouter

the app root.

make_tus_router

make_tus_router(
    store: TusStore,
    *,
    prefix: str = "/api/uploads",
    max_size: int = DEFAULT_TUS_MAX_SIZE,
    max_chunk_size: int = DEFAULT_TUS_MAX_CHUNK_SIZE,
    expiration: timedelta | None = DEFAULT_TUS_EXPIRATION,
    current_user_id: Callable[..., Any] | None = None,
    on_complete: TusCompleteCallback | None = None,
    max_uploads_per_owner: int | None = None,
    max_bytes_per_owner: int | None = None,
    body_read_timeout: timedelta = DEFAULT_TUS_BODY_READ_TIMEOUT,
    tags: list[str] | None = None,
    include_in_schema: bool = True,
) -> APIRouter

Build the tus routes createResumableUpload talks to.

Every response of these routes carries Tus-Resumable: 1.0.0, and so does every refusal raised while handling them (the router's errors and a 401/403 from current_user_id); an unhandled 500 is answered by the app without it. Errors use the SDK envelope (detail/code/details) through :class:~tempest_fastapi_sdk.AppException, so mount the app with :func:~tempest_fastapi_sdk.register_exception_handlers as usual.

A PATCH takes the upload's lock before reading its body; a second PATCH or DELETE arriving meanwhile answers 409 TUS_UPLOAD_LOCKED at once, so one upload never has two bodies spooled. Under the lock: owner (404), expiry (410), already complete (409 TUS_UPLOAD_COMPLETED), offset (409), size (413), the store's min_chunk_size (400). The PATCH that stores the last byte finalizes the upload and calls on_complete — exactly once per upload. An empty PATCH writes nothing and does not renew the expiry.

The lock lives on the store instance, in this process. Two replicas behind a load balancer can still race on one upload; route an upload's requests to one replica (sticky sessions on the upload path) when you run more than one.

Parameters:

Name Type Description Default
store TusStore

Where uploads live — :class:LocalTusStore <tempest_fastapi_sdk.storage.tus.LocalTusStore> or :class:S3TusStore <tempest_fastapi_sdk.storage.tus.S3TusStore>.

required
prefix str

The creation endpoint; uploads live under {prefix}/{id}. Defaults to "/api/uploads", the path the tempest-react-sdk examples post to.

'/api/uploads'
max_size int

Largest Upload-Length accepted; past it the creation answers 413 with Tus-Max-Size.

DEFAULT_TUS_MAX_SIZE
max_chunk_size int

Largest PATCH body accepted.

DEFAULT_TUS_MAX_CHUNK_SIZE
expiration timedelta | None

How long an incomplete upload stays resumable after creation or its last PATCH that stored bytes, sent as Upload-Expires. None never expires uploads. Expired ones answer 410 and are deleted by :meth:TusStore.purge_expired <tempest_fastapi_sdk.storage.tus.TusStore.purge_expired>.

DEFAULT_TUS_EXPIRATION
current_user_id Callable[..., Any] | None

FastAPI dependency resolving the caller's id as str, int or UUID (any other type raises TypeError). Its str() is stored as the upload's owner, and only the same value can probe, continue or delete it; anyone else gets 404. None makes uploads anonymous: the unguessable URL is then the only capability, and Idempotency-Key is ignored (there is no owner to scope it by).

None
on_complete TusCompleteCallback | None

Awaited once with the upload and the store when the last byte is stored. If it raises, the request answers 500, the upload stays complete with notified false, and the client — whose next HEAD sees every byte — does not retry; find those with :meth:TusStore.list_uploads <tempest_fastapi_sdk.storage.tus.TusStore.list_uploads>.

None
max_uploads_per_owner int | None

Most unfinished, unexpired uploads one owner may hold; a creation past it answers 403 TUS_QUOTA_EXCEEDED. None (default) sets no limit. Applies only to callers with an owner: in anonymous mode every caller would share one quota, so none is enforced. An empty upload completes on creation and is never counted. Checking reads every record in the store (:meth:TusStore.list_uploads <tempest_fastapi_sdk.storage.tus.TusStore.list_uploads>) on each creation, so keep the store swept with purge_expired.

None
max_bytes_per_owner int | None

Most declared bytes (Upload-Length) one owner's unfinished uploads may add up to; same answer and same cost. None (default) sets no limit.

None
body_read_timeout timedelta

Longest wait for the next piece of a PATCH body. Past it the request answers 408 TUS_BODY_READ_TIMEOUT (which the client retries), the chunk is discarded whole — the stored offset does not move — and the upload's lock is released. 30 seconds by default.

DEFAULT_TUS_BODY_READ_TIMEOUT
tags list[str] | None

OpenAPI tags. Defaults to ["uploads"].

None
include_in_schema bool

Whether the routes appear in OpenAPI.

True

Returns:

Name Type Description
APIRouter APIRouter

Ready for app.include_router.

TusCompleteCallback

Bases: Protocol

Called exactly once per upload, after its last byte is stored and finalized.

Receives the upload and the store, so it can read the file with :meth:TusStore.stream <tempest_fastapi_sdk.storage.tus.TusStore.stream> (or :meth:LocalTusStore.data_path <tempest_fastapi_sdk.storage.tus.LocalTusStore.data_path> / :meth:S3TusStore.object_key <tempest_fastapi_sdk.storage.tus.S3TusStore.object_key>) and register, move or delete it. Runs inside the request that sent the last chunk, under the upload's lock, before the 204; a later PATCH to the complete upload answers 409 without calling it. Whatever it returns is discarded, and it may call :meth:TusStore.delete <tempest_fastapi_sdk.storage.tus.TusStore.delete> — the router then leaves the record deleted.

TusStore

Bases: ABC

Persistence contract of :func:~tempest_fastapi_sdk.storage.tus.make_tus_router.

Writes to one upload are serialized by a lock table that lives on the store instance and is shared by every router built over it and by :meth:purge_expired; it covers one process. A method given an id that fails :func:valid_upload_id treats it as absent instead of building a path or key from it.

Subclass it to keep uploads elsewhere; :meth:purge_expired and :meth:list_uploads come for free from the abstract methods.

min_chunk_size class-attribute instance-attribute

min_chunk_size: int = 0

Smallest chunk the router accepts, except the one that ends the upload.

create abstractmethod async

create(upload: TusUpload) -> None

Persist a new upload with no bytes.

Parameters:

Name Type Description Default
upload TusUpload

The record, offset 0.

required

load abstractmethod async

load(upload_id: str) -> TusUpload | None

Read an upload's record.

Parameters:

Name Type Description Default
upload_id str

The id.

required

Returns:

Type Description
TusUpload | None

TusUpload | None: The record, or None when absent or the id

TusUpload | None

is malformed.

save abstractmethod async

save(upload: TusUpload) -> None

Overwrite an upload's record.

Parameters:

Name Type Description Default
upload TusUpload

The record to persist.

required

write abstractmethod async

write(upload: TusUpload, data: BinaryIO, size: int) -> None

Store size bytes of data at upload.offset.

Does not change the record: the router saves the new offset after this returns, so a failure here leaves the upload where it was.

Parameters:

Name Type Description Default
upload TusUpload

The upload, with the offset the bytes start at.

required
data BinaryIO

A stream positioned at the first byte.

required
size int

How many bytes to take from it.

required

finalize abstractmethod async

finalize(upload: TusUpload) -> None

Turn the stored chunks into the finished file.

Called once offset == length, before on_complete.

Parameters:

Name Type Description Default
upload TusUpload

The complete upload.

required

discard_parts async

discard_parts(upload: TusUpload) -> None

Drop whatever :meth:finalize assembled from, once the record says complete.

Called after the complete record is saved, so a failure here never leaves an upload that cannot finish; a store with nothing to drop keeps this no-op.

Parameters:

Name Type Description Default
upload TusUpload

The complete upload.

required

stream abstractmethod

stream(
    upload_id: str, *, chunk_size: int = TUS_STREAM_CHUNK_SIZE
) -> AsyncIterator[bytes]

Read a finished upload's bytes.

Parameters:

Name Type Description Default
upload_id str

The id of a finalized upload.

required
chunk_size int

Bytes per yielded chunk.

TUS_STREAM_CHUNK_SIZE

Returns:

Type Description
AsyncIterator[bytes]

AsyncIterator[bytes]: The file, in order.

delete abstractmethod async

delete(upload_id: str) -> None

Remove an upload's bytes, record and idempotency entry.

Idempotent: an absent upload is not an error.

Parameters:

Name Type Description Default
upload_id str

The id.

required

list_ids abstractmethod async

list_ids() -> list[str]

List the ids of every stored upload.

Returns:

Type Description
list[str]

list[str]: The ids; [] when there are none.

find_idempotent abstractmethod async

find_idempotent(digest: str) -> str | None

Look up the upload a creation Idempotency-Key produced.

Parameters:

Name Type Description Default
digest str

SHA-256 hex of owner and key.

required

Returns:

Type Description
str | None

str | None: The upload id, or None.

remember_idempotent abstractmethod async

remember_idempotent(digest: str, upload_id: str) -> None

Record which upload a creation Idempotency-Key produced.

Parameters:

Name Type Description Default
digest str

SHA-256 hex of owner and key.

required
upload_id str

The upload it created.

required

list_uploads async

list_uploads() -> list[TusUpload]

Load every stored upload's record.

Returns:

Type Description
list[TusUpload]

list[TusUpload]: The records; [] when there are none. An id

list[TusUpload]

whose record vanished between the listing and the read is skipped.

purge_expired async

purge_expired(*, now: datetime | None = None) -> list[str]

Delete every incomplete upload past its expires_at.

Run it on a schedule (a TaskIQ periodic task, a cron). Each upload is re-read under the same per-upload lock the router writes under, and one with a request in progress is skipped. A complete upload is never purged, notified or not: its bytes belong to the service, which deletes them with :meth:delete when done.

Parameters:

Name Type Description Default
now datetime | None

The moment to compare with. Defaults to the current UTC time.

None

Returns:

Type Description
list[str]

list[str]: The ids deleted; [] when none had expired.

LocalTusStore

LocalTusStore(root: str | Path)

Bases: TusStore

Keep tus uploads in a directory of the server.

Layout under root: <id>.json holds the record (replaced atomically with os.replace), <id>.bin the bytes, written in place at the offset with fsync, and _idempotency/<digest> the upload id a creation key produced. File names come from the generated id only, never from Upload-Metadata, so a client name cannot escape root.

Every call runs its blocking I/O in asyncio.to_thread.

Attributes:

Name Type Description
root Path

The directory, created on first use.

Initialize the store.

Parameters:

Name Type Description Default
root str | Path

Directory to keep uploads in. Created with its parents when missing.

required

data_path

data_path(upload_id: str) -> Path

Path of an upload's bytes on disk.

After the upload completes this is the finished file, ready for the service to move or read.

Parameters:

Name Type Description Default
upload_id str

The upload id.

required

Returns:

Name Type Description
Path Path

root/<id>.bin.

Raises:

Type Description
ValueError

When upload_id is not a valid id.

create async

create(upload: TusUpload) -> None

Create the empty data file and the record.

Parameters:

Name Type Description Default
upload TusUpload

The new record.

required

Raises:

Type Description
ValueError

When upload.id is not a valid id.

load async

load(upload_id: str) -> TusUpload | None

Read a record from disk.

Parameters:

Name Type Description Default
upload_id str

The id.

required

Returns:

Type Description
TusUpload | None

TusUpload | None: The record, or None.

save async

save(upload: TusUpload) -> None

Replace a record on disk.

Parameters:

Name Type Description Default
upload TusUpload

The record.

required

Raises:

Type Description
ValueError

When upload.id is not a valid id.

write async

write(upload: TusUpload, data: BinaryIO, size: int) -> None

Write bytes at the offset, cutting anything a crashed write left past it.

Parameters:

Name Type Description Default
upload TusUpload

The upload.

required
data BinaryIO

The chunk stream.

required
size int

Bytes to copy.

required

finalize async

finalize(upload: TusUpload) -> None

Nothing to assemble: the data file already is the finished file.

Parameters:

Name Type Description Default
upload TusUpload

The complete upload.

required

stream async

stream(
    upload_id: str, *, chunk_size: int = TUS_STREAM_CHUNK_SIZE
) -> AsyncIterator[bytes]

Read the data file in chunks.

Parameters:

Name Type Description Default
upload_id str

The upload id.

required
chunk_size int

Bytes per chunk.

TUS_STREAM_CHUNK_SIZE

Yields:

Name Type Description
bytes AsyncIterator[bytes]

The next chunk.

delete async

delete(upload_id: str) -> None

Remove the data file, the record and the idempotency entry.

Parameters:

Name Type Description Default
upload_id str

The id.

required

list_ids async

list_ids() -> list[str]

List the ids that have a record file.

Returns:

Type Description
list[str]

list[str]: The ids, sorted; [] when the directory is empty or

list[str]

missing.

find_idempotent async

find_idempotent(digest: str) -> str | None

Read an idempotency entry.

Parameters:

Name Type Description Default
digest str

SHA-256 hex digest.

required

Returns:

Type Description
str | None

str | None: The upload id, or None.

remember_idempotent async

remember_idempotent(digest: str, upload_id: str) -> None

Write an idempotency entry atomically.

Parameters:

Name Type Description Default
digest str

SHA-256 hex digest.

required
upload_id str

The upload it created.

required

Raises:

Type Description
ValueError

When the digest or the id is malformed.

S3TusStore

S3TusStore(
    client: TusObjectClient,
    *,
    bucket: str | None = None,
    prefix: str = "tus/",
    min_chunk_size: int = DEFAULT_S3_TUS_MIN_CHUNK_SIZE,
)

Bases: TusStore

Keep tus uploads in an S3-compatible bucket.

See the module docstring for the layout and why chunks are separate objects. Install the [minio] extra for :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient.

Attributes:

Name Type Description
client TusObjectClient

The object-storage client.

bucket str | None

Bucket override; None uses the client's default bucket.

prefix str

Key prefix every object of this store lives under.

min_chunk_size int

Smallest non-final chunk the router accepts.

Initialize the store.

Parameters:

Name Type Description Default
client TusObjectClient

The object-storage client, e.g. an :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient.

required
bucket str | None

Bucket override.

None
prefix str

Key prefix, "tus/" by default. A trailing / is added when missing.

'tus/'
min_chunk_size int

Smallest PATCH body the router accepts, except the one that ends the upload — every chunk is an object, and this bounds how many one upload can create (length / min_chunk_size). 0 accepts any size.

DEFAULT_S3_TUS_MIN_CHUNK_SIZE

object_key

object_key(upload_id: str) -> str

Key of a finished upload's file, for the service to copy or serve.

Parameters:

Name Type Description Default
upload_id str

The upload id.

required

Returns:

Name Type Description
str str

<prefix><id>/data.

Raises:

Type Description
ValueError

When upload_id is not a valid id.

create async

create(upload: TusUpload) -> None

Write the record of a new upload.

Parameters:

Name Type Description Default
upload TusUpload

The record.

required

load async

load(upload_id: str) -> TusUpload | None

Read a record from the bucket.

Parameters:

Name Type Description Default
upload_id str

The id.

required

Returns:

Type Description
TusUpload | None

TusUpload | None: The record, or None.

save async

save(upload: TusUpload) -> None

Overwrite a record in the bucket.

Parameters:

Name Type Description Default
upload TusUpload

The record.

required

Raises:

Type Description
ValueError

When upload.id is not a valid id.

write async

write(upload: TusUpload, data: BinaryIO, size: int) -> None

Store a chunk as its own object, keyed by its offset.

A chunk an earlier attempt wrote at the same offset is replaced.

Parameters:

Name Type Description Default
upload TusUpload

The upload.

required
data BinaryIO

The chunk stream.

required
size int

Bytes in it.

required

finalize async

finalize(upload: TusUpload) -> None

Concatenate the chunks into <prefix><id>/data.

Only the chain of chunks that starts at 0 and ends at upload.length is read; a chunk outside it (an earlier attempt at an offset that a later write superseded) is skipped. The chunks stay until :meth:discard_parts, which the router calls after saving the complete record: a failure here, or before that save, leaves every chunk in place, and the retried last PATCH assembles again.

Parameters:

Name Type Description Default
upload TusUpload

The complete upload.

required

Raises:

Type Description
RuntimeError

When the stored chunks do not cover the upload.

discard_parts async

discard_parts(upload: TusUpload) -> None

Delete the chunk objects of a complete upload.

Runs after the router saved the complete record, so a failure here leaves stray chunks — removed by :meth:delete — but never an upload stuck before completion.

Parameters:

Name Type Description Default
upload TusUpload

The complete upload.

required

stream async

stream(
    upload_id: str, *, chunk_size: int = TUS_STREAM_CHUNK_SIZE
) -> AsyncIterator[bytes]

Read a finished upload's file from the bucket.

Parameters:

Name Type Description Default
upload_id str

The upload id.

required
chunk_size int

Bytes per chunk.

TUS_STREAM_CHUNK_SIZE

Yields:

Name Type Description
bytes AsyncIterator[bytes]

The next chunk.

delete async

delete(upload_id: str) -> None

Remove every object of the upload and its idempotency entry.

Parameters:

Name Type Description Default
upload_id str

The id.

required

list_ids async

list_ids() -> list[str]

List the ids that have a record object.

Returns:

Type Description
list[str]

list[str]: The ids, sorted; [] when there are none.

find_idempotent async

find_idempotent(digest: str) -> str | None

Read an idempotency entry from the bucket.

Parameters:

Name Type Description Default
digest str

SHA-256 hex digest.

required

Returns:

Type Description
str | None

str | None: The upload id, or None.

remember_idempotent async

remember_idempotent(digest: str, upload_id: str) -> None

Write an idempotency entry to the bucket.

Parameters:

Name Type Description Default
digest str

SHA-256 hex digest.

required
upload_id str

The upload it created.

required

Raises:

Type Description
ValueError

When the digest or the id is malformed.

TusObjectClient

Bases: Protocol

The object-storage calls :class:S3TusStore makes.

:class:~tempest_fastapi_sdk.storage.AsyncMinIOClient, :class:~tempest_fastapi_sdk.storage.BucketRoutedMinIOClient, :class:~tempest_fastapi_sdk.storage.LocalObjectStorageClient and :class:~tempest_fastapi_sdk.testing.fakes.FakeObjectStorageClient all satisfy it. A missing object must raise :class:FileNotFoundError or an error whose code is "NoSuchKey".

put_object async

put_object(
    key: str,
    data: bytes | BinaryIO,
    /,
    *,
    bucket: str | None = None,
    content_type: str = "application/octet-stream",
    length: int | None = None,
) -> str

Store one object.

Parameters:

Name Type Description Default
key str

Object key.

required
data bytes | BinaryIO

Payload.

required
bucket str | None

Target bucket.

None
content_type str

MIME type.

'application/octet-stream'
length int | None

Payload size, required for a stream.

None

Returns:

Name Type Description
str str

The ETag.

stream_object async

stream_object(
    key: str, /, *, bucket: str | None = None, chunk_size: int = 64 * 1024
) -> AsyncIterator[bytes]

Read one object in chunks.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Source bucket.

None
chunk_size int

Bytes per chunk.

64 * 1024

Returns:

Type Description
AsyncIterator[bytes]

AsyncIterator[bytes]: The payload.

list_objects async

list_objects(prefix: str = '', /, *, bucket: str | None = None) -> list[str]

List keys under a prefix, recursively.

Parameters:

Name Type Description Default
prefix str

Key prefix.

''
bucket str | None

Source bucket.

None

Returns:

Type Description
list[str]

list[str]: The keys.

remove_object async

remove_object(key: str, /, *, bucket: str | None = None) -> None

Delete one object; absent is not an error.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Target bucket.

None

TusUpload dataclass

TusUpload(
    id: str,
    length: int,
    offset: int = 0,
    metadata: dict[str, str] = dict(),
    owner: str | None = None,
    created_at: datetime = (lambda: now(UTC))(),
    expires_at: datetime | None = None,
    idempotency_digest: str | None = None,
    notified: bool = False,
)

One resumable upload, as a tus store keeps it.

The record is the authority on how many bytes are stored: a chunk is written first and the record saved after, so a crash between the two leaves offset at the last confirmed byte and the next PATCH overwrites whatever was half-written past it.

Attributes:

Name Type Description
id str

Unguessable id, the last segment of the upload URL.

length int

Total size the client declared in Upload-Length.

offset int

Bytes stored so far.

metadata dict[str, str]

Decoded Upload-Metadata pairs, as the client sent them. Read the name through :attr:filename, never from here, before using it in a path.

owner str | None

str() of what current_user_id resolved when the upload was created; None for an anonymous upload.

created_at datetime

Creation time, UTC.

expires_at datetime | None

When an incomplete upload stops being resumable. Renewed by every accepted PATCH; None when the router has no expiration.

idempotency_digest str | None

SHA-256 of owner and Idempotency-Key, when the creation carried one.

notified bool

Whether on_complete returned without raising. A complete upload with notified false is one the service still has to handle.

completed property

completed: bool

Whether every declared byte is stored.

Returns:

Name Type Description
bool bool

offset == length.

filename property

filename: str | None

The client's file name, sanitized for use in a path or header.

Read from the filename metadata key, then name, through :func:sanitize_upload_filename.

Returns:

Type Description
str | None

str | None: The safe name, or None when absent or unusable.

is_expired

is_expired(now: datetime | None = None) -> bool

Whether this upload is incomplete and past expires_at.

A complete upload never expires: its bytes are the service's now.

Parameters:

Name Type Description Default
now datetime | None

The moment to compare with. Defaults to the current UTC time.

None

Returns:

Name Type Description
bool bool

True when the upload can no longer be resumed.

to_json

to_json() -> str

Serialize the record for a store.

Returns:

Name Type Description
str str

A JSON object.

from_json classmethod

from_json(raw: str | bytes) -> TusUpload

Rebuild a record written by :meth:to_json.

Parameters:

Name Type Description Default
raw str | bytes

The stored JSON.

required

Returns:

Name Type Description
TusUpload TusUpload

The record.

PutObjectItem dataclass

PutObjectItem(
    key: str,
    data: bytes | BinaryIO,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
    length: int | None = None,
    part_size: int = 10 * 1024 * 1024,
)

One object to upload in an :meth:AsyncMinIOClient.put_objects batch.

Mirrors the per-object arguments of :meth:AsyncMinIOClient.put_object so a single batch can carry heterogeneous payloads — different content types, metadata, or unknown-length streams.

Attributes:

Name Type Description
key str

Destination object key.

data bytes | BinaryIO

Payload. bytes is wrapped in a BytesIO; file-like objects are forwarded as-is and require length.

content_type str

MIME type. "application/octet-stream" by default.

metadata dict[str, str] | None

User metadata stored under the x-amz-meta- namespace by minio; pass plain names.

length int | None

Payload size in bytes. Required for file-like data; pass -1 for unknown-length streams to trigger multipart upload. Computed automatically for bytes.

part_size int

Multipart chunk size in bytes. At least 5 MiB. Default 10 MiB.

TUS_CORS_ALLOW_HEADERS module-attribute

TUS_CORS_ALLOW_HEADERS: tuple[str, ...] = (
    "Authorization",
    "Content-Type",
    "Idempotency-Key",
    "Tus-Resumable",
    "Upload-Length",
    "Upload-Metadata",
    "Upload-Offset",
    "X-CSRF-Token",
)

Request headers createResumableUpload sends.

Pass to CORSMiddleware(allow_headers=...).

TUS_CORS_EXPOSE_HEADERS module-attribute

TUS_CORS_EXPOSE_HEADERS: tuple[str, ...] = (
    "Location",
    "Tus-Max-Size",
    "Tus-Resumable",
    "Tus-Version",
    "Upload-Expires",
    "Upload-Length",
    "Upload-Metadata",
    "Upload-Offset",
)

Response headers a cross-origin client must be allowed to read.

Pass to CORSMiddleware(expose_headers=...). Without Location and Upload-Offset there, a browser on another origin gets null from getResponseHeader and the client cannot find the upload it created.