Greg Claude Sonnet 4.6 commited on
Commit
9e5f651
·
1 Parent(s): f2358b4

feat(ta-01): add PhotoStorage abstraction with Local/InMemory/Supabase adapters

Browse files
backend/app/storage/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from app.storage.base import PhotoStorage
3
+
4
+
5
+ def get_storage() -> PhotoStorage:
6
+ backend = os.getenv("PHOTO_STORAGE_BACKEND", "local").lower()
7
+ if backend == "local":
8
+ from app.storage.local_disk import LocalDiskStorage
9
+ return LocalDiskStorage(
10
+ root=os.getenv("LOCAL_PHOTO_ROOT", "/data/photos"),
11
+ url_prefix=os.getenv("LOCAL_PHOTO_URL_PREFIX", "/api/v1/photos"),
12
+ )
13
+ if backend == "supabase":
14
+ from app.storage.supabase import SupabaseStorage
15
+ return SupabaseStorage(
16
+ url=os.getenv("SUPABASE_URL", ""),
17
+ key=os.getenv("SUPABASE_SERVICE_KEY", ""),
18
+ bucket=os.getenv("SUPABASE_PHOTO_BUCKET", "user-photos"),
19
+ )
20
+ raise ValueError(f"Unknown PHOTO_STORAGE_BACKEND: {backend}")
backend/app/storage/base.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Protocol
2
+
3
+
4
+ class PhotoStorage(Protocol):
5
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
6
+ """Persiste el archivo y devuelve la ruta/identificador canónico que se guarda en BD."""
7
+ ...
8
+
9
+ def delete(self, path_or_url: str) -> None:
10
+ """Borra el archivo. Best-effort, no levanta si no existe."""
11
+ ...
12
+
13
+ def get_url(self, path_or_url: str) -> str:
14
+ """Devuelve la URL pública/firmada que el frontend usa para mostrar la foto."""
15
+ ...
backend/app/storage/in_memory.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+
3
+
4
+ class InMemoryStorage:
5
+ def __init__(self) -> None:
6
+ self.files: dict[str, bytes] = {}
7
+
8
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
9
+ path = f"mem://{account_id}/{user_id}/{uuid.uuid4()}.{ext}"
10
+ self.files[path] = content
11
+ return path
12
+
13
+ def delete(self, path_or_url: str) -> None:
14
+ self.files.pop(path_or_url, None)
15
+
16
+ def get_url(self, path_or_url: str) -> str:
17
+ return path_or_url
backend/app/storage/local_disk.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ from pathlib import Path
3
+
4
+
5
+ class LocalDiskStorage:
6
+ def __init__(self, root: str, url_prefix: str = "/api/v1/photos") -> None:
7
+ self.root = Path(root)
8
+ self.url_prefix = url_prefix.rstrip("/")
9
+
10
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
11
+ rel = f"{account_id}/{user_id}/{uuid.uuid4()}.{ext}"
12
+ target = self.root / rel
13
+ target.parent.mkdir(parents=True, exist_ok=True)
14
+ target.write_bytes(content)
15
+ return rel
16
+
17
+ def delete(self, path_or_url: str) -> None:
18
+ rel = path_or_url
19
+ if path_or_url.startswith(self.url_prefix + "/"):
20
+ rel = path_or_url[len(self.url_prefix) + 1:]
21
+ target = self.root / rel
22
+ try:
23
+ target.unlink()
24
+ except FileNotFoundError:
25
+ pass
26
+
27
+ def get_url(self, path_or_url: str) -> str:
28
+ if path_or_url.startswith("http://") or path_or_url.startswith("https://"):
29
+ return path_or_url
30
+ if path_or_url.startswith(self.url_prefix + "/"):
31
+ return path_or_url
32
+ return f"{self.url_prefix}/{path_or_url}"
backend/app/storage/supabase.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class SupabaseStorage:
2
+ """Stub. Se implementa cuando lleguen credenciales de Supabase."""
3
+
4
+ def __init__(self, url: str, key: str, bucket: str) -> None:
5
+ self.url = url
6
+ self.key = key
7
+ self.bucket = bucket
8
+
9
+ def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
10
+ raise NotImplementedError(
11
+ "SupabaseStorage upload todavía no implementado — usar PHOTO_STORAGE_BACKEND=local"
12
+ )
13
+
14
+ def delete(self, path_or_url: str) -> None:
15
+ raise NotImplementedError(
16
+ "SupabaseStorage delete todavía no implementado"
17
+ )
18
+
19
+ def get_url(self, path_or_url: str) -> str:
20
+ raise NotImplementedError(
21
+ "SupabaseStorage get_url todavía no implementado"
22
+ )
backend/tests/storage/__init__.py ADDED
File without changes
backend/tests/storage/test_factory.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from app.storage import get_storage
3
+ from app.storage.local_disk import LocalDiskStorage
4
+ from app.storage.supabase import SupabaseStorage
5
+
6
+
7
+ def test_default_backend_is_local(monkeypatch):
8
+ monkeypatch.delenv("PHOTO_STORAGE_BACKEND", raising=False)
9
+ s = get_storage()
10
+ assert isinstance(s, LocalDiskStorage)
11
+
12
+
13
+ def test_supabase_backend(monkeypatch):
14
+ monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "supabase")
15
+ s = get_storage()
16
+ assert isinstance(s, SupabaseStorage)
17
+
18
+
19
+ def test_unknown_backend_raises(monkeypatch):
20
+ monkeypatch.setenv("PHOTO_STORAGE_BACKEND", "azureblobs")
21
+ with pytest.raises(ValueError, match="Unknown PHOTO_STORAGE_BACKEND"):
22
+ get_storage()
backend/tests/storage/test_in_memory.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from app.storage.in_memory import InMemoryStorage
3
+
4
+
5
+ def test_upload_returns_unique_path():
6
+ storage = InMemoryStorage()
7
+ p1 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp")
8
+ p2 = storage.upload(account_id=1, user_id=10, content=b"a", ext="webp")
9
+ assert p1 != p2
10
+ assert p1.startswith("mem://1/10/") and p1.endswith(".webp")
11
+
12
+
13
+ def test_get_url_returns_canonical_form():
14
+ storage = InMemoryStorage()
15
+ path = storage.upload(1, 10, b"x", "webp")
16
+ assert storage.get_url(path) == path
17
+
18
+
19
+ def test_delete_is_idempotent():
20
+ storage = InMemoryStorage()
21
+ path = storage.upload(1, 10, b"x", "webp")
22
+ storage.delete(path)
23
+ storage.delete(path)
24
+ storage.delete("mem://does/not/exist.webp")
25
+
26
+
27
+ def test_files_attribute_exposes_content_for_assertions():
28
+ storage = InMemoryStorage()
29
+ path = storage.upload(1, 10, b"hello", "webp")
30
+ assert storage.files[path] == b"hello"
backend/tests/storage/test_local_disk.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import pytest
3
+ from app.storage.local_disk import LocalDiskStorage
4
+
5
+
6
+ @pytest.fixture
7
+ def storage(tmp_path: Path) -> LocalDiskStorage:
8
+ return LocalDiskStorage(root=str(tmp_path), url_prefix="/api/v1/photos")
9
+
10
+
11
+ def test_upload_creates_file(storage: LocalDiskStorage, tmp_path: Path):
12
+ path = storage.upload(account_id=2, user_id=20, content=b"abc", ext="webp")
13
+ assert path.startswith("2/20/") and path.endswith(".webp")
14
+ full = tmp_path / path
15
+ assert full.read_bytes() == b"abc"
16
+
17
+
18
+ def test_upload_creates_parent_dirs(storage: LocalDiskStorage, tmp_path: Path):
19
+ path = storage.upload(99, 999, b"x", "webp")
20
+ assert (tmp_path / path).exists()
21
+
22
+
23
+ def test_get_url_prepends_prefix(storage: LocalDiskStorage):
24
+ path = storage.upload(1, 1, b"x", "webp")
25
+ assert storage.get_url(path) == f"/api/v1/photos/{path}"
26
+
27
+
28
+ def test_delete_removes_file(storage: LocalDiskStorage, tmp_path: Path):
29
+ path = storage.upload(1, 1, b"x", "webp")
30
+ storage.delete(path)
31
+ assert not (tmp_path / path).exists()
32
+
33
+
34
+ def test_delete_missing_file_does_not_raise(storage: LocalDiskStorage):
35
+ storage.delete("nope/nope.webp")
backend/tests/storage/test_supabase.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from app.storage.supabase import SupabaseStorage
3
+
4
+
5
+ def test_upload_raises_until_credentials_arrive():
6
+ storage = SupabaseStorage(url="", key="", bucket="user-photos")
7
+ with pytest.raises(NotImplementedError, match="Supabase"):
8
+ storage.upload(1, 1, b"x", "webp")
9
+
10
+
11
+ def test_constructor_stores_config_without_calling_network():
12
+ s = SupabaseStorage(url="https://example.supabase.co", key="k", bucket="b")
13
+ assert s.bucket == "b"