|
| 1 | +"""FileTreeStore implementation using native filesystem operations.""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +from key_value.shared.errors import DeserializationError |
| 6 | +from key_value.shared.utils.managed_entry import ManagedEntry |
| 7 | +from key_value.shared.utils.serialization import BasicSerializationAdapter, SerializationAdapter |
| 8 | +from typing_extensions import override |
| 9 | + |
| 10 | +from key_value.aio.stores.base import ( |
| 11 | + BaseDestroyCollectionStore, |
| 12 | + BaseDestroyStore, |
| 13 | + BaseEnumerateCollectionsStore, |
| 14 | + BaseEnumerateKeysStore, |
| 15 | +) |
| 16 | + |
| 17 | +DEFAULT_PAGE_SIZE = 10000 |
| 18 | +PAGE_LIMIT = 10000 |
| 19 | + |
| 20 | + |
| 21 | +class FileTreeStore(BaseDestroyStore, BaseDestroyCollectionStore, BaseEnumerateCollectionsStore, BaseEnumerateKeysStore): |
| 22 | + """A file-tree based store using directories for collections and files for keys. |
| 23 | +
|
| 24 | + This store uses the native filesystem: |
| 25 | + - Each collection is a subdirectory under the base directory |
| 26 | + - Each key is stored as a JSON file named "{key}.json" |
| 27 | + - File contents contain the ManagedEntry serialized to JSON |
| 28 | +
|
| 29 | + Directory structure: |
| 30 | + {base_directory}/ |
| 31 | + {collection_1}/ |
| 32 | + {key_1}.json |
| 33 | + {key_2}.json |
| 34 | + {collection_2}/ |
| 35 | + {key_3}.json |
| 36 | +
|
| 37 | + Warning: |
| 38 | + This store is intended for development and testing purposes only. |
| 39 | + It is not suitable for production use due to: |
| 40 | + - Poor performance with many keys |
| 41 | + - No atomic operations |
| 42 | + - No built-in cleanup of expired entries |
| 43 | + - Filesystem limitations on file names and directory sizes |
| 44 | +
|
| 45 | + The store does NOT automatically clean up expired entries from disk. Expired entries |
| 46 | + are only filtered out when read via get() or similar methods. |
| 47 | + """ |
| 48 | + |
| 49 | + _directory: Path |
| 50 | + |
| 51 | + def __init__( |
| 52 | + self, |
| 53 | + *, |
| 54 | + directory: Path | str, |
| 55 | + serialization_adapter: SerializationAdapter | None = None, |
| 56 | + default_collection: str | None = None, |
| 57 | + ) -> None: |
| 58 | + """Initialize the file-tree store. |
| 59 | +
|
| 60 | + Args: |
| 61 | + directory: The base directory to use for storing collections and keys. |
| 62 | + serialization_adapter: The serialization adapter to use for the store. |
| 63 | + default_collection: The default collection to use if no collection is provided. |
| 64 | + """ |
| 65 | + self._directory = Path(directory).resolve() |
| 66 | + self._directory.mkdir(parents=True, exist_ok=True) |
| 67 | + |
| 68 | + self._stable_api = False |
| 69 | + |
| 70 | + super().__init__( |
| 71 | + serialization_adapter=serialization_adapter or BasicSerializationAdapter(), |
| 72 | + default_collection=default_collection, |
| 73 | + ) |
| 74 | + |
| 75 | + def _get_collection_path(self, collection: str) -> Path: |
| 76 | + """Get the path to a collection directory. |
| 77 | +
|
| 78 | + Args: |
| 79 | + collection: The collection name. |
| 80 | +
|
| 81 | + Returns: |
| 82 | + The path to the collection directory. |
| 83 | +
|
| 84 | + Raises: |
| 85 | + ValueError: If the collection name would result in a path outside the base directory. |
| 86 | + """ |
| 87 | + collection_path = (self._directory / collection).resolve() |
| 88 | + |
| 89 | + if not collection_path.is_relative_to(self._directory): |
| 90 | + msg = f"Invalid collection name: {collection!r} would escape base directory" |
| 91 | + raise ValueError(msg) |
| 92 | + |
| 93 | + return collection_path |
| 94 | + |
| 95 | + def _get_key_path(self, collection: str, key: str) -> Path: |
| 96 | + """Get the path to a key file. |
| 97 | +
|
| 98 | + Args: |
| 99 | + collection: The collection name. |
| 100 | + key: The key name. |
| 101 | +
|
| 102 | + Returns: |
| 103 | + The path to the key file. |
| 104 | +
|
| 105 | + Raises: |
| 106 | + ValueError: If the collection or key name would result in a path outside the base directory. |
| 107 | + """ |
| 108 | + collection_path = self._get_collection_path(collection) |
| 109 | + key_path = (collection_path / f"{key}.json").resolve() |
| 110 | + |
| 111 | + if not key_path.is_relative_to(self._directory): |
| 112 | + msg = f"Invalid key name: {key!r} would escape base directory" |
| 113 | + raise ValueError(msg) |
| 114 | + |
| 115 | + return key_path |
| 116 | + |
| 117 | + @override |
| 118 | + async def _setup_collection(self, *, collection: str) -> None: |
| 119 | + """Set up a collection by creating its directory if it doesn't exist. |
| 120 | +
|
| 121 | + Args: |
| 122 | + collection: The collection name. |
| 123 | + """ |
| 124 | + collection_path = self._get_collection_path(collection) |
| 125 | + collection_path.mkdir(parents=True, exist_ok=True) |
| 126 | + |
| 127 | + @override |
| 128 | + async def _get_managed_entry(self, *, key: str, collection: str) -> ManagedEntry | None: |
| 129 | + """Retrieve a managed entry by key from the specified collection. |
| 130 | +
|
| 131 | + Args: |
| 132 | + collection: The collection name. |
| 133 | + key: The key name. |
| 134 | +
|
| 135 | + Returns: |
| 136 | + The managed entry if found and not expired, None otherwise. |
| 137 | + """ |
| 138 | + key_path = self._get_key_path(collection, key) |
| 139 | + |
| 140 | + if not key_path.exists(): |
| 141 | + return None |
| 142 | + |
| 143 | + try: |
| 144 | + json_str = key_path.read_text(encoding="utf-8") |
| 145 | + return self._serialization_adapter.load_json(json_str=json_str) |
| 146 | + except (OSError, DeserializationError): |
| 147 | + # If we can't read or parse the file, treat it as not found |
| 148 | + return None |
| 149 | + |
| 150 | + @override |
| 151 | + async def _put_managed_entry( |
| 152 | + self, |
| 153 | + *, |
| 154 | + key: str, |
| 155 | + collection: str, |
| 156 | + managed_entry: ManagedEntry, |
| 157 | + ) -> None: |
| 158 | + """Store a managed entry at the specified key in the collection. |
| 159 | +
|
| 160 | + Args: |
| 161 | + collection: The collection name. |
| 162 | + key: The key name. |
| 163 | + managed_entry: The managed entry to store. |
| 164 | + """ |
| 165 | + key_path = self._get_key_path(collection, key) |
| 166 | + |
| 167 | + # Ensure the parent directory exists |
| 168 | + key_path.parent.mkdir(parents=True, exist_ok=True) |
| 169 | + |
| 170 | + # Write the managed entry to the file |
| 171 | + json_str = self._serialization_adapter.dump_json(entry=managed_entry) |
| 172 | + key_path.write_text(json_str, encoding="utf-8") |
| 173 | + |
| 174 | + @override |
| 175 | + async def _delete_managed_entry(self, *, key: str, collection: str) -> bool: |
| 176 | + """Delete a managed entry from the specified collection. |
| 177 | +
|
| 178 | + Args: |
| 179 | + collection: The collection name. |
| 180 | + key: The key name. |
| 181 | +
|
| 182 | + Returns: |
| 183 | + True if the entry was deleted, False if it didn't exist. |
| 184 | + """ |
| 185 | + key_path = self._get_key_path(collection, key) |
| 186 | + |
| 187 | + if not key_path.exists(): |
| 188 | + return False |
| 189 | + |
| 190 | + try: |
| 191 | + key_path.unlink() |
| 192 | + except OSError: |
| 193 | + return False |
| 194 | + else: |
| 195 | + return True |
| 196 | + |
| 197 | + @override |
| 198 | + async def _get_collection_keys(self, *, collection: str, limit: int | None = None) -> list[str]: |
| 199 | + """List all keys in the specified collection. |
| 200 | +
|
| 201 | + Args: |
| 202 | + collection: The collection name. |
| 203 | + limit: Maximum number of keys to return. |
| 204 | +
|
| 205 | + Returns: |
| 206 | + A list of key names (without the .json extension). |
| 207 | + """ |
| 208 | + limit = min(limit or DEFAULT_PAGE_SIZE, PAGE_LIMIT) |
| 209 | + collection_path = self._get_collection_path(collection) |
| 210 | + |
| 211 | + if not collection_path.exists(): |
| 212 | + return [] |
| 213 | + |
| 214 | + keys: list[str] = [] |
| 215 | + for file_path in collection_path.iterdir(): |
| 216 | + if file_path.is_file() and file_path.suffix == ".json": |
| 217 | + keys.append(file_path.stem) |
| 218 | + if len(keys) >= limit: |
| 219 | + break |
| 220 | + |
| 221 | + return keys |
| 222 | + |
| 223 | + @override |
| 224 | + async def _get_collection_names(self, *, limit: int | None = None) -> list[str]: |
| 225 | + """List all collection names. |
| 226 | +
|
| 227 | + Args: |
| 228 | + limit: Maximum number of collections to return. |
| 229 | +
|
| 230 | + Returns: |
| 231 | + A list of collection names. |
| 232 | + """ |
| 233 | + limit = min(limit or DEFAULT_PAGE_SIZE, PAGE_LIMIT) |
| 234 | + |
| 235 | + collections: list[str] = [] |
| 236 | + for dir_path in self._directory.iterdir(): |
| 237 | + if dir_path.is_dir(): |
| 238 | + collections.append(dir_path.name) |
| 239 | + if len(collections) >= limit: |
| 240 | + break |
| 241 | + |
| 242 | + return collections |
| 243 | + |
| 244 | + @override |
| 245 | + async def _delete_collection(self, *, collection: str) -> bool: |
| 246 | + """Delete an entire collection and all its keys. |
| 247 | +
|
| 248 | + Args: |
| 249 | + collection: The collection name. |
| 250 | +
|
| 251 | + Returns: |
| 252 | + True if the collection was deleted, False if it didn't exist or an error occurred. |
| 253 | + """ |
| 254 | + collection_path = self._get_collection_path(collection) |
| 255 | + |
| 256 | + if not collection_path.exists(): |
| 257 | + return False |
| 258 | + |
| 259 | + try: |
| 260 | + # Delete all files in the collection |
| 261 | + for file_path in collection_path.iterdir(): |
| 262 | + if file_path.is_file(): |
| 263 | + file_path.unlink() |
| 264 | + |
| 265 | + # Delete the collection directory |
| 266 | + collection_path.rmdir() |
| 267 | + except OSError: |
| 268 | + return False |
| 269 | + else: |
| 270 | + return True |
| 271 | + |
| 272 | + @override |
| 273 | + async def _delete_store(self) -> bool: |
| 274 | + """Delete the entire store and all its collections. |
| 275 | +
|
| 276 | + Returns: |
| 277 | + True if the store was deleted successfully. |
| 278 | + """ |
| 279 | + try: |
| 280 | + # Delete all collections |
| 281 | + for collection_path in self._directory.iterdir(): |
| 282 | + if collection_path.is_dir(): |
| 283 | + # Delete all files in the collection |
| 284 | + for file_path in collection_path.iterdir(): |
| 285 | + if file_path.is_file(): |
| 286 | + file_path.unlink() |
| 287 | + # Delete the collection directory |
| 288 | + collection_path.rmdir() |
| 289 | + except OSError: |
| 290 | + return False |
| 291 | + else: |
| 292 | + return True |
0 commit comments