"""Supabase Storage helpers (private bucket + signed URLs). We store references in DB as `sb:///` (NOT signed URLs). At read time we mint signed URLs and return them to the UI. """ from __future__ import annotations import mimetypes import os from dataclasses import dataclass from pathlib import Path from typing import Dict, Iterable, List, Optional, Tuple from supabase import Client, create_client SB_REF_PREFIX = "sb://" def is_sb_ref(value: Optional[str]) -> bool: return bool(value and str(value).startswith(SB_REF_PREFIX)) def make_sb_ref(bucket: str, object_path: str) -> str: bucket = str(bucket).strip().strip("/") object_path = str(object_path).strip().lstrip("/") return f"{SB_REF_PREFIX}{bucket}/{object_path}" def parse_sb_ref(ref: str) -> Tuple[str, str]: raw = str(ref) if not raw.startswith(SB_REF_PREFIX): raise ValueError("Not a Supabase storage ref") rest = raw[len(SB_REF_PREFIX) :] bucket, _, path = rest.partition("/") if not bucket or not path: raise ValueError("Malformed Supabase storage ref") return bucket, path @dataclass class SupabaseStorageManager: """Thin wrapper around supabase-py storage operations.""" url: str service_key: str bucket: str = "ai-tester-screenshots" signed_url_ttl_seconds: int = 3600 _client: Optional[Client] = None _bucket_ready: bool = False @classmethod def from_env(cls) -> Optional["SupabaseStorageManager"]: url = os.getenv("SUPABASE_URL") service_key = os.getenv("SUPABASE_SERVICE_KEY") if not url or not service_key: return None bucket = os.getenv("SUPABASE_SCREENSHOTS_BUCKET", "ai-tester-screenshots").strip() or "ai-tester-screenshots" try: ttl = int(os.getenv("SUPABASE_SIGNED_URL_TTL_SECONDS", "3600")) except (TypeError, ValueError): ttl = 3600 ttl = max(60, ttl) # avoid accidental 0/negative return cls( url=url, service_key=service_key, bucket=bucket, signed_url_ttl_seconds=ttl, ) def client(self) -> Client: if self._client is None: # Service role key is required for private bucket admin ops (create/sign). self._client = create_client(self.url, self.service_key) return self._client def ensure_bucket(self, bucket: Optional[str] = None) -> None: bucket_id = (bucket or self.bucket).strip().strip("/") if not bucket_id: raise ValueError("Bucket id is empty") # Only memoize the default bucket. if bucket_id == self.bucket and self._bucket_ready: return storage = self.client().storage try: storage.get_bucket(bucket_id) except Exception: # Create a private bucket (public=False). Idempotent enough for our use. storage.create_bucket(bucket_id, options={"public": False}) if bucket_id == self.bucket: self._bucket_ready = True def upload_file(self, local_path: Path, object_path: str, bucket: Optional[str] = None) -> str: bucket_id = (bucket or self.bucket).strip().strip("/") if not bucket_id: raise ValueError("Bucket id is empty") object_path = str(object_path).strip().lstrip("/") if not object_path: raise ValueError("Object path is empty") self.ensure_bucket(bucket_id) content_type = mimetypes.guess_type(str(local_path))[0] or "application/octet-stream" file_options = { "content-type": content_type, "upsert": "true", # Cache signed URL responses at the edge/browser when possible. "cache-control": "max-age=3600", } # `upload` accepts a file path string; it streams the file. self.client().storage.from_(bucket_id).upload(object_path, str(local_path), file_options=file_options) return make_sb_ref(bucket_id, object_path) def upload_bytes( self, content: bytes, object_path: str, *, content_type: Optional[str] = None, bucket: Optional[str] = None, ) -> str: bucket_id = (bucket or self.bucket).strip().strip("/") if not bucket_id: raise ValueError("Bucket id is empty") object_path = str(object_path).strip().lstrip("/") if not object_path: raise ValueError("Object path is empty") self.ensure_bucket(bucket_id) file_options = { "content-type": content_type or "application/octet-stream", "upsert": "true", "cache-control": "max-age=3600", } self.client().storage.from_(bucket_id).upload(object_path, content, file_options=file_options) return make_sb_ref(bucket_id, object_path) def download_bytes(self, ref: str) -> Tuple[bytes, str]: """Download the object referenced by an `sb://` URI and return (bytes, content_type). Used to attach screenshots to OpenProject.""" bucket, path = parse_sb_ref(ref) self.ensure_bucket(bucket) content = self.client().storage.from_(bucket).download(path) if not isinstance(content, (bytes, bytearray)): content = bytes(content) content_type = mimetypes.guess_type(path)[0] or "application/octet-stream" return bytes(content), content_type def delete_refs(self, refs: Iterable[str]) -> Dict[str, int]: """Cancella i file referenziati da `sb://...` URIs dal bucket. Raggruppa per bucket per minimizzare le round-trip e usa il batch `remove([path1, path2, ...])` di supabase-py. Ritorna un dict `{bucket: count_deleted}` per telemetry/logging. Errori per singolo file vengono swallow-ati per non bloccare un batch: il file è già "perso" dal punto di vista del DB se la ref viene rimossa subito dopo, e supabase-py non distingue 404 (già cancellato) da altri errori in modo affidabile. Usato da: - `delete_session()` quando l'utente cancella manualmente (hard delete cascading anche sul bucket). - Purge job ricorrente (>45gg, vedi `purge_old_screenshots`). """ refs_list = [r for r in refs if is_sb_ref(r)] if not refs_list: return {} by_bucket: Dict[str, List[str]] = {} for ref in refs_list: try: bucket, path = parse_sb_ref(ref) except Exception: continue by_bucket.setdefault(bucket, []).append(path) deleted: Dict[str, int] = {} for bucket, paths in by_bucket.items(): if not paths: continue try: self.ensure_bucket(bucket) # supabase-py: client.storage.from_(bucket).remove(paths) # accetta una lista di paths e ritorna lista di rimossi. # Spezziamo in chunk per evitare richieste troppo grosse # (limite empirico: ~500 path/call). chunk_size = 500 bucket_deleted = 0 for i in range(0, len(paths), chunk_size): chunk = paths[i : i + chunk_size] try: self.client().storage.from_(bucket).remove(chunk) bucket_deleted += len(chunk) except Exception: # Best-effort: continua col chunk successivo. pass deleted[bucket] = bucket_deleted except Exception: continue return deleted def sign_refs(self, refs: Iterable[str], expires_in: Optional[int] = None) -> Dict[str, str]: """Return a map of `sb://...` ref -> signed URL.""" refs_list = [r for r in refs if is_sb_ref(r)] if not refs_list: return {} ttl = int(expires_in or self.signed_url_ttl_seconds) ttl = max(60, ttl) by_bucket: Dict[str, List[str]] = {} for ref in refs_list: try: bucket, path = parse_sb_ref(ref) except Exception: continue by_bucket.setdefault(bucket, []).append(path) signed: Dict[str, str] = {} for bucket, paths in by_bucket.items(): if not paths: continue try: self.ensure_bucket(bucket) responses = self.client().storage.from_(bucket).create_signed_urls(paths, ttl) except Exception: continue for item in responses or []: # storage3 can return objects or plain dicts depending on version. if isinstance(item, dict): url = item.get("signedUrl") or item.get("signedURL") path = item.get("path") err = item.get("error") else: # storage3 returns both `signedUrl` and `signedURL` depending on version url = getattr(item, "signedUrl", None) or getattr(item, "signedURL", None) path = getattr(item, "path", None) err = getattr(item, "error", None) if err or not url or not path: continue signed[make_sb_ref(bucket, path)] = url return signed