-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfile_storage.py
More file actions
161 lines (123 loc) · 4.85 KB
/
file_storage.py
File metadata and controls
161 lines (123 loc) · 4.85 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
from __future__ import annotations
import json
import time
import uuid
from dataclasses import asdict, dataclass
from pathlib import Path
@dataclass(frozen=True, slots=True)
class FileMetadata:
file_id: str
filename: str
size_bytes: int
upload_time: float
class FileStorageService:
"""Service for managing uploaded files with UUID-based storage."""
def __init__(self, storage_dir: Path) -> None:
self.storage_dir = storage_dir
self.storage_dir.mkdir(parents=True, exist_ok=True)
def _get_file_path(self, file_id: str) -> Path:
"""Get the filesystem path for a file ID."""
return self.storage_dir / file_id
def _get_metadata_path(self, file_id: str) -> Path:
"""Get the filesystem path for file metadata."""
return self.storage_dir / f"{file_id}.meta.json"
def save_file(self, content: bytes, filename: str) -> str:
"""Save file content and return a unique file ID.
Args:
content: Raw file bytes to store
filename: Original filename for metadata
Returns:
UUID string identifying the stored file
"""
file_id = str(uuid.uuid4())
file_path = self._get_file_path(file_id)
metadata_path = self._get_metadata_path(file_id)
# Write file content
file_path.write_bytes(content)
# Write metadata
metadata = FileMetadata(
file_id=file_id,
filename=filename,
size_bytes=len(content),
upload_time=time.time(),
)
metadata_path.write_text(json.dumps(asdict(metadata)), encoding="utf-8")
return file_id
def get_file(self, file_id: str) -> tuple[bytes, FileMetadata]:
"""Retrieve file content and metadata by ID.
Args:
file_id: UUID of the file to retrieve
Returns:
Tuple of (file_content, metadata)
Raises:
FileNotFoundError: If file_id doesn't exist
"""
file_path = self._get_file_path(file_id)
metadata_path = self._get_metadata_path(file_id)
if not file_path.exists():
raise FileNotFoundError(f"File with ID '{file_id}' not found")
content = file_path.read_bytes()
# Read metadata if available, otherwise create minimal metadata
if metadata_path.exists():
meta_dict = json.loads(metadata_path.read_text(encoding="utf-8"))
metadata = FileMetadata(**meta_dict)
else:
# Fallback for files without metadata
metadata = FileMetadata(
file_id=file_id,
filename="unknown",
size_bytes=len(content),
upload_time=file_path.stat().st_mtime,
)
return content, metadata
def delete_file(self, file_id: str) -> bool:
"""Delete a file and its metadata by ID.
Args:
file_id: UUID of the file to delete
Returns:
True if file was deleted, False if it didn't exist
"""
file_path = self._get_file_path(file_id)
metadata_path = self._get_metadata_path(file_id)
existed = file_path.exists()
# Remove both file and metadata if they exist
if file_path.exists():
file_path.unlink()
if metadata_path.exists():
metadata_path.unlink()
return existed
def list_files(self) -> list[FileMetadata]:
"""List all stored files with their metadata.
Returns:
List of FileMetadata objects for all stored files
"""
result: list[FileMetadata] = []
for metadata_path in self.storage_dir.glob("*.meta.json"):
try:
meta_dict = json.loads(metadata_path.read_text(encoding="utf-8"))
result.append(FileMetadata(**meta_dict))
except (json.JSONDecodeError, TypeError):
# Skip invalid metadata files
continue
return result
def cleanup_expired_files(self, max_age_sec: int) -> int:
"""Remove files older than the specified age.
Args:
max_age_sec: Maximum age in seconds before files are deleted
Returns:
Number of files deleted
"""
current_time = time.time()
deleted_count = 0
for metadata_path in self.storage_dir.glob("*.meta.json"):
try:
meta_dict = json.loads(metadata_path.read_text(encoding="utf-8"))
metadata = FileMetadata(**meta_dict)
if current_time - metadata.upload_time > max_age_sec and self.delete_file(
metadata.file_id
):
deleted_count += 1
except (json.JSONDecodeError, TypeError, FileNotFoundError):
# Skip invalid or already-deleted files
continue
return deleted_count