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) withupload,download,download_to,signed_url,public_url,exists,list,deleteanddelete_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
- Bucket:
UploadOptions.bucket(orSBX_BUCKET_DEFAULT) is resolved and checked against the bucket allowlist. - Validation: size (empty and above-ceiling files are rejected), extension, declared type and real content (magic bytes) must agree.
- Path: explicit
path, or generated as<folder>/YYYY/MM/<uuid><ext>. - Transfer: standard upload or, above
SBX_STORAGE_RESUMABLE_THRESHOLD_BYTES(6 MiB), resumable upload (TUS), read as a stream. - Collision: if the path already exists, the
CollisionPolicyapplies (REJECT,VERSIONorOVERWRITE). - Result: a
StoredFilewithbucket,path,size,content_type,original_name,upload_modeandmetadata.
#Configuration
Configuration comes from the SBX_* environment variables. The ones used by files are:
| Variable | Description |
|---|---|
SBX_URL | https URL of the Supabase project (required) |
SBX_SECRET_KEY | Backend secret key (required; never in the frontend) |
SBX_BUCKET_DEFAULT | Default bucket (e.g. images) |
SBX_BUCKETS_ALLOWLIST | Allowed buckets, comma-separated (required in prod) |
SBX_BUCKETS_PUBLIC | Public buckets; public_url only works for these |
SBX_STORAGE_MAX_FILE_BYTES | Maximum file size (50 MiB) |
SBX_STORAGE_ALLOWED_MIME | Allowed MIME types; accepts image/*; empty accepts any |
SBX_STORAGE_SIGNED_URL_TTL_SECONDS | Default signed URL lifetime (300) |
SBX_STORAGE_SIGNED_URL_MAX_TTL_SECONDS | Signed URL lifetime ceiling (3600) |
SBX_STORAGE_RESUMABLE_THRESHOLD_BYTES | Size above which the upload becomes resumable (6 MiB) |
SBX_STORAGE_MEMORY_CAP_BYTES | Memory ceiling for BytesSource and download (32 MiB) |
SBX_STORAGE_UPLOAD_TIMEOUT_SECONDS | Upload timeout in seconds (120) |
SBX_STORAGE_MAX_CONCURRENT_TRANSFERS | Concurrent 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
| Class | Fields | Notes |
|---|---|---|
BytesSource | data, filename, content_type | In memory; above SBX_STORAGE_MEMORY_CAP_BYTES it raises ValidationError (use PathSource or StreamSource). |
PathSource | path, filename, content_type | Reads from disk as a stream; filename defaults to the file name; a missing file raises ValidationError. |
StreamSource | stream, size, filename, content_type, restartable | With 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
| Field | Effect |
|---|---|
bucket | None uses SBX_BUCKET_DEFAULT; must be in the allowlist. |
folder | Logical subfolder (validated). Generated path: <folder>/YYYY/MM/<uuid><ext>. |
path | Explicit path, which replaces automatic naming and is always validated. |
collision | REJECT (default: FileAlreadyExistsError), VERSION (writes to name-v2.ext, -v3...) or OVERWRITE (overwrites, explicit only). |
content_type | Declared MIME type, checked against the extension and the content. |
metadata | str to str metadata (up to 50 entries); the integration adds original_name. |
cache_control_seconds | None uses SBX_STORAGE_CACHE_CONTROL_SECONDS. |
correlation_id | Identifier 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, recursivelyPartial 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
| Method | Return | Short Description |
|---|---|---|
upload(source, options=None) | StoredFile | Validates and uploads the file; upload_mode is standard or resumable. |
download(path, bucket=None) | bytes | Downloads into memory; rejects an object above the ceiling (use download_to). |
download_to(path, destination, bucket=None) | Path | Streams the download to disk and creates parent folders. |
signed_url(path, bucket=None, ttl_seconds=None) | str | Temporary URL; it is never logged. |
public_url(path, bucket=None) | str | Public URL, only for a bucket in SBX_BUCKETS_PUBLIC; built locally, without network. |
exists(path, bucket=None) | bool | Tells 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) | DeleteReport | Deletes in batches; idempotent; failures go to failed. |
delete_prefix(prefix, bucket=None) | DeleteReport | Deletes 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 afterstatus | Meaning | orphan_possible |
|---|---|---|
completa | All steps completed. | False |
falhou | Nothing was left behind (failure before writing, or successful compensation). | False |
parcial | Something 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
| Exception | When |
|---|---|
ValidationError | Bucket outside the allowlist, empty file, mismatched or disallowed type, invalid path, signed URL above the ceiling, non-public bucket in public_url. |
FileTooLargeError | File above SBX_STORAGE_MAX_FILE_BYTES or a 413 response from Storage. |
FileAlreadyExistsError | The path already exists with CollisionPolicy.REJECT. |
FileNotFoundInStorageError | Object does not exist (Storage also uses 404 for "no permission"). |
PermissionDeniedError, AuthenticationError | The bucket policy denied access; invalid key. |
UploadError, DownloadError | Unclassified storage failure. |
OperationTimeoutError, ServiceUnavailableError, RateLimitError | Transient 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_BYTESthe transfer uses the TUS protocol in chunks, without loading the whole file into memory. - Safe retry: only
OVERWRITEis retried by the executor. WithREJECTandVERSIONa timeout becomesoutcome_unknown=Trueand the object may have been written: check withexists. - 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_KEYkey and signed URLs never appear in logs or error messages.
Source: src/database/supabase_integration/storage/