Spaces:
Paused

File size: 4,776 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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.UPLOAD_DIR)
        self.base_dir.mkdir(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)

def get_storage_provider() -> Union[LocalStorage, S3Storage]:
    if settings.STORAGE_BACKEND == "s3":
        return S3Storage()
    return LocalStorage()