Spaces:
Runtime error

File size: 9,495 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""Supabase Storage helpers (private bucket + signed URLs).

We store references in DB as `sb://<bucket>/<object_path>` (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