595 lines
19 KiB
Markdown
595 lines
19 KiB
Markdown
# Subtask: File Download API
|
|
|
|
**Parent Task**: Decomp/005
|
|
**Subtask ID**: Decomp/005-06
|
|
**Dependencies**: Decomp-005-01 (Storage Architecture), Decomp-005-05 (Access Control)
|
|
|
|
## Description
|
|
|
|
Implement file download API supporting range requests, direct-from-node streaming, presigned URLs, and download tracking.
|
|
|
|
## Requirements
|
|
|
|
- Download files from buckets
|
|
- Support HTTP range requests for partial content
|
|
- Stream directly from storage nodes
|
|
- Track download metrics
|
|
- Generate presigned download URLs
|
|
- Handle HEAD requests (metadata only)
|
|
- Support conditional downloads (ETag, If-Modified-Since)
|
|
- Response caching headers
|
|
|
|
## Technical Specifications
|
|
|
|
**Download service**:
|
|
```python
|
|
from typing import Optional, Dict, Any, Tuple
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timezone, timedelta
|
|
from pathlib import Path
|
|
import logging
|
|
import asyncio
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
@dataclass
|
|
class ObjectMetadata:
|
|
"""Metadata about an object."""
|
|
object_id: int
|
|
bucket_id: int
|
|
bucket_name: str
|
|
object_key: str
|
|
version_id: str
|
|
content_type: str
|
|
content_length: int
|
|
etag: str
|
|
last_modified: datetime
|
|
metadata: Dict[str, Any]
|
|
storage_nodes: List[str]
|
|
|
|
@dataclass
|
|
class DownloadResult:
|
|
"""Result of download preparation."""
|
|
success: bool
|
|
metadata: ObjectMetadata = None
|
|
node_url: str = None
|
|
error: str = None
|
|
|
|
class FileDownloadService:
|
|
"""Service for handling file downloads."""
|
|
|
|
def __init__(
|
|
self,
|
|
db,
|
|
storage_adapter,
|
|
access_service,
|
|
hash_ring
|
|
):
|
|
self.db = db
|
|
self.storage = storage_adapter
|
|
self.access = access_service
|
|
self.hash_ring = hash_ring
|
|
|
|
async def get_object_metadata(
|
|
self,
|
|
bucket_id: int,
|
|
object_key: str,
|
|
version_id: str = None
|
|
) -> Optional[ObjectMetadata]:
|
|
"""Get object metadata."""
|
|
async with self.db.acquire() as conn:
|
|
query = """
|
|
SELECT o.*, b.name as bucket_name
|
|
FROM objects o
|
|
JOIN buckets b ON b.id = o.bucket_id
|
|
WHERE o.bucket_id = $1 AND o.object_key = $2
|
|
"""
|
|
params = [bucket_id, object_key]
|
|
|
|
if version_id:
|
|
query += " AND o.version_id = $3"
|
|
params.append(version_id)
|
|
else:
|
|
query += " AND o.is_latest = TRUE"
|
|
|
|
obj = await conn.fetchrow(query, *params)
|
|
|
|
if not obj:
|
|
return None
|
|
|
|
return ObjectMetadata(
|
|
object_id=obj["id"],
|
|
bucket_id=obj["bucket_id"],
|
|
bucket_name=obj["bucket_name"],
|
|
object_key=obj["object_key"],
|
|
version_id=obj["version_id"],
|
|
content_type=obj.get("content_type", "application/octet-stream"),
|
|
content_length=obj["content_length"],
|
|
etag=obj["etag"],
|
|
last_modified=obj["modified_at"],
|
|
metadata=json.loads(obj.get("user_metadata", "{}")),
|
|
storage_nodes=json.loads(obj.get("storage_nodes", "[]"))
|
|
)
|
|
|
|
async def prepare_download(
|
|
self,
|
|
bucket_id: int,
|
|
object_key: str,
|
|
user_id: str = None,
|
|
version_id: str = None,
|
|
presigned_key: str = None
|
|
) -> DownloadResult:
|
|
"""
|
|
Prepare a file for download.
|
|
|
|
Returns metadata and the URL to download from (can redirect to storage node).
|
|
"""
|
|
# Check presigned URL access
|
|
if presigned_key:
|
|
valid = await self._verify_presigned_download(presigned_key)
|
|
if not valid:
|
|
return DownloadResult(
|
|
success=False,
|
|
error="Presigned URL invalid or expired"
|
|
)
|
|
else:
|
|
# Check user permissions
|
|
if user_id:
|
|
# Check permission
|
|
has_access = await self.access.check_permission(
|
|
user_id=user_id,
|
|
resource_type="object",
|
|
resource_id=f"{bucket_id}:{object_key}", # Approximate
|
|
required_permission=Permission.READ
|
|
)
|
|
if not has_access:
|
|
return DownloadResult(
|
|
success=False,
|
|
error="Access denied"
|
|
)
|
|
else:
|
|
# Check for public access
|
|
obj = await self.get_object_metadata(bucket_id, object_key, version_id)
|
|
if not obj:
|
|
return DownloadResult(success=False, error="Object not found")
|
|
|
|
is_public = await self._is_public(obj.object_id)
|
|
if not is_public:
|
|
return DownloadResult(
|
|
success=False,
|
|
error="Authentication required"
|
|
)
|
|
|
|
# Get object metadata
|
|
metadata = await self.get_object_metadata(bucket_id, object_key, version_id)
|
|
|
|
if not metadata:
|
|
return DownloadResult(success=False, error="Object not found")
|
|
|
|
# Select best storage node for download
|
|
# Prefer local node or fastest responding node
|
|
node_id = await self._select_download_node(metadata.storage_nodes)
|
|
|
|
# Generate download URL
|
|
# In production, this would be the actual storage node URL
|
|
node_url = f"http://{node_id}:8080/files/{metadata.bucket_name}/{metadata.object_key}"
|
|
|
|
# Update access time
|
|
async with self.db.acquire() as conn:
|
|
await conn.execute(
|
|
"UPDATE objects SET accessed_at = NOW() WHERE id = $1",
|
|
metadata.object_id
|
|
)
|
|
|
|
return DownloadResult(
|
|
success=True,
|
|
metadata=metadata,
|
|
node_url=node_url
|
|
)
|
|
|
|
async def read_file_data(
|
|
self,
|
|
bucket_id: int,
|
|
object_key: str,
|
|
range_header: str = None
|
|
) -> Tuple[Optional[ObjectMetadata], Optional[bytes], Dict[str, str]]:
|
|
"""
|
|
Read file data directly (for streaming response).
|
|
|
|
Returns (metadata, data, headers).
|
|
"""
|
|
metadata = await self.get_object_metadata(bucket_id, object_key)
|
|
|
|
if not metadata:
|
|
return None, None, {}
|
|
|
|
# Parse range header
|
|
content_range = None
|
|
status_code = 200
|
|
|
|
if range_header:
|
|
start, end = self._parse_range_header(range_header, metadata.content_length)
|
|
if start is not None:
|
|
# Read partial content
|
|
node_id = await self._select_download_node(metadata.storage_nodes)
|
|
file_path = f"{metadata.bucket_name}/{metadata.object_key}"
|
|
|
|
all_data = await self.storage.read_file(node_id, file_path)
|
|
data = all_data[start:end+1]
|
|
|
|
headers = {
|
|
"Content-Type": metadata.content_type,
|
|
"Content-Length": str(len(data)),
|
|
"Content-Range": f"bytes {start}-{end}/{metadata.content_length}",
|
|
"ETag": metadata.etag,
|
|
"Last-Modified": metadata.last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT")
|
|
}
|
|
status_code = 206
|
|
return metadata, data, headers
|
|
|
|
# Read full file
|
|
node_id = await self._select_download_node(metadata.storage_nodes)
|
|
file_path = f"{metadata.bucket_name}/{metadata.object_key}"
|
|
data = await self.storage.read_file(node_id, file_path)
|
|
|
|
headers = {
|
|
"Content-Type": metadata.content_type,
|
|
"Content-Length": str(metadata.content_length),
|
|
"Content-Disposition": f'inline; filename="{Path(metadata.object_key).name}"',
|
|
"ETag": metadata.etag,
|
|
"Last-Modified": metadata.last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT"),
|
|
"Cache-Control": "private, max-age=3600",
|
|
"Accept-Ranges": "bytes"
|
|
}
|
|
|
|
return metadata, data, headers
|
|
|
|
async def create_presigned_download_url(
|
|
self,
|
|
bucket_id: int,
|
|
object_key: str,
|
|
expires_in_seconds: int = 3600,
|
|
version_id: str = None
|
|
) -> str:
|
|
"""Create a presigned URL for download."""
|
|
# Verify object exists and get ID
|
|
metadata = await self.get_object_metadata(bucket_id, object_key, version_id)
|
|
|
|
if not metadata:
|
|
raise ValueError("Object not found")
|
|
|
|
# Generate presigned key
|
|
import uuid
|
|
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, 'get')""",
|
|
metadata.object_id, access_key, expires_at
|
|
)
|
|
|
|
return f"https://storage.example.com/v1/download/{access_key}"
|
|
|
|
async def _verify_presigned_download(self, access_key: str) -> bool:
|
|
"""Verify a presigned download URL."""
|
|
async with self.db.acquire() as conn:
|
|
record = await conn.fetchrow(
|
|
"""SELECT pu.*
|
|
FROM presigned_urls pu
|
|
WHERE pu.access_key = $1
|
|
AND pu.operation = 'get'
|
|
AND pu.expires_at > NOW()""",
|
|
access_key
|
|
)
|
|
|
|
return record is not None
|
|
|
|
async def _is_public(self, object_id: int) -> bool:
|
|
"""Check if object is publicly accessible."""
|
|
async with self.db.acquire() as conn:
|
|
return await conn.fetchval(
|
|
"""SELECT EXISTS(
|
|
SELECT 1 FROM acls
|
|
WHERE resource_type = 'object'
|
|
AND resource_id = $1
|
|
AND grantee_type = 'all'
|
|
AND permission = 'read'
|
|
)""",
|
|
object_id
|
|
)
|
|
|
|
async def _select_download_node(self, node_ids: List[str]) -> str:
|
|
"""Select the best node for download."""
|
|
if not node_ids:
|
|
raise ValueError("No storage nodes available")
|
|
|
|
# Simple round-robin or random selection
|
|
# In production, would consider:
|
|
# - Node proximity/location
|
|
# - Current load
|
|
# - Health status
|
|
# - Network latency
|
|
|
|
import random
|
|
return random.choice(node_ids)
|
|
|
|
def _parse_range_header(
|
|
self,
|
|
range_header: str,
|
|
content_length: int
|
|
) -> Tuple[Optional[int], Optional[int]]:
|
|
"""
|
|
Parse HTTP Range header.
|
|
|
|
Returns (start, end) tuple or (None, None) if invalid.
|
|
Supports format: "bytes=start-end"
|
|
"""
|
|
if not range_header.startswith("bytes="):
|
|
return None, None
|
|
|
|
try:
|
|
range_spec = range_header[6:] # Remove "bytes="
|
|
|
|
if "-" not in range_spec:
|
|
return None, None
|
|
|
|
start_str, end_str = range_spec.split("-", 1)
|
|
|
|
start = int(start_str) if start_str else 0
|
|
|
|
if end_str:
|
|
end = int(end_str)
|
|
else:
|
|
end = content_length - 1
|
|
|
|
# Validate range
|
|
if start < 0 or end >= content_length or start > end:
|
|
return None, None
|
|
|
|
return start, end
|
|
|
|
except (ValueError, IndexError):
|
|
return None, None
|
|
|
|
async def log_download(
|
|
self,
|
|
bucket_id: int,
|
|
object_id: int,
|
|
user_id: str = None,
|
|
bytes_sent: int = None,
|
|
http_status: int = None
|
|
):
|
|
"""Log download 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_sent, http_status)
|
|
VALUES ($1, $2, 'GET', $3, $4, $5)""",
|
|
bucket_id, object_id, user_id, bytes_sent, http_status
|
|
)
|
|
```
|
|
|
|
**Download API endpoints**:
|
|
```python
|
|
from fastapi import APIRouter, Response, Request, HTTPException, Header, Query
|
|
from fastapi.responses import StreamingResponse, RedirectResponse
|
|
from typing import Optional
|
|
|
|
router = APIRouter(prefix="/v1", tags=["download"])
|
|
|
|
@router.head("/buckets/{bucket_id}/objects/{object_key:path}")
|
|
async def head_object(
|
|
bucket_id: int,
|
|
object_key: str,
|
|
version_id: Optional[str] = None,
|
|
if_match: Optional[str] = Header(None), # ETag match
|
|
if_none_match: Optional[str] = Header(None), # ETag none match
|
|
auth_context: AuthContext = Depends(get_auth_context)
|
|
):
|
|
"""Get object metadata without downloading."""
|
|
download_service = get_download_service()
|
|
|
|
result = await download_service.prepare_download(
|
|
bucket_id=bucket_id,
|
|
object_key=object_key,
|
|
user_id=auth_context.user_id,
|
|
version_id=version_id
|
|
)
|
|
|
|
if not result.success:
|
|
if result.error == "Access denied":
|
|
raise HTTPException(status_code=403, detail=result.error)
|
|
raise HTTPException(status_code=404, detail=result.error)
|
|
|
|
metadata = result.metadata
|
|
|
|
# Check conditional requests
|
|
if if_none_match and if_none_match == metadata.etag:
|
|
return Response(status_code=304)
|
|
|
|
if if_match and if_match != metadata.etag:
|
|
raise HTTPException(status_code=412, detail="Precondition Failed")
|
|
|
|
return Response(
|
|
content_type=metadata.content_type,
|
|
headers={
|
|
"Content-Length": str(metadata.content_length),
|
|
"ETag": metadata.etag,
|
|
"Last-Modified": metadata.last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT"),
|
|
"Cache-Control": "private, max-age=3600",
|
|
"Accept-Ranges": "bytes"
|
|
}
|
|
)
|
|
|
|
@router.get("/buckets/{bucket_id}/objects/{object_key:path}")
|
|
async def download_object(
|
|
bucket_id: int,
|
|
object_key: str,
|
|
version_id: Optional[str] = None,
|
|
range: Optional[str] = Header(None),
|
|
if_match: Optional[str] = Header(None),
|
|
if_none_match: Optional[str] = Header(None),
|
|
auth_context: AuthContext = Depends(get_auth_context)
|
|
):
|
|
"""Download an object."""
|
|
download_service = get_download_service()
|
|
|
|
# Check conditional requests first
|
|
metadata = await download_service.get_object_metadata(bucket_id, object_key, version_id)
|
|
|
|
if not metadata:
|
|
raise HTTPException(status_code=404, detail="Object not found")
|
|
|
|
if if_none_match and if_none_match == metadata.etag:
|
|
return Response(status_code=304)
|
|
|
|
if if_match and if_match != metadata.etag:
|
|
raise HTTPException(status_code=412, detail="Precondition Failed")
|
|
|
|
# Prepare download
|
|
result = await download_service.prepare_download(
|
|
bucket_id=bucket_id,
|
|
object_key=object_key,
|
|
user_id=auth_context.user_id,
|
|
version_id=version_id
|
|
)
|
|
|
|
if not result.success:
|
|
if result.error == "Access denied":
|
|
raise HTTPException(status_code=403, detail=result.error)
|
|
raise HTTPException(status_code=404, detail=result.error)
|
|
|
|
# Get file data
|
|
obj_metadata, data, headers = await download_service.read_file_data(
|
|
bucket_id=bucket_id,
|
|
object_key=object_key,
|
|
range_header=range
|
|
)
|
|
|
|
if not obj_metadata:
|
|
raise HTTPException(status_code=404, detail="Object not found")
|
|
|
|
# Determine status code
|
|
status_code = 206 if range and "Content-Range" in headers else 200
|
|
|
|
# Log download
|
|
await download_service.log_download(
|
|
bucket_id=bucket_id,
|
|
object_id=obj_metadata.object_id,
|
|
user_id=auth_context.user_id,
|
|
bytes_sent=len(data),
|
|
http_status=status_code
|
|
)
|
|
|
|
return Response(
|
|
content=data,
|
|
status_code=status_code,
|
|
media_type=obj_metadata.content_type,
|
|
headers=headers
|
|
)
|
|
|
|
@router.get("/download/{access_key}")
|
|
async def download_via_presigned_url(
|
|
access_key: str,
|
|
range: Optional[str] = Header(None)
|
|
):
|
|
"""Download via presigned URL (no auth required)."""
|
|
download_service = get_download_service()
|
|
|
|
# Verify presigned URL and get object info
|
|
async with download_service.db.acquire() as conn:
|
|
presigned = await conn.fetchrow(
|
|
"""SELECT pu.*, o.bucket_id, o.object_key, o.id as object_id
|
|
FROM presigned_urls pu
|
|
JOIN objects o ON o.id = pu.object_id
|
|
WHERE pu.access_key = $1
|
|
AND pu.operation = 'get'
|
|
AND pu.expires_at > NOW()""",
|
|
access_key
|
|
)
|
|
|
|
if not presigned:
|
|
raise HTTPException(status_code=403, detail="Invalid or expired presigned URL")
|
|
|
|
# Get file data
|
|
obj_metadata, data, headers = await download_service.read_file_data(
|
|
bucket_id=presigned["bucket_id"],
|
|
object_key=presigned["object_key"],
|
|
range_header=range
|
|
)
|
|
|
|
if not obj_metadata:
|
|
raise HTTPException(status_code=404, detail="Object not found")
|
|
|
|
status_code = 206 if range and "Content-Range" in headers else 200
|
|
|
|
return Response(
|
|
content=data,
|
|
status_code=status_code,
|
|
media_type=obj_metadata.content_type,
|
|
headers=headers
|
|
)
|
|
|
|
@router.post("/buckets/{bucket_id}/objects/{object_key:path}/presign")
|
|
async def create_presigned_download(
|
|
bucket_id: int,
|
|
object_key: str,
|
|
expires_in: int = Query(3600, description="URL expiration in seconds", ge=60, le=86400),
|
|
version_id: Optional[str] = None,
|
|
auth_context: AuthContext = Depends(get_auth_context)
|
|
):
|
|
"""Create a presigned download URL."""
|
|
download_service = get_download_service()
|
|
|
|
# Verify permissions
|
|
has_access = await download_service.access.check_permission(
|
|
user_id=auth_context.user_id,
|
|
resource_type="object",
|
|
resource_id=f"{bucket_id}:{object_key}",
|
|
required_permission=Permission.READ
|
|
)
|
|
|
|
if not has_access:
|
|
raise HTTPException(status_code=403, detail="Access denied")
|
|
|
|
try:
|
|
url = await download_service.create_presigned_download_url(
|
|
bucket_id=bucket_id,
|
|
object_key=object_key,
|
|
expires_in_seconds=expires_in,
|
|
version_id=version_id
|
|
)
|
|
|
|
return {"download_url": url, "expires_in": expires_in}
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=404, detail=str(e))
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
|
|
- [ ] Files can be downloaded by authorized users
|
|
- [ ] Range requests work correctly
|
|
- [ ] HEAD requests return metadata only
|
|
- [ ] Conditional requests (ETag) work
|
|
- [ ] Presigned URLs work without auth
|
|
- [ ] Downloads are logged
|
|
- [ ] Public files are accessible
|
|
|
|
## Notes
|
|
|
|
**Trade-offs**:
|
|
- Redirect vs proxy: Redirect to storage node for performance
|
|
- Synchronous vs streaming: Streaming for memory efficiency
|
|
|
|
**Performance**:
|
|
- Use CDN caching for public objects
|
|
- Implement byte-range seek for large files
|
|
- Cache metadata in Redis
|
|
|
|
**Alternatives considered**:
|
|
- CloudFront/S3 direct: Simpler but less control
|
|
- Nginx X-Accel-Redirect: Faster for large files
|