# Subtask: File Upload API **Parent Task**: Decomp/005 **Subtask ID**: Decomp-005-02 **Dependencies**: Decomp-005-01 (Storage Architecture and Metadata) ## Description Implement file upload API supporting single file uploads, metadata handling, checksum verification, and automatic replication. Support multiple upload methods (direct, presigned URL). ## Requirements - Upload files to buckets - Support files up to 5GB (single part) - Calculate and verify MD5 checksums - Handle content-type and custom metadata - Automatic replication to storage nodes - Progress tracking for uploads - Presigned URL support for direct uploads - Quota enforcement ## Technical Specifications **Upload service**: ```python from typing import Optional, Dict, Any, BinaryIO from dataclasses import dataclass from datetime import datetime, timezone, timedelta from decimal import Decimal from pathlib import Path import hashlib import uuid import logging import asyncio logger = logging.getLogger(__name__) @dataclass class UploadResult: """Result of file upload.""" success: bool object_id: int = None version_id: str = None etag: str = None location: str = None error: str = None @dataclass class UploadProgress: """Upload progress tracking.""" bytes_uploaded: int total_bytes: int percentage: float current_part: int = None class FileUploadService: """Service for handling file uploads.""" def __init__( self, db, hash_ring, replication_service, storage_adapter ): self.db = db self.hash_ring = hash_ring self.replication = replication_service self.storage = storage_adapter async def upload_file( self, bucket_id: int, object_key: str, data: BinaryIO, content_length: int, content_type: str = None, metadata: Dict[str, Any] = None, storage_class: str = "standard" ) -> UploadResult: """ Upload a file to a bucket. Args: bucket_id: Target bucket ID object_key: Object key (path/filename) data: File data as readable stream content_length: Size of file in bytes content_type: MIME type metadata: Custom user metadata storage_class: Storage class (standard, infrequent, archive) Returns: UploadResult with object details """ try: # Verify bucket exists and check quota bucket = await self._verify_bucket(bucket_id) if not bucket: return UploadResult(success=False, error="Bucket not found") # Check quota if bucket["quota_bytes"]: used = bucket.get("used_bytes", 0) if used + content_length > bucket["quota_bytes"]: return UploadResult( success=False, error=f"Quota exceeded. Available: {bucket['quota_bytes'] - used} bytes" ) # Calculate checksum while reading md5_hash = hashlib.md5() sha256_hash = hashlib.sha256() file_data = bytearray() while chunk := data.read(8192): md5_hash.update(chunk) sha256_hash.update(chunk) file_data.extend(chunk) etag = md5_hash.hexdigest() checksum_sha256 = sha256_hash.hexdigest() # Get storage nodes via consistent hashing storage_key = f"{bucket_id}:{object_key}" node_ids = self.hash_ring.get_nodes(storage_key) if not node_ids: return UploadResult(success=False, error="No storage nodes available") # Write to primary node primary_node = node_ids[0] file_path = await self.storage.write_file( node_id=primary_node, bucket_name=bucket["name"], object_key=object_key, data=bytes(file_data) ) # Create object record async with self.db.acquire() as conn: object_record = await conn.fetchrow( """INSERT INTO objects (bucket_id, object_key, content_type, content_length, etag, checksum_sha256, storage_class, storage_nodes, user_metadata, modified_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NOW()) RETURNING id, version_id, etag""", bucket_id, object_key, content_type or "application/octet-stream", content_length, etag, checksum_sha256, storage_class, json.dumps(node_ids), json.dumps(metadata or {}) ) # Trigger replication to other nodes await self.replication.replicate_object( object_id=object_record["id"], source_node=primary_node, target_nodes=node_ids[1:] ) # Log upload await self._log_operation( bucket_id=bucket_id, object_id=object_record["id"], operation="PUT", bytes_received=content_length, http_status=201 ) return UploadResult( success=True, object_id=object_record["id"], version_id=object_record["version_id"], etag=object_record["etag"], location=f"/{bucket['name']}/{object_key}" ) except Exception as e: logger.error(f"Upload failed for {object_key}: {e}") return UploadResult(success=False, error=str(e)) async def upload_file_from_path( self, bucket_id: int, object_key: str, file_path: str, content_type: str = None, metadata: Dict[str, Any] = None ) -> UploadResult: """Upload a file from local filesystem path.""" path = Path(file_path) if not path.exists(): return UploadResult(success=False, error="File not found") content_length = path.stat().st_size with open(file_path, "rb") as f: return await self.upload_file( bucket_id=bucket_id, object_key=object_key, data=f, content_length=content_length, content_type=content_type, metadata=metadata ) async def create_presigned_url( self, bucket_id: int, object_key: str, operation: str = "put", expires_in_seconds: int = 3600 ) -> str: """ Create a presigned URL for direct upload/download. Client can upload directly to storage node without going through API. """ # Verify object exists async with self.db.acquire() as conn: if operation == "put": # For new uploads, verify bucket bucket = await conn.fetchrow( "SELECT * FROM buckets WHERE id = $1", bucket_id ) if not bucket: raise ValueError("Bucket not found") object_id = None else: # For existing objects obj = await conn.fetchrow( """SELECT * FROM objects WHERE bucket_id = $1 AND object_key = $2 AND is_latest = TRUE""", bucket_id, object_key ) if not obj: raise ValueError("Object not found") object_id = obj["id"] # Generate presigned URL key access_key = f"presigned:{uuid.uuid4().hex}" expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in_seconds) async with self.db.acquire() as conn: await conn.execute( """INSERT INTO presigned_urls (object_id, access_key, expires_at, operation) VALUES ($1, $2, $3, $4)""", object_id, access_key, expires_at, operation ) # Return URL # In production, this would be your API gateway URL return f"https://storage.example.com/v1/upload/{access_key}" async def verify_presigned_url( self, access_key: str, operation: str ) -> Optional[Dict[str, Any]]: """Verify a presigned URL is valid.""" async with self.db.acquire() as conn: record = await conn.fetchrow( """SELECT pu.*, o.bucket_id, o.object_key FROM presigned_urls pu LEFT JOIN objects o ON o.id = pu.object_id WHERE pu.access_key = $1 AND pu.operation = $2 AND pu.expires_at > NOW()""", access_key, operation ) if not record: return None return { "bucket_id": record["bucket_id"], "object_key": record["object_key"], "object_id": record["object_id"], "operation": record["operation"] } async def get_upload_progress( self, upload_id: str ) -> Optional[UploadProgress]: """Get progress of an ongoing upload.""" # For multipart uploads async with self.db.acquire() as conn: upload = await conn.fetchrow( """SELECT mu.*, (SELECT COUNT(*) FROM multipart_parts mp WHERE mp.upload_id = mu.upload_id) as completed_parts FROM multipart_uploads mu WHERE mu.upload_id = $1""", upload_id ) if not upload: return None total_parts = upload.get("total_parts") or upload["completed_parts"] + 1 completed = upload["completed_parts"] return UploadProgress( bytes_uploaded=completed * 5 * 1024 * 1024, # Assume 5MB parts total_bytes=total_parts * 5 * 1024 * 1024, percentage=(completed / total_parts * 100) if total_parts > 0 else 0, current_part=completed + 1 ) async def complete_upload( self, upload_id: str ) -> UploadResult: """Complete a multipart upload.""" # Implementation in multipart upload subtask pass async def abort_upload( self, upload_id: str ) -> bool: """Abort a multipart upload.""" async with self.db.acquire() as conn: # Get upload info upload = await conn.fetchrow( "SELECT * FROM multipart_uploads WHERE upload_id = $1", upload_id ) if not upload: return False # Delete uploaded parts await conn.execute( "DELETE FROM multipart_parts WHERE upload_id = $1", upload_id ) # Delete upload record await conn.execute( "DELETE FROM multipart_uploads WHERE upload_id = $1", upload_id ) # Clean up files from storage parts = await conn.fetch( """SELECT mp.*, o.storage_nodes FROM multipart_parts mp JOIN objects o ON o.id = mp.object_id WHERE mp.upload_id = $1""", upload_id ) for part in parts: node_ids = json.loads(part["storage_nodes"]) for node_id in node_ids: await self.storage.delete_file( node_id=node_id, file_path=str(part["id"]) ) return True async def _verify_bucket(self, bucket_id: int) -> Optional[dict]: """Verify bucket exists and is accessible.""" async with self.db.acquire() as conn: return await conn.fetchrow( "SELECT * FROM buckets WHERE id = $1", bucket_id ) async def _log_operation( self, bucket_id: int = None, object_id: int = None, operation: str = None, user_id: str = None, bytes_received: int = None, http_status: int = None, error_code: str = None ): """Log operation to audit table.""" async with self.db.acquire() as conn: await conn.execute( """INSERT INTO audit_log (bucket_id, object_id, operation, user_id, bytes_received, http_status, error_code) VALUES ($1, $2, $3, $4, $5, $6, $7)""", bucket_id, object_id, operation, user_id, bytes_received, http_status, error_code ) ``` **Storage adapter interface**: ```python from abc import ABC, abstractmethod from typing import Optional class StorageAdapter(ABC): """Interface for storage backends.""" @abstractmethod async def write_file( self, node_id: str, bucket_name: str, object_key: str, data: bytes ) -> str: """Write file to storage node. Returns file path.""" pass @abstractmethod async def read_file( self, node_id: str, file_path: str ) -> bytes: """Read file from storage node.""" pass @abstractmethod async def delete_file( self, node_id: str, file_path: str ) -> bool: """Delete file from storage node.""" pass @abstractmethod async def file_exists( self, node_id: str, file_path: str ) -> bool: """Check if file exists on node.""" pass @abstractmethod async def get_file_info( self, node_id: str, file_path: str ) -> dict: """Get file metadata from node.""" pass ``` **Local filesystem storage adapter**: ```python import aiofiles import shutil from pathlib import Path class LocalStorageAdapter(StorageAdapter): """Local filesystem storage adapter.""" def __init__(self, base_path: str = "/data/storage"): self.base_path = Path(base_path) self.base_path.mkdir(parents=True, exist_ok=True) async def write_file( self, node_id: str, bucket_name: str, object_key: str, data: bytes ) -> str: """Write file to local filesystem.""" # Create path: /data/storage/{node_id}/{bucket}/{object_key} file_path = self.base_path / node_id / bucket_name / object_key file_path.parent.mkdir(parents=True, exist_ok=True) async with aiofiles.open(file_path, "wb") as f: await f.write(data) return str(file_path) async def read_file(self, node_id: str, file_path: str) -> bytes: """Read file from local filesystem.""" async with aiofiles.open(file_path, "rb") as f: return await f.read() async def delete_file(self, node_id: str, file_path: str) -> bool: """Delete file from local filesystem.""" path = Path(file_path) if path.exists(): path.unlink() return True return False async def file_exists(self, node_id: str, file_path: str) -> bool: """Check if file exists.""" return Path(file_path).exists() async def get_file_info(self, node_id: str, file_path: str) -> dict: """Get file metadata.""" path = Path(file_path) if not path.exists(): return None stat = path.stat() return { "size": stat.st_size, "modified": stat.st_mtime, "created": stat.st_ctime } ``` **Upload API endpoints**: ```python from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Header from typing import Optional router = APIRouter(prefix="/v1", tags=["upload"]) @router.put("/buckets/{bucket_id}/objects/{object_key:path}") async def upload_object( bucket_id: int, object_key: str, file: UploadFile = File(...), content_type: Optional[str] = Header(None), content_md5: Optional[str] = Header(None), metadata: Optional[str] = Form(None) # JSON string ): """Upload an object to a bucket.""" upload_service = get_upload_service() # Parse metadata user_metadata = json.loads(metadata) if metadata else None # Read file data content = await file.read() content_length = len(content) # Verify MD5 if provided if content_md5: calculated_md5 = hashlib.md5(content).hexdigest() if calculated_md5 != content_md5: raise HTTPException( status_code=400, detail=f"MD5 mismatch. Expected: {content_md5}, Got: {calculated_md5}" ) # Create file-like object from io import BytesIO data_stream = BytesIO(content) # Upload result = await upload_service.upload_file( bucket_id=bucket_id, object_key=object_key, data=data_stream, content_length=content_length, content_type=content_type or file.content_type, metadata=user_metadata ) if not result.success: raise HTTPException(status_code=400, detail=result.error) return { "object_id": result.object_id, "version_id": result.version_id, "etag": result.etag, "location": result.location } @router.post("/buckets/{bucket_id}/uploads/presign") async def create_presigned_upload( bucket_id: int, object_key: str, expires_in: int = 3600 ): """Create a presigned URL for direct upload.""" upload_service = get_upload_service() url = await upload_service.create_presigned_url( bucket_id=bucket_id, object_key=object_key, operation="put", expires_in_seconds=expires_in ) return {"upload_url": url, "expires_in": expires_in} @router.post("/uploads/presigned/{access_key}") async def upload_via_presigned_url( access_key: str, file: UploadFile = File(...) ): """Handle presigned URL upload.""" upload_service = get_upload_service() # Verify presigned URL presigned = await upload_service.verify_presigned_url(access_key, "put") if not presigned: raise HTTPException(status_code=403, detail="Invalid or expired presigned URL") # Read and upload file content = await file.read() from io import BytesIO result = await upload_service.upload_file( bucket_id=presigned["bucket_id"], object_key=presigned["object_key"], data=BytesIO(content), content_length=len(content), content_type=file.content_type ) if not result.success: raise HTTPException(status_code=400, detail=result.error) return {"etag": result.etag} ``` ## Acceptance Criteria - [ ] Files can be uploaded to buckets - [ ] MD5 checksum is verified - [ ] Files are replicated to storage nodes - [ ] Presigned URLs work for direct uploads - [ ] Bucket quota is enforced - [ ] Upload progress is tracked - [ ] Failed uploads don't leave orphaned files ## Notes **Trade-offs**: - Streaming vs full read in memory: Streaming for large files - Direct-to-node vs proxy through API: Presigned URL for direct upload **Performance**: - Use streaming for files > 100MB - Parallel multipart uploads for large files **Alternatives considered**: - Direct S3 upload: Complex setup - Tus.io protocol: Overkill for MVP