import os import uuid import aiofiles import aioboto3 from pathlib import Path from typing import Optional, Any, Union from core.config import get_settings from core.logging import get_logger settings = get_settings() logger = get_logger(__name__) class StorageResult: def __init__(self, path: str, backend: str, url: Optional[str] = None): self.path = path self.backend = backend self.url = url class LocalStorage: def __init__(self): self.base_dir = Path(settings.effective_upload_dir) self.base_dir.mkdir(parents=True, exist_ok=True) async def upload(self, file_content: bytes, filename: str, workspace_id: Any) -> StorageResult: file_id = uuid.uuid4() workspace_dir = self.base_dir / str(workspace_id) workspace_dir.mkdir(exist_ok=True) file_path = workspace_dir / f"{file_id}_{filename}" async with aiofiles.open(file_path, mode="wb") as f: await f.write(file_content) return StorageResult(path=str(file_path), backend="local") async def get_url(self, storage_path: str) -> str: # For local, we return a mock or actual local download endpoint if we had one # Currently, the API handles this via FileResponse. return storage_path def get_local_path(self, storage_path: str) -> str: return storage_path async def delete(self, storage_path: str) -> bool: try: if os.path.exists(storage_path): os.remove(storage_path) return True except Exception as e: logger.error(f"Local Storage: Failed to delete {storage_path}: {e}") return False class S3Storage: def __init__(self): self.bucket = settings.S3_BUCKET self.session = aioboto3.Session( aws_access_key_id=settings.S3_ACCESS_KEY, aws_secret_access_key=settings.S3_SECRET_KEY, region_name=settings.S3_REGION ) self.local_fallback = LocalStorage() async def upload(self, file_content: bytes, filename: str, workspace_id: Any) -> StorageResult: # Check if S3 is even configured if not settings.S3_ACCESS_KEY or not settings.S3_SECRET_KEY: logger.warning("S3 Storage not configured. Falling back to local storage.") return await self.local_fallback.upload(file_content, filename, workspace_id) file_id = uuid.uuid4() key = f"{workspace_id}/{file_id}_{filename}" try: async with self.session.client("s3", endpoint_url=settings.S3_ENDPOINT_URL or None) as s3: await s3.put_object(Bucket=self.bucket, Key=key, Body=file_content) logger.info(f"S3 Storage: Uploaded {key} to bucket {self.bucket}") return StorageResult(path=key, backend="s3") except Exception as e: logger.error(f"S3 Storage Upload failed: {e}. Falling back to local storage.") return await self.local_fallback.upload(file_content, filename, workspace_id) async def get_url(self, storage_path: str, expires_in: int = 3600) -> str: """Generates a Presigned URL for S3 or returns local path.""" if "/" not in storage_path and not storage_path.startswith("uploads"): # Likely an S3 Key try: async with self.session.client("s3", endpoint_url=settings.S3_ENDPOINT_URL or None) as s3: url = await s3.generate_presigned_url( 'get_object', Params={'Bucket': self.bucket, 'Key': storage_path}, ExpiresIn=expires_in ) return url except Exception as e: logger.error(f"S3 Storage: Failed to generate presigned URL for {storage_path}: {e}") return storage_path return storage_path def get_local_path(self, storage_path: str) -> str: return self.local_fallback.get_local_path(storage_path) async def delete(self, storage_path: str) -> bool: if "/" in storage_path and not storage_path.startswith("uploads"): try: async with self.session.client("s3", endpoint_url=settings.S3_ENDPOINT_URL or None) as s3: await s3.delete_object(Bucket=self.bucket, Key=storage_path) return True except Exception as e: logger.error(f"S3 Storage: Failed to delete key {storage_path}: {e}") return False return await self.local_fallback.delete(storage_path) _storage_instance = None def get_storage_provider() -> Union[LocalStorage, S3Storage]: global _storage_instance if _storage_instance is None: if settings.STORAGE_BACKEND == "s3": _storage_instance = S3Storage() else: _storage_instance = LocalStorage() return _storage_instance