Ir para o conteúdo

tempest_fastapi_sdk.admin.storage

A fonte de dados do navegador de storage do admin: um bucket de object store.

« Admin, dados e API


storage

The storage browser's data source: one bucket of an object store.

The admin already wrote to object storage (upload_fields=) and the CLI already read it (tempest storage ls), but an operator who needed to see what a bucket holds, look at one file or remove a stray upload had no screen for it. :class:StorageBrowserService is that screen's service: it lists a "folder", describes one object, decides how the object can be previewed, and carries out the writes — upload, replace, rename, in-place text edit and delete — with the limits checked here rather than in the template.

It talks to any store with the five calls of :class:AdminStorageClient, which :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient and :class:~tempest_fastapi_sdk.storage.LocalObjectStorageClient both implement. Folders are not objects on either: they are the /-separated prefixes of the keys, so an empty folder does not exist and a folder appears as soon as one key is written under it.

What the browser deliberately does not do is serve a stored file as a page of the admin's origin. Previews go through :func:~tempest_fastapi_sdk.storage.object_download_response, which grants inline only to :data:~tempest_fastapi_sdk.utils.INLINE_SAFE_MEDIA_TYPES and stamps nosniff plus a sandboxing CSP on every response. Text-like types outside that list — HTML, SVG, JSON — are previewed as escaped source in the page, never rendered.

DEFAULT_STORAGE_PAGE_SIZE module-attribute

DEFAULT_STORAGE_PAGE_SIZE: Final[int] = 100

Entries (folders and files) shown per page of a folder listing.

DEFAULT_STORAGE_MAX_UPLOAD_BYTES module-attribute

DEFAULT_STORAGE_MAX_UPLOAD_BYTES: Final[int] = 25 * 1024 * 1024

Largest file the browser accepts in one upload or replace: 25 MiB.

The same figure as :data:~tempest_fastapi_sdk.storage.DEFAULT_LOCAL_MAX_UPLOAD_BYTES, so a store and its admin screen refuse at the same size by default.

DEFAULT_STORAGE_MAX_TEXT_BYTES module-attribute

DEFAULT_STORAGE_MAX_TEXT_BYTES: Final[int] = 256 * 1024

Largest text object previewed in the page and editable in place: 256 KiB.

A bigger file is still downloadable and replaceable; it is only kept out of a <textarea>, where a multi-megabyte log would make the page unusable.

STORAGE_KEY_MAX_BYTES module-attribute

STORAGE_KEY_MAX_BYTES: Final[int] = 1024

Longest key accepted, in UTF-8 bytes — the S3 object-key limit.

STORAGE_SPOOL_BYTES module-attribute

STORAGE_SPOOL_BYTES: Final[int] = 8 * 1024 * 1024

Bytes an upload or copy keeps in memory before spilling to a temp file.

STORAGE_STAT_CONCURRENCY module-attribute

STORAGE_STAT_CONCURRENCY: Final[int] = 8

Concurrent stat_object calls made while describing one listing page.

TEXT_MEDIA_TYPES module-attribute

TEXT_MEDIA_TYPES: Final[frozenset[str]] = frozenset(
    {
        "application/csv",
        "application/javascript",
        "application/json",
        "application/ld+json",
        "application/sql",
        "application/toml",
        "application/x-ndjson",
        "application/x-sh",
        "application/x-yaml",
        "application/xml",
        "application/yaml",
        "image/svg+xml",
    }
)

Types outside text/* that are text and preview as source.

image/svg+xml is here on purpose: it is never served inline (it can carry <script>), so the only safe preview is its escaped source.

StoragePreviewEnum

Bases: BaseStrEnum

How the object page previews a stored object.

IMAGE, VIDEO, AUDIO and PDF are rendered by the browser from the raw route, and only for types in :data:~tempest_fastapi_sdk.utils.INLINE_SAFE_MEDIA_TYPES. TEXT is the escaped source in the page. NONE offers the download only.

StorageBrowserError

Bases: ValueError

A browser operation refused for a reason the operator can fix.

The message is shown on the page as is, so it names the key and the limit rather than the exception type.

StorageObjectMissingError

Bases: StorageBrowserError

The object the operation names is not stored (any more).

AdminStorageClient

Bases: Protocol

The object-store calls :class:StorageBrowserService makes.

:class:~tempest_fastapi_sdk.storage.AsyncMinIOClient and :class:~tempest_fastapi_sdk.storage.LocalObjectStorageClient satisfy it; it is also a :class:~tempest_fastapi_sdk.storage.DownloadableStore, which is what the raw route streams from. Parameter names are the SDK clients' own.

list_objects async

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

List object keys under prefix.

Parameters:

Name Type Description Default
prefix str

Prefix filter.

''
bucket str | None

Source bucket.

None
recursive bool

False lists one level, folders ending in /.

True

Returns:

Type Description
list[str]

list[str]: The matching keys.

stat_object async

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

Describe an 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, content type, ETag, metadata.

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]

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

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Source bucket.

None
chunk_size int

Bytes per chunk.

64 * 1024
offset int

First byte to read.

0
length int | None

Bytes to read; None reads to the end.

None

Returns:

Type Description
AsyncIterator[bytes]

AsyncIterator[bytes]: The chunks, in order.

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.

Parameters:

Name Type Description Default
key str

Object key.

required
data bytes | BinaryIO

The payload.

required
bucket str | None

Target bucket.

None
content_type str

MIME type stored with the object.

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

User metadata.

None
length int | None

Payload size when data is a stream.

None

Returns:

Name Type Description
str str

The object's ETag.

remove_object async

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

Delete one object; a missing key is not an error.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Target bucket.

None

StorageEntry dataclass

StorageEntry(
    key: str,
    name: str,
    is_folder: bool,
    size: int | None = None,
    content_type: str | None = None,
    last_modified: datetime | None = None,
)

One row of a folder listing.

Attributes:

Name Type Description
key str

Full key; a folder's ends in /.

name str

Last segment, as the row shows it.

is_folder bool

True for a prefix with keys under it.

size int | None

Bytes; None for a folder or a file whose stat failed.

content_type str | None

Stored MIME type.

last_modified datetime | None

Last write, UTC.

StorageCrumb dataclass

StorageCrumb(name: str, prefix: str)

One link of the breadcrumb above a listing.

Attributes:

Name Type Description
name str

Segment shown; the bucket name for the root.

prefix str

Prefix the link opens; "" for the root.

StorageListing dataclass

StorageListing(
    prefix: str,
    entries: list[StorageEntry] = list(),
    crumbs: list[StorageCrumb] = list(),
    page: int = 1,
    pages: int = 1,
    total: int = 0,
)

One page of one folder.

Attributes:

Name Type Description
prefix str

The folder, "" or ending in /.

entries list[StorageEntry]

Folders first, then files, each sorted by name.

crumbs list[StorageCrumb]

Root to the current folder.

page int

1-based page shown.

pages int

Pages in the folder; at least 1.

total int

Entries in the folder, across pages.

StorageObjectView dataclass

StorageObjectView(
    key: str,
    name: str,
    folder: str,
    size: int,
    content_type: str,
    etag: str | None,
    last_modified: datetime | None,
    metadata: dict[str, str],
    preview: StoragePreviewEnum,
    text: str | None,
    editable: bool,
    crumbs: list[StorageCrumb] = list(),
)

What the object page shows about one stored object.

Attributes:

Name Type Description
key str

Object key.

name str

Last segment of the key.

folder str

Prefix holding the object, "" or ending in /.

size int

Bytes.

content_type str

Stored MIME type, application/octet-stream when none was recorded.

etag str | None

ETag; sent back by the text editor to detect a concurrent write.

last_modified datetime | None

Last write, UTC.

metadata dict[str, str]

User metadata.

preview StoragePreviewEnum

How the page previews it.

text str | None

The decoded content for a TEXT preview that fits :attr:StorageBrowserService.max_text_bytes.

editable bool

Whether the in-place text editor is offered.

crumbs list[StorageCrumb]

Root to the holding folder.

StorageBrowserService

StorageBrowserService(
    client: AdminStorageClient,
    *,
    bucket: str | None = None,
    label: str | None = None,
    read_only: bool = False,
    page_size: int = DEFAULT_STORAGE_PAGE_SIZE,
    max_upload_bytes: int = DEFAULT_STORAGE_MAX_UPLOAD_BYTES,
    max_text_bytes: int = DEFAULT_STORAGE_MAX_TEXT_BYTES,
)

List, preview and edit the objects of one bucket from the admin.

Example:

>>> from tempest_fastapi_sdk.admin import StorageBrowserService
>>> from tempest_fastapi_sdk.storage import LocalObjectStorageClient
>>> store = LocalObjectStorageClient(
...     "/var/lib/app/storage",
...     public_url="https://api.example.com",
...     signing_secret=settings.JWT_SECRET,
... )
>>> browser = StorageBrowserService(store)
>>> make_admin_router(site, ..., storage=browser)

Attributes:

Name Type Description
client AdminStorageClient

The store.

bucket str | None

Bucket browsed; None is the client's default.

label str

Name of the root in the breadcrumb.

read_only bool

True hides and refuses every write.

page_size int

Entries per listing page.

max_upload_bytes int

Largest upload or replace accepted.

max_text_bytes int

Largest text previewed and edited in place.

Keep the store and the limits the screen enforces.

Parameters:

Name Type Description Default
client AdminStorageClient

The store to browse.

required
bucket str | None

Bucket to browse; None uses the client's default bucket.

None
label str | None

Name of the root in the breadcrumb; defaults to bucket, or "storage".

None
read_only bool

True keeps listing, preview and download and refuses upload, replace, rename, edit and delete. Default False.

False
page_size int

Entries per listing page. Default :data:DEFAULT_STORAGE_PAGE_SIZE.

DEFAULT_STORAGE_PAGE_SIZE
max_upload_bytes int

Largest upload or replace. Default :data:DEFAULT_STORAGE_MAX_UPLOAD_BYTES.

DEFAULT_STORAGE_MAX_UPLOAD_BYTES
max_text_bytes int

Largest text object previewed in the page and edited in place. Default :data:DEFAULT_STORAGE_MAX_TEXT_BYTES.

DEFAULT_STORAGE_MAX_TEXT_BYTES

Raises:

Type Description
ValueError

When a size or the page size is not positive.

exists async

exists(key: str) -> bool

Tell whether key is stored.

Parameters:

Name Type Description Default
key str

Object key.

required

Returns:

Name Type Description
bool bool

True when stat_object finds it.

browse async

browse(prefix: str = '', *, page: int = 1) -> StorageListing

List one folder, folders first, one page at a time.

Both a one-level listing (folders ending in /) and a recursive one are folded into the folder's direct children, so a store that ignores recursive=False still lists correctly.

Parameters:

Name Type Description Default
prefix str

The folder; "" for the root.

''
page int

1-based page; clamped into range.

1

Returns:

Name Type Description
StorageListing StorageListing

The page, its files stat-ed for size, type and

StorageListing

date. An empty or unknown folder is an empty listing.

Raises:

Type Description
StorageBrowserError

When prefix is not a valid folder.

describe async

describe(key: str) -> StorageObjectView

Describe one object for its page, text content included.

Parameters:

Name Type Description Default
key str

Object key.

required

Returns:

Name Type Description
StorageObjectView StorageObjectView

Metadata, preview kind and, for a text object

within StorageObjectView

attr:max_text_bytes that decodes as UTF-8, its content.

StorageObjectView

Text that does not decode is downgraded to NONE.

Raises:

Type Description
StorageBrowserError

When the key is invalid.

StorageObjectMissingError

When the object is not stored.

upload async

upload(
    folder: str,
    name: str,
    read: Callable[[int], Awaitable[bytes]],
    *,
    content_type: str | None = None,
    overwrite: bool = False,
) -> str

Store a new file under folder.

Parameters:

Name Type Description Default
folder str

Target folder; "" for the root.

required
name str

File name, or a relative path ("a/b.txt") that creates the folders it names.

required
read Callable[[int], Awaitable[bytes]]

Reads the upload in chunks — UploadFile.read.

required
content_type str | None

Type the browser declared.

None
overwrite bool

Replace an object already stored under the key. Default False.

False

Returns:

Name Type Description
str str

The key written.

Raises:

Type Description
StorageBrowserError

When the browser is read-only, the key is invalid, the key is taken and overwrite is off, or the file is over :attr:max_upload_bytes.

replace async

replace(
    key: str,
    read: Callable[[int], Awaitable[bytes]],
    *,
    content_type: str | None = None,
    filename: str | None = None,
) -> None

Overwrite an existing object's content, keeping its key and metadata.

Parameters:

Name Type Description Default
key str

Object key.

required
read Callable[[int], Awaitable[bytes]]

Reads the new content in chunks.

required
content_type str | None

Type the browser declared; when generic, guessed from filename, then the key.

None
filename str | None

The uploaded file's own name.

None

Raises:

Type Description
StorageBrowserError

When the browser is read-only, the key is invalid or the file is over :attr:max_upload_bytes.

StorageObjectMissingError

When the object is not stored.

save_text async

save_text(key: str, text: str, *, expected_etag: str | None) -> None

Write edited text back, refusing when someone wrote in between.

Browsers submit a <textarea> with \r\n line ends; they are written back as \n when the original held no \r\n, so saving a Unix file unchanged does not rewrite every line.

Parameters:

Name Type Description Default
key str

Object key.

required
text str

The new content.

required
expected_etag str | None

ETag the editor was opened at; None skips the check.

required

Raises:

Type Description
StorageBrowserError

When the browser is read-only, the key is invalid, the object is not editable text, the content is over :attr:max_text_bytes, or its ETag changed since the editor opened.

StorageObjectMissingError

When the object is not stored.

rename async

rename(key: str, new_key: str) -> str

Move an object to another key, folder included.

Object stores have no rename: this copies the bytes, type and metadata to new_key, then deletes key. The copy streams through this process, so it costs one download and one upload of the object.

Parameters:

Name Type Description Default
key str

Current key.

required
new_key str

Target key; a leading / is ignored.

required

Returns:

Name Type Description
str str

The new key.

Raises:

Type Description
StorageBrowserError

When the browser is read-only, a key is invalid, the keys are equal, or new_key is taken.

StorageObjectMissingError

When the object is not stored.

delete async

delete(key: str) -> None

Delete one object.

Parameters:

Name Type Description Default
key str

Object key.

required

Raises:

Type Description
StorageBrowserError

When the browser is read-only or the key is invalid.

StorageObjectMissingError

When the object is not stored — reported so a double submit does not claim a second delete.

check_storage_key

check_storage_key(key: str) -> str

Validate a key typed or derived in the browser.

S3 accepts almost any byte string as a key; the browser does not, because a key with an empty, . or .. segment cannot be shown as a folder path, means something else on :class:~tempest_fastapi_sdk.storage.LocalObjectStorageClient, and is never what an operator meant to type.

Parameters:

Name Type Description Default
key str

The candidate key.

required

Returns:

Name Type Description
str str

key unchanged.

Raises:

Type Description
StorageBrowserError

When the key is empty, longer than :data:STORAGE_KEY_MAX_BYTES, starts or ends with /, holds an empty, . or .. segment, a backslash or a control character.

normalize_storage_prefix

normalize_storage_prefix(prefix: str) -> str

Return prefix as a folder: "" or a valid path ending in /.

Parameters:

Name Type Description Default
prefix str

The folder from the query string, with or without the trailing /.

required

Returns:

Name Type Description
str str

"" for the root, otherwise the folder with one trailing

str

/.

Raises:

Type Description
StorageBrowserError

When the folder is not a valid key path.

guess_storage_content_type

guess_storage_content_type(name: str, declared: str | None = None) -> str

Pick the content type an uploaded file is stored with.

The browser's declared type wins when it is specific; a missing or generic application/octet-stream falls back to the extension.

Parameters:

Name Type Description Default
name str

The file name or key.

required
declared str | None

The type the browser sent with the upload.

None

Returns:

Name Type Description
str str

The type to store; application/octet-stream when nothing

str

better is known.

storage_preview_for

storage_preview_for(content_type: str | None, key: str) -> StoragePreviewEnum

Decide how an object is previewed.

Parameters:

Name Type Description Default
content_type str | None

Stored MIME type.

required
key str

Object key, whose extension is consulted when the stored type is missing or application/octet-stream.

required

Returns:

Name Type Description
StoragePreviewEnum StoragePreviewEnum

A rendered preview only for a type the raw route

StoragePreviewEnum

will serve inline; TEXT for textual types; otherwise

StoragePreviewEnum

NONE.