Stream uploads and downloads in 1 MB blocks so memory use does not grow with file size, under both WSGI and ASGI. - S3 multipart upload API (create, upload part, list parts, complete, abort), so boto3 upload_file works for files over 8 MB. - Browser uploader on the studio page: sends 16 MB parts three at a time with retries, and resumes when the same file is picked again. Uses session-authenticated, CSRF-protected JSON endpoints under /studio/<bucket>/uploads/. - Request bodies are checked against the signed X-Amz-Content-Sha256 instead of being read into memory; signed requests must include it. boto3's aws-chunked bodies with CRC32 trailers are decoded. - Objects are written to a temporary file and renamed into place, so a failed upload leaves the existing file intact. - Downloads stream with FileResponse, or an async iterator under ASGI. - SigV4 verification uses the encoded path, fixing keys with spaces. - cleanup_uploads command removes abandoned uploads and temp files. - DATA_UPLOAD_MAX_MEMORY_SIZE is capped at 10 MB again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
80 lines
3.2 KiB
Python
80 lines
3.2 KiB
Python
import time
|
|
import uuid
|
|
from datetime import timedelta
|
|
|
|
from django.conf import settings
|
|
from django.core.management.base import BaseCommand
|
|
from django.db.models import Max
|
|
from django.db.models.functions import Coalesce, Greatest
|
|
from django.utils import timezone
|
|
|
|
from privatestudio.studio import uploads
|
|
from privatestudio.studio.models import MultipartUpload, UploadStatus
|
|
from privatestudio.studio.storage import LockBusy, UploadGone, get_storage
|
|
|
|
TEMP_AGE_SECONDS = 24 * 3600
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = "Remove abandoned uploads, orphaned part directories and old temporary files."
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument("--days", type=int, default=settings.PRIVATESTUDIO_UPLOAD_EXPIRY_DAYS,
|
|
help="Remove uploads without activity for this many days (default %(default)s)")
|
|
parser.add_argument("--dry-run", action="store_true", help="Only report what would be removed")
|
|
|
|
def handle(self, *args, days, dry_run, **options):
|
|
storage = get_storage()
|
|
cutoff = timezone.now() - timedelta(days=days)
|
|
verb = "Would remove" if dry_run else "Removed"
|
|
|
|
expired = MultipartUpload.objects.annotate(
|
|
last_activity=Greatest("created_at", Coalesce(Max("parts__uploaded_at"), "created_at")),
|
|
).filter(last_activity__lt=cutoff)
|
|
for upload in expired:
|
|
if not dry_run:
|
|
if upload.status == UploadStatus.ACTIVE:
|
|
try:
|
|
uploads.abort(upload)
|
|
except uploads.UploadError as e:
|
|
self.stdout.write(f"Skipped {upload}: {e.message}")
|
|
continue
|
|
storage.remove_upload(upload.upload_id)
|
|
upload.delete()
|
|
self.stdout.write(f"{verb} upload {upload.upload_id} {upload}")
|
|
|
|
old = time.time() - TEMP_AGE_SECONDS
|
|
for path in self.children(storage.multipart_path):
|
|
try:
|
|
upload_id = uuid.UUID(path.name)
|
|
except ValueError:
|
|
continue
|
|
if path.stat().st_mtime > old:
|
|
continue
|
|
if MultipartUpload.objects.filter(upload_id=upload_id, status=UploadStatus.ACTIVE).exists():
|
|
continue
|
|
if not dry_run:
|
|
try:
|
|
with storage.lock_upload(upload_id, timeout=0):
|
|
storage.remove_upload(upload_id)
|
|
except LockBusy:
|
|
continue
|
|
except UploadGone:
|
|
storage.remove_upload(upload_id)
|
|
self.stdout.write(f"{verb} directory {path.name}")
|
|
|
|
# Writes move a file's mtime, so an upload in progress is never this old.
|
|
for path in [*self.children(storage.temp_path), *storage.multipart_path.glob("*/*.tmp")]:
|
|
try:
|
|
stale = path.stat().st_mtime < old
|
|
if stale and not dry_run:
|
|
path.unlink()
|
|
except FileNotFoundError:
|
|
continue
|
|
if stale:
|
|
self.stdout.write(f"{verb} temporary file {path.name}")
|
|
|
|
@staticmethod
|
|
def children(directory):
|
|
return list(directory.iterdir()) if directory.is_dir() else []
|