|
| 1 | +import mimetypes |
| 2 | +import shutil |
| 3 | +from pathlib import Path |
| 4 | +from typing import Any, Dict, Union |
| 5 | +from urllib.request import pathname2url |
| 6 | + |
| 7 | +from chainlit import make_async |
| 8 | +from chainlit.data.storage_clients.base import BaseStorageClient |
| 9 | +from chainlit.logger import logger |
| 10 | + |
| 11 | + |
| 12 | +class LocalStorageClient(BaseStorageClient): |
| 13 | + """ |
| 14 | + Class to enable local file system storage provider |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__(self, storage_path: str): |
| 18 | + try: |
| 19 | + self.storage_path = Path(storage_path).resolve() |
| 20 | + |
| 21 | + # Create storage directory if it doesn't exist |
| 22 | + self.storage_path.mkdir(parents=True, exist_ok=True) |
| 23 | + |
| 24 | + logger.info( |
| 25 | + f"LocalStorageClient initialized with path: {self.storage_path}" |
| 26 | + ) |
| 27 | + except Exception as e: |
| 28 | + logger.warning(f"LocalStorageClient initialization error: {e}") |
| 29 | + raise |
| 30 | + |
| 31 | + def _validate_object_key(self, object_key: str) -> Path: |
| 32 | + """ |
| 33 | + Validate object_key and ensure the resolved path is within storage directory. |
| 34 | +
|
| 35 | + Args: |
| 36 | + object_key: The object key to validate |
| 37 | +
|
| 38 | + Returns: |
| 39 | + Resolved Path object within storage directory |
| 40 | +
|
| 41 | + Raises: |
| 42 | + ValueError: If path traversal is detected or path is invalid |
| 43 | + """ |
| 44 | + try: |
| 45 | + # Reject absolute paths immediately |
| 46 | + if object_key.startswith("/"): |
| 47 | + logger.warning(f"Absolute path rejected: {object_key}") |
| 48 | + raise ValueError("Invalid object key: absolute paths not allowed") |
| 49 | + |
| 50 | + # Normalize object_key and check for traversal patterns |
| 51 | + normalized_key = object_key.strip() |
| 52 | + if ".." in normalized_key or "\\" in normalized_key: |
| 53 | + logger.warning(f"Path traversal patterns detected: {object_key}") |
| 54 | + raise ValueError("Invalid object key: path traversal detected") |
| 55 | + |
| 56 | + # Create the file path |
| 57 | + file_path = self.storage_path / normalized_key |
| 58 | + resolved_path = file_path.resolve() |
| 59 | + |
| 60 | + # Ensure the resolved path is within the storage directory |
| 61 | + resolved_path.relative_to(self.storage_path) |
| 62 | + |
| 63 | + return resolved_path |
| 64 | + except ValueError as e: |
| 65 | + # Re-raise ValueError as is (our custom errors) |
| 66 | + raise e |
| 67 | + except Exception as e: |
| 68 | + logger.warning(f"Path validation error for {object_key}: {e}") |
| 69 | + raise ValueError(f"Invalid object key: {e}") |
| 70 | + |
| 71 | + def sync_get_read_url(self, object_key: str) -> str: |
| 72 | + try: |
| 73 | + file_path = self._validate_object_key(object_key) |
| 74 | + if file_path.exists(): |
| 75 | + # Return URL pointing to the backend's storage route |
| 76 | + url_path = pathname2url(object_key) |
| 77 | + return f"/storage/file/{url_path}" |
| 78 | + else: |
| 79 | + logger.warning(f"LocalStorageClient: File not found: {object_key}") |
| 80 | + return object_key |
| 81 | + except ValueError: |
| 82 | + # Path validation failed, return object_key as fallback |
| 83 | + return object_key |
| 84 | + except Exception as e: |
| 85 | + logger.warning(f"LocalStorageClient, get_read_url error: {e}") |
| 86 | + return object_key |
| 87 | + |
| 88 | + async def get_read_url(self, object_key: str) -> str: |
| 89 | + return await make_async(self.sync_get_read_url)(object_key) |
| 90 | + |
| 91 | + def sync_upload_file( |
| 92 | + self, |
| 93 | + object_key: str, |
| 94 | + data: Union[bytes, str], |
| 95 | + mime: str = "application/octet-stream", |
| 96 | + overwrite: bool = True, |
| 97 | + content_disposition: str | None = None, |
| 98 | + ) -> Dict[str, Any]: |
| 99 | + try: |
| 100 | + file_path = self._validate_object_key(object_key) |
| 101 | + |
| 102 | + # Create parent directories if they don't exist |
| 103 | + file_path.parent.mkdir(parents=True, exist_ok=True) |
| 104 | + |
| 105 | + # Check if file exists and overwrite is False |
| 106 | + if file_path.exists() and not overwrite: |
| 107 | + logger.warning( |
| 108 | + f"LocalStorageClient: File exists and overwrite=False: {object_key}" |
| 109 | + ) |
| 110 | + return {} |
| 111 | + |
| 112 | + # Write data to file |
| 113 | + if isinstance(data, str): |
| 114 | + file_path.write_text(data, encoding="utf-8") |
| 115 | + else: |
| 116 | + file_path.write_bytes(data) |
| 117 | + |
| 118 | + # Generate URL for the uploaded file using backend's storage route |
| 119 | + relative_path = file_path.relative_to(self.storage_path) |
| 120 | + url_path = pathname2url(str(relative_path)) |
| 121 | + url = f"/storage/file/{url_path}" |
| 122 | + |
| 123 | + return {"object_key": object_key, "url": url} |
| 124 | + except ValueError as e: |
| 125 | + logger.warning(f"LocalStorageClient, upload_file error: {e}") |
| 126 | + return {} |
| 127 | + except Exception as e: |
| 128 | + logger.warning(f"LocalStorageClient, upload_file error: {e}") |
| 129 | + return {} |
| 130 | + |
| 131 | + async def upload_file( |
| 132 | + self, |
| 133 | + object_key: str, |
| 134 | + data: Union[bytes, str], |
| 135 | + mime: str = "application/octet-stream", |
| 136 | + overwrite: bool = True, |
| 137 | + content_disposition: str | None = None, |
| 138 | + ) -> Dict[str, Any]: |
| 139 | + return await make_async(self.sync_upload_file)( |
| 140 | + object_key, data, mime, overwrite, content_disposition |
| 141 | + ) |
| 142 | + |
| 143 | + def sync_delete_file(self, object_key: str) -> bool: |
| 144 | + try: |
| 145 | + file_path = self._validate_object_key(object_key) |
| 146 | + if file_path.exists(): |
| 147 | + if file_path.is_file(): |
| 148 | + file_path.unlink() |
| 149 | + elif file_path.is_dir(): |
| 150 | + shutil.rmtree(file_path) |
| 151 | + return True |
| 152 | + else: |
| 153 | + logger.warning( |
| 154 | + f"LocalStorageClient: File not found for deletion: {object_key}" |
| 155 | + ) |
| 156 | + return False |
| 157 | + except ValueError as e: |
| 158 | + logger.warning(f"LocalStorageClient, delete_file error: {e}") |
| 159 | + return False |
| 160 | + except Exception as e: |
| 161 | + logger.warning(f"LocalStorageClient, delete_file error: {e}") |
| 162 | + return False |
| 163 | + |
| 164 | + async def delete_file(self, object_key: str) -> bool: |
| 165 | + return await make_async(self.sync_delete_file)(object_key) |
| 166 | + |
| 167 | + def sync_download_file(self, object_key: str) -> tuple[bytes, str] | None: |
| 168 | + try: |
| 169 | + file_path = self._validate_object_key(object_key) |
| 170 | + if not file_path.exists() or not file_path.is_file(): |
| 171 | + logger.warning( |
| 172 | + f"LocalStorageClient: File not found for download: {object_key}" |
| 173 | + ) |
| 174 | + return None |
| 175 | + |
| 176 | + # Get MIME type |
| 177 | + mime_type, _ = mimetypes.guess_type(str(file_path)) |
| 178 | + if not mime_type: |
| 179 | + mime_type = "application/octet-stream" |
| 180 | + |
| 181 | + # Read file content |
| 182 | + content = file_path.read_bytes() |
| 183 | + return (content, mime_type) |
| 184 | + except ValueError as e: |
| 185 | + logger.warning(f"LocalStorageClient, download_file error: {e}") |
| 186 | + return None |
| 187 | + except Exception as e: |
| 188 | + logger.warning(f"LocalStorageClient, download_file error: {e}") |
| 189 | + return None |
| 190 | + |
| 191 | + async def download_file(self, object_key: str) -> tuple[bytes, str] | None: |
| 192 | + return await make_async(self.sync_download_file)(object_key) |
0 commit comments