Storage / Supabase

Storage Menager

Documentation of the BetterAI integration with Supabase Storage: how to configure buckets and upload, read, list and delete files, including together with a table record.

On this page

    #Overview

    File management in Supabase buckets goes through the same integration as tables, in src/database/supabase_integration/. Project flows do not use the supabase SDK directly: they ask for the integration and use sb.storage.

    • get_supabase().storage: the file class (FileStore) with upload, download, download_to, signed_url, public_url, exists, list, delete and delete_prefix.
    • BytesSource, PathSource, StreamSource: the three ways to hand over the content to upload.
    • UploadOptions: bucket, folder, explicit path, collision policy, content type and metadata.
    • StorageRepository (src/storage/storage_repository.py): project wrapper to upload images and get the public URL, used by image generation.

    All operations validate the input before going over the network (allowed bucket, size, extension, declared type and real content) and raise domain exceptions instead of returning None.

    #Upload Flow

    1. Bucket: UploadOptions.bucket (or SBX_BUCKET_DEFAULT) is resolved and checked against the bucket allowlist.
    2. Validation: size (empty and above-ceiling files are rejected), extension, declared type and real content (magic bytes) must agree.
    3. Path: explicit path, or generated as <folder>/YYYY/MM/<uuid><ext>.
    4. Transfer: standard upload or, above SBX_STORAGE_RESUMABLE_THRESHOLD_BYTES (6 MiB), resumable upload (TUS), read as a stream.
    5. Collision: if the path already exists, the CollisionPolicy applies (REJECT, VERSION or OVERWRITE).
    6. Result: a StoredFile with bucket, path, size, content_type, original_name, upload_mode and metadata.

    #Configuration

    Configuration comes from the SBX_* environment variables. The ones used by files are:

    VariableDescription
    SBX_URLhttps URL of the Supabase project (required)
    SBX_SECRET_KEYBackend secret key (required; never in the frontend)
    SBX_BUCKET_DEFAULTDefault bucket (e.g. images)
    SBX_BUCKETS_ALLOWLISTAllowed buckets, comma-separated (required in prod)
    SBX_BUCKETS_PUBLICPublic buckets; public_url only works for these
    SBX_STORAGE_MAX_FILE_BYTESMaximum file size (50 MiB)
    SBX_STORAGE_ALLOWED_MIMEAllowed MIME types; accepts image/*; empty accepts any
    SBX_STORAGE_SIGNED_URL_TTL_SECONDSDefault signed URL lifetime (300)
    SBX_STORAGE_SIGNED_URL_MAX_TTL_SECONDSSigned URL lifetime ceiling (3600)
    SBX_STORAGE_RESUMABLE_THRESHOLD_BYTESSize above which the upload becomes resumable (6 MiB)
    SBX_STORAGE_MEMORY_CAP_BYTESMemory ceiling for BytesSource and download (32 MiB)
    SBX_STORAGE_UPLOAD_TIMEOUT_SECONDSUpload timeout in seconds (120)
    SBX_STORAGE_MAX_CONCURRENT_TRANSFERSConcurrent transfers (4)

    Public bucket. To generate the public URL of images, the bucket must be in SBX_BUCKETS_PUBLIC (for example SBX_BUCKET_DEFAULT=images, SBX_BUCKETS_PUBLIC=images, SBX_BUCKETS_ALLOWLIST=images). In homol and prod the .env file is forbidden. The full list is in src/database/supabase_integration/.env.example.

    #Upload

    from src.database.supabase_provider import get_supabase
    from src.database.supabase_integration import BytesSource, PathSource, StreamSource, UploadOptions, CollisionPolicy
    
    storage = get_supabase().storage
    
    st = storage.upload(
        BytesSource(b"content", filename="note.txt", content_type="text/plain"),
        UploadOptions(folder="docs"),  # Generated path: docs/YYYY/MM/<uuid>.txt
    )
    print(st.bucket, st.path, st.size, st.upload_mode, st.content_type, st.original_name)
    
    big = storage.upload(
        PathSource("video.mp4", content_type="video/mp4"),  # Read as a stream; above 6 MiB it becomes resumable (TUS)
        UploadOptions(folder="videos"),
    )
    
    with open("report.pdf", "rb") as f:
        storage.upload(StreamSource(f, size=None, filename="report.pdf", content_type="application/pdf"))  # Stream, for example FastAPI's UploadFile
    
    storage.upload(
        BytesSource(b"v2", filename="a.txt", content_type="text/plain"),
        UploadOptions(path=st.path, collision=CollisionPolicy.VERSION),  # Collision: writes to a new path (-v2)
    )

    #Data sources

    ClassFieldsNotes
    BytesSourcedata, filename, content_typeIn memory; above SBX_STORAGE_MEMORY_CAP_BYTES it raises ValidationError (use PathSource or StreamSource).
    PathSourcepath, filename, content_typeReads from disk as a stream; filename defaults to the file name; a missing file raises ValidationError.
    StreamSourcestream, size, filename, content_type, restartableWith size and a seekable stream, it is re-read on retry; without size it is copied to a temporary file (bytes are counted and the ceiling is checked).

    #UploadOptions

    FieldEffect
    bucketNone uses SBX_BUCKET_DEFAULT; must be in the allowlist.
    folderLogical subfolder (validated). Generated path: <folder>/YYYY/MM/<uuid><ext>.
    pathExplicit path, which replaces automatic naming and is always validated.
    collisionREJECT (default: FileAlreadyExistsError), VERSION (writes to name-v2.ext, -v3...) or OVERWRITE (overwrites, explicit only).
    content_typeDeclared MIME type, checked against the extension and the content.
    metadatastr to str metadata (up to 50 entries); the integration adds original_name.
    cache_control_secondsNone uses SBX_STORAGE_CACHE_CONTROL_SECONDS.
    correlation_idIdentifier to tie together the operation's logs.

    The content type is chosen as follows: detected content (if specific), then the declared one, then the extension, finally application/octet-stream. Extension, declared type and content must agree, otherwise ValidationError is raised. In public buckets, active types (.html, .svg, .js, executables) are rejected.

    Object paths only accept ASCII [A-Za-z0-9._-], with no accents or spaces, no segment starting with a dot and up to 8 levels. In the generated path, the user's original name goes in as metadata (original_name), not in the path.

    #Image Upload in the Project

    Image generation writes files through StorageRepository, which uses the integration: it builds the path <base_path>/<file_name>, uploads the bytes and returns the public URL. If the upload fails, it raises RuntimeError with the original cause in __cause__.

    from src.storage.storage_repository import StorageRepository
    
    repository = StorageRepository(base_path="image_generations", bucket_name="images")
    
    url = repository.upload_to_supabase(file_name="example_image.png", byte_data=image_bytes)
    print(url)  # Public URL of the file in the bucket

    #Read

    data = storage.download(st.path)  # bytes, limited by the memory ceiling (32 MiB)
    storage.download_to(big.path, "out/video.mp4")  # Streams straight to disk, for large files
    url = storage.signed_url(st.path, ttl_seconds=300)  # Signed URL; ceiling 3600 s, above that ValidationError
    pub = storage.public_url(st.path, bucket="images")  # Only for a bucket in SBX_BUCKETS_PUBLIC
    found = storage.exists(st.path)
    page = storage.list(prefix="docs", limit=100)  # Page[ObjectInfo]
    for o in page.items:
        print(o.path, o.size, o.content_type, o.updated_at, o.is_folder)

    exists also returns False on 401 and 403 (an SDK limitation): a permission problem can look like "does not exist".

    #Deletion

    rep = storage.delete([st.path, big.path])  # Idempotent; report per path
    print(rep.requested, rep.removed, rep.failed)  # failed: {path: reason}
    storage.delete_prefix("docs/2026/11")  # DESTRUCTIVE: deletes everything under the prefix, recursively

    Partial failures in delete do not raise: check rep.failed. delete_prefix is destructive and recursive (maximum depth 16); an empty prefix is forbidden.

    #Method Table

    MethodReturnShort Description
    upload(source, options=None)StoredFileValidates and uploads the file; upload_mode is standard or resumable.
    download(path, bucket=None)bytesDownloads into memory; rejects an object above the ceiling (use download_to).
    download_to(path, destination, bucket=None)PathStreams the download to disk and creates parent folders.
    signed_url(path, bucket=None, ttl_seconds=None)strTemporary URL; it is never logged.
    public_url(path, bucket=None)strPublic URL, only for a bucket in SBX_BUCKETS_PUBLIC; built locally, without network.
    exists(path, bucket=None)boolTells whether the object exists.
    list(prefix="", bucket=None, limit=None, offset=0)Page[ObjectInfo]Lists objects; folders come with is_folder=True.
    delete(paths, bucket=None)DeleteReportDeletes in batches; idempotent; failures go to failed.
    delete_prefix(prefix, bucket=None)DeleteReportDeletes everything under the prefix, recursively.

    #File and Record Together

    When the file must be written together with a table record, use the facade's combined operations. They follow a fixed order and compensate on failure: if the record fails after the upload, the file is deleted. Tables are described on the Supabase Database page.

    sb = get_supabase()
    
    r = sb.save_file_with_record(
        "sbx_test_items",
        BytesSource(b"content", filename="contract.txt", content_type="text/plain"),
        lambda f: {"name": "contract", "bucket": f.bucket, "path": f.path},  # Builds the record from the stored file
        UploadOptions(folder="contracts"),
    )
    r.raise_if_failed()  # Raises the same original error, if there was a failure
    print(r.status.value, r.record["id"])  # completa, parcial or falhou
    
    sb.replace_file_in_record(
        "sbx_test_items", r.record["id"],
        BytesSource(b"v2", filename="contract.txt", content_type="text/plain"),
        lambda f: {"bucket": f.bucket, "path": f.path},
        old_ref=(r.stored_file.bucket, r.stored_file.path),  # The old file is deleted last
    )
    
    sb.delete_record_and_file("sbx_test_items", r.record["id"], (r.stored_file.bucket, r.stored_file.path))  # Record first, file after
    statusMeaningorphan_possible
    completaAll steps completed.False
    falhouNothing was left behind (failure before writing, or successful compensation).False
    parcialSomething was left: an orphan file or an old file not deleted. The log carries orfao_possivel=true with bucket and path.True

    raise_if_failed() also raises on the parcial status, even when the record was updated. Read r.status before deciding.

    #Error Handling

    ExceptionWhen
    ValidationErrorBucket outside the allowlist, empty file, mismatched or disallowed type, invalid path, signed URL above the ceiling, non-public bucket in public_url.
    FileTooLargeErrorFile above SBX_STORAGE_MAX_FILE_BYTES or a 413 response from Storage.
    FileAlreadyExistsErrorThe path already exists with CollisionPolicy.REJECT.
    FileNotFoundInStorageErrorObject does not exist (Storage also uses 404 for "no permission").
    PermissionDeniedError, AuthenticationErrorThe bucket policy denied access; invalid key.
    UploadError, DownloadErrorUnclassified storage failure.
    OperationTimeoutError, ServiceUnavailableError, RateLimitErrorTransient failures (retryable=True).
    try:
        storage.upload(BytesSource(data, filename="a.png"), UploadOptions(path="images/a.png"))
    except FileAlreadyExistsError:
        ...  # The path already exists
    except SupabaseIntegrationError as e:  # Any integration error
        print(e.retryable, e.outcome_unknown, e.correlation_id)

    #Architecture and Insights

    • Resumable upload: above SBX_STORAGE_RESUMABLE_THRESHOLD_BYTES the transfer uses the TUS protocol in chunks, without loading the whole file into memory.
    • Safe retry: only OVERWRITE is retried by the executor. With REJECT and VERSION a timeout becomes outcome_unknown=True and the object may have been written: check with exists.
    • Safe names: the generated path never uses the user's name, which avoids collisions and invalid characters.
    • Without blocking the event loop: in FastAPI use create_async_integration; await asb.upload(...) runs in a thread.
    • Protected secrets: the SBX_SECRET_KEY key and signed URLs never appear in logs or error messages.

    Source: src/database/supabase_integration/storage/

    Esc
    ↑↓navigate Enteropen